From 98dcb4f25b39a5dba28210ebb016602b6cfd8f69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A2u=20Cao?= Date: Thu, 23 Apr 2026 09:23:41 +0100 Subject: [PATCH] 1.20.1 --- package.json | 2 +- release/assets/{main-AsE4IKjj.js => main-CGySSjv6.js} | 4 ++-- .../{modules-4-12-CyDF3xZj.js => modules-4-12-CktBxFgZ.js} | 2 +- .../assets/{negentropy-Baf3_xbt.js => negentropy-CkK5_v5U.js} | 2 +- release/index.html | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) rename release/assets/{main-AsE4IKjj.js => main-CGySSjv6.js} (86%) rename release/assets/{modules-4-12-CyDF3xZj.js => modules-4-12-CktBxFgZ.js} (98%) rename release/assets/{negentropy-Baf3_xbt.js => negentropy-CkK5_v5U.js} (99%) diff --git a/package.json b/package.json index c69f3f7..78b8fc7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "marco", - "version": "1.20.0", + "version": "1.20.1", "private": true, "description": "Unhosted maps app", "repository": { diff --git a/release/assets/main-AsE4IKjj.js b/release/assets/main-CGySSjv6.js similarity index 86% rename from release/assets/main-AsE4IKjj.js rename to release/assets/main-CGySSjv6.js index f5d1905..f27d6d9 100644 --- a/release/assets/main-AsE4IKjj.js +++ b/release/assets/main-CGySSjv6.js @@ -12,5 +12,5 @@ const qC=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function DS(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function NS(...t){const e=(t,e)=>n=>t(e(n)),n=Array.from(t).reverse().reduce((t,n)=>t?e(t,n.encode):n.encode,void 0),r=t.reduce((t,n)=>t?e(t,n.decode):n.decode,void 0);return{encode:n,decode:r}}function jS(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&"number"!=typeof e[0])throw new Error("alphabet.encode input should be an array of numbers");return e.map(e=>{if(DS(e),e<0||e>=t.length)throw new Error(`Digit index outside alphabet: ${e} (alphabet: ${t.length})`);return t[e]})},decode:e=>{if(!Array.isArray(e)||e.length&&"string"!=typeof e[0])throw new Error("alphabet.decode input should be array of strings");return e.map(e=>{if("string"!=typeof e)throw new Error(`alphabet.decode: not string element=${e}`);const n=t.indexOf(e);if(-1===n)throw new Error(`Unknown letter: "${e}". Allowed: ${t}`);return n})}}}function BS(t=""){if("string"!=typeof t)throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&"string"!=typeof e[0])throw new Error("join.encode input should be array of strings");for(let t of e)if("string"!=typeof t)throw new Error(`join.encode: non-string input=${t}`);return e.join(t)},decode:e=>{if("string"!=typeof e)throw new Error("join.decode input should be string");return e.split(t)}}}function US(t,e="="){if(DS(t),"string"!=typeof e)throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let t of n)if("string"!=typeof t)throw new Error(`padding.encode: non-string input=${t}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let t of n)if("string"!=typeof t)throw new Error(`padding.decode: non-string input=${t}`);let r=n.length;if(r*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if(!((r-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function $S(t){if("function"!=typeof t)throw new Error("normalize fn should be function");return{encode:t=>t,decode:e=>t(e)}}function qS(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let r=0;const i=[],s=Array.from(t);for(s.forEach(t=>{if(DS(t),t<0||t>=e)throw new Error(`Wrong integer: ${t}`)});;){let t=0,o=!0;for(let i=r;inew FS);const VS=(t,e)=>e?VS(e,t%e):t,WS=(t,e)=>t+(e-VS(t,e));function HS(t,e,n,r){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(WS(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${WS(e,n)}`);let i=0,s=0;const o=2**n-1,a=[];for(const l of t){if(DS(l),l>=2**e)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(i=i<32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)a.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<=e)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&a.push(i>>>0),a}function GS(t,e=!1){if(DS(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(WS(8,t)>32||WS(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return HS(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(HS(n,t,8,e))}}}function KS(t){if("function"!=typeof t)throw new Error("unsafeWrapper fn should be function");return function(...e){try{return t.apply(null,e)}catch(ej){}}}const ZS=NS(GS(4),jS("0123456789ABCDEF"),BS("")),YS=NS(GS(5),jS("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),US(5),BS(""));NS(GS(5),jS("0123456789ABCDEFGHIJKLMNOPQRSTUV"),US(5),BS("")),NS(GS(5),jS("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),BS(""),$S(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const XS=NS(GS(6),jS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),US(6),BS("")),JS=NS(GS(6),jS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),US(6),BS("")),QS=t=>NS((DS(58),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return qS(Array.from(t),256,58)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(qS(t,58,256))}}),jS(t),BS("")),tk=QS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");QS("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),QS("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const ek=[0,2,3,5,6,7,9,10,11],nk={encode(t){let e="";for(let n=0;n>25;let n=(33554431&t)<<5;for(let r=0;r>r&1)&&(n^=ik[r]);return n}function ok(t,e,n=1){const r=t.length;let i=1;for(let s=0;s126)throw new Error(`Invalid prefix (${t})`);i=sk(i)^e>>5}i=sk(i);for(let s=0;sn)throw new TypeError(`Wrong string length: ${t.length} (${t}). Expected (8..${n})`);const r=t.toLowerCase();if(t!==r&&t!==t.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=(t=r).lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const a=rk.decode(o).slice(0,-6),l=ok(s,a,e);if(!o.endsWith(l))throw new Error(`Invalid checksum in ${t}: expected "${l}"`);return{prefix:s,words:a}}return{encode:function(t,n,r=90){if("string"!=typeof t)throw new Error("bech32.encode prefix should be string, not "+typeof t);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const i=t.length+7+n.length;if(!1!==r&&i>r)throw new TypeError(`Length ${i} exceeds limit ${r}`);return`${t=t.toLowerCase()}1${rk.encode(n)}${ok(t,n,e)}`},decode:o,decodeToBytes:function(t){const{prefix:e,words:n}=o(t,!1);return{prefix:e,words:n,bytes:r(n)}},decodeUnsafe:KS(o),fromWords:r,fromWordsUnsafe:s,toWords:i}}const lk=ak("bech32");ak("bech32m");const ck={utf8:{encode:t=>(new TextDecoder).decode(t),decode:t=>(new TextEncoder).encode(t)},hex:NS(GS(4),jS("0123456789abcdef"),BS(""),$S(t=>{if("string"!=typeof t||t.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()})),base16:ZS,base32:YS,base64:XS,base64url:JS,base58:tk,base58xmr:nk};function uk(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function hk(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}function dk(t,...e){if(!((n=t)instanceof Uint8Array||null!=n&&"object"==typeof n&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)} /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Object.keys(ck).join(", ");const pk=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");const fk=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function gk(t){dk(t);let e="";for(let n=0;n=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function yk(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i>7)}function wk(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(1&e),t=bk(t);return n}const _k=(()=>{let t=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=bk(r))t[n]=r;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return e})(),xk=_k.map((t,e)=>_k.indexOf(e)),Ck=t=>t<<24|t>>>8,Sk=t=>t<<8|t>>>24;function kk(t,e){if(256!==t.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((n,r)=>e(t[r])),r=n.map(Sk),i=r.map(Sk),s=i.map(Sk),o=new Uint32Array(65536),a=new Uint32Array(65536),l=new Uint16Array(65536);for(let c=0;c<256;c++)for(let e=0;e<256;e++){const u=256*c+e;o[u]=n[c]^r[e],a[u]=i[c]^s[e],l[u]=t[c]<<8|t[e]}return{sbox:t,sbox2:l,T0:n,T1:r,T2:i,T3:s,T01:o,T23:a}}const Ek=kk(_k,t=>wk(t,3)<<24|t<<16|t<<8|wk(t,2)),Tk=kk(xk,t=>wk(t,11)<<24|wk(t,13)<<16|wk(t,9)<<8|wk(t,14)),Rk=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=bk(n))t[e]=n;return t})();function Mk(t){dk(t);const e=t.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:n}=Ek,r=pk(t),i=r.length,s=t=>Ik(n,t,t,t,t),o=new Uint32Array(e+28);o.set(r);for(let a=i;a6&&a%i===4&&(t=s(t)),o[a]=o[a-i]^t}return o}function Lk(t,e,n,r,i,s){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|s>>>24&255]}function Ik(t,e,n,r,i){return t[255&e|65280&n]|t[r>>>16&255|i>>>16&65280]<<16}function Pk(t,e,n,r,i){const{sbox2:s,T01:o,T23:a}=Ek;let l=0;e^=t[l++],n^=t[l++],r^=t[l++],i^=t[l++];const c=t.length/4-2;for(let u=0;u{const s=Mk(t),{b:o,o:a,out:l}=function(t,e,n){let r=t.length;const i=r%vk;if(!e&&0!==i)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=pk(t);if(e){let t=vk-i;t||(t=vk),r+=t}const o=Ok(r,n);return{b:s,o:pk(o),out:o}}(n,r,i),c=pk(e);let u=c[0],h=c[1],d=c[2],p=c[3],f=0;for(;f+4<=o.length;)u^=o[f+0],h^=o[f+1],d^=o[f+2],p^=o[f+3],({s0:u,s1:h,s2:d,s3:p}=Pk(s,u,h,d,p)),a[f++]=u,a[f++]=h,a[f++]=d,a[f++]=p;if(r){const t=function(t){const e=new Uint8Array(16),n=pk(e);e.set(t);const r=vk-t.length;for(let i=vk-r;i{!function(t){if(dk(t),t.length%vk!==0)throw new Error("aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size 16")}(n);const s=function(t){const e=Mk(t),n=e.slice(),r=e.length,{sbox2:i}=Ek,{T0:s,T1:o,T2:a,T3:l}=Tk;for(let c=0;c>>8&255]^a[e>>>16&255]^l[e>>>24]}return n}(t),o=pk(e),a=Ok(n.length,i),l=pk(n),c=pk(a);let u=o[0],h=o[1],d=o[2],p=o[3];for(let t=0;t+4<=l.length;){const e=u,n=h,r=d,i=p;u=l[t+0],h=l[t+1],d=l[t+2],p=l[t+3];const{s0:o,s1:a,s2:f,s3:g}=Ak(s,u,h,d,p);c[t++]=o^e,c[t++]=a^n,c[t++]=f^r,c[t++]=g^i}return s.fill(0),function(t,e){if(!e)return t;const n=t.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=t[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=t.subarray(0,-r);for(let s=0;sUint8Array.from(t.split("").map(t=>t.charCodeAt(0))),jk=Nk("expand 16-byte k"),Bk=Nk("expand 32-byte k"),Uk=pk(jk),$k=pk(Bk);function qk(t,e){return t<>>32-e}function Vk(t){return t.byteOffset%4==0}$k.slice();const Wk=2**32-1,Hk=new Uint32Array;function Gk(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=function(t,e){if(null==e||"object"!=typeof e)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e)}(0,e);if("function"!=typeof t)throw new Error("core must be a function");return uk(i),uk(o),hk(s),hk(n),(e,a,l,c,u=0)=>{dk(e),dk(a),dk(l);const h=l.length;if(c||(c=new Uint8Array(h)),dk(c),uk(u),u<0||u>=Wk)throw new Error("arx: counter overflow");if(c.length=Wk)throw new Error("arx: counter overflow");const g=Math.min(64,l-f);if(h&&64===g){const t=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let e,n=0;n<16;n++)e=t+n,p[e]=d[e]^u[n];f+=64;continue}for(let t,e=0;e0;)d.pop().fill(0);return c}}function Kk(t,e,n,r,i,s=20){let o=t[0],a=t[1],l=t[2],c=t[3],u=e[0],h=e[1],d=e[2],p=e[3],f=e[4],g=e[5],m=e[6],y=e[7],v=i,b=n[0],w=n[1],_=n[2],x=o,C=a,S=l,k=c,E=u,T=h,R=d,M=p,L=f,I=g,P=m,A=y,O=v,F=b,z=w,D=_;for(let j=0;jr?t.create().update(n).digest():n);for(let s=0;snew Yk(t,e).update(n).digest();Xk.create=(t,e)=>new Yk(t,e);const Jk=new Uint8Array([0]),Qk=new Uint8Array;var tE=Object.defineProperty,eE=(t,e)=>{for(var n in e)tE(t,n,{get:e[n],enumerable:!0})},nE=Symbol("verified");function rE(t){if(!(t instanceof Object))return!1;if("number"!=typeof t.kind)return!1;if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if("string"!=typeof t.pubkey)return!1;if(!t.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(t.tags))return!1;for(let e=0;ehE,QueueNode:()=>uE,binarySearch:()=>cE,bytesToHex:()=>vS,hexToBytes:()=>bS,insertEventIntoAscendingList:()=>lE,insertEventIntoDescendingList:()=>aE,normalizeURL:()=>oE,utf8Decoder:()=>iE,utf8Encoder:()=>sE});var iE=new TextDecoder("utf-8"),sE=new TextEncoder;function oE(t){try{-1===t.indexOf("://")&&(t="wss://"+t);let e=new URL(t);return"http:"===e.protocol?e.protocol="ws:":"https:"===e.protocol&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),("80"===e.port&&"ws:"===e.protocol||"443"===e.port&&"wss:"===e.protocol)&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch(ej){throw new Error(`Invalid URL: ${t}`)}}function aE(t,e){const[n,r]=cE(t,t=>e.id===t.id?0:e.created_at===t.created_at?-1:t.created_at-e.created_at);return r||t.splice(n,0,e),t}function lE(t,e){const[n,r]=cE(t,t=>e.id===t.id?0:e.created_at===t.created_at?-1:e.created_at-t.created_at);return r||t.splice(n,0,e),t}function cE(t,e){let n=0,r=t.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=e(t[i]);if(0===s)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var uE=class{value;next=null;prev=null;constructor(t){this.value=t}},hE=class{first;last;constructor(){this.first=null,this.last=null}enqueue(t){const e=new uE(t);return this.last?this.last===this.first?(this.last=e,this.last.prev=this.first,this.first.next=e):(e.prev=this.last,this.last.next=e,this.last=e):(this.first=e,this.last=e),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const t=this.first;return this.first=t.next,this.first&&(this.first.prev=null),t.value}};function dE(t){return vS(zS(sE.encode(function(t){if(!rE(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}(t))))}var pE=new class{generateSecretKey(){return dS.utils.randomPrivateKey()}getPublicKey(t){return vS(dS.getPublicKey(t))}finalizeEvent(t,e){const n=t;return n.pubkey=vS(dS.getPublicKey(e)),n.id=dE(n),n.sig=vS(dS.sign(dE(n),e)),n[nE]=!0,n}verifyEvent(t){if("boolean"==typeof t[nE])return t[nE];const e=dE(t);if(e!==t.id)return t[nE]=!1,!1;try{const n=dS.verify(t.sig,e,t.pubkey);return t[nE]=n,n}catch(n){return t[nE]=!1,!1}}},fE=pE.generateSecretKey,gE=pE.getPublicKey,mE=pE.finalizeEvent,yE=pE.verifyEvent,vE={};function bE(t){return t<1e4&&0!==t&&3!==t}function wE(t){return 0===t||3===t||1e4<=t&&t<2e4}function _E(t){return 2e4<=t&&t<3e4}function xE(t){return 3e4<=t&&t<4e4}function CE(t){return bE(t)?"regular":wE(t)?"replaceable":_E(t)?"ephemeral":xE(t)?"parameterized":"unknown"}function SE(t,e){const n=e instanceof Array?e:[e];return rE(t)&&n.includes(t.kind)||!1}eE(vE,{Application:()=>ZT,BadgeAward:()=>AE,BadgeDefinition:()=>$T,BlockedRelaysList:()=>_T,BlossomServerList:()=>RT,BookmarkList:()=>vT,Bookmarksets:()=>jT,Calendar:()=>nR,CalendarEventRSVP:()=>rR,ChannelCreation:()=>qE,ChannelHideMessage:()=>HE,ChannelMessage:()=>WE,ChannelMetadata:()=>VE,ChannelMuteUser:()=>GE,ChatMessage:()=>OE,ClassifiedListing:()=>JT,ClientAuth:()=>IT,Comment:()=>JE,CommunitiesList:()=>bT,CommunityDefinition:()=>aR,CommunityPostApproval:()=>oT,Contacts:()=>RE,CreateOrUpdateProduct:()=>WT,CreateOrUpdateStall:()=>VT,Curationsets:()=>BT,Date:()=>tR,DirectMessageRelaysList:()=>ET,DraftClassifiedListing:()=>QT,DraftLong:()=>GT,Emojisets:()=>KT,EncryptedDirectMessage:()=>ME,EventDeletion:()=>LE,FavoriteRelays:()=>CT,FileMessage:()=>NE,FileMetadata:()=>XE,FileServerPreference:()=>TT,Followsets:()=>zT,ForumThread:()=>FE,GenericRepost:()=>jE,Genericlists:()=>DT,GiftWrap:()=>ZE,GroupMetadata:()=>lR,HTTPAuth:()=>FT,Handlerinformation:()=>oR,Handlerrecommendation:()=>sR,Highlights:()=>pT,InterestsList:()=>ST,Interestsets:()=>qT,JobFeedback:()=>cT,JobRequest:()=>aT,JobResult:()=>lT,Label:()=>sT,LightningPubRPC:()=>LT,LiveChatMessage:()=>QE,LiveEvent:()=>YT,LongFormArticle:()=>HT,Metadata:()=>kE,Mutelist:()=>gT,NWCWalletInfo:()=>MT,NWCWalletRequest:()=>PT,NWCWalletResponse:()=>AT,NormalVideo:()=>UE,NostrConnect:()=>OT,OpenTimestamps:()=>KE,Photo:()=>BE,Pinlist:()=>mT,Poll:()=>YE,PollResponse:()=>fT,PrivateDirectMessage:()=>DE,ProblemTracker:()=>nT,ProfileBadges:()=>UT,PublicChatsList:()=>wT,Reaction:()=>PE,RecommendRelay:()=>TE,RelayList:()=>yT,RelayReview:()=>iR,Relaysets:()=>NT,Report:()=>rT,Reporting:()=>iT,Repost:()=>IE,Seal:()=>zE,SearchRelaysList:()=>xT,ShortTextNote:()=>EE,ShortVideo:()=>$E,Time:()=>eR,UserEmojiList:()=>kT,UserStatuses:()=>XT,Voice:()=>tT,VoiceComment:()=>eT,Zap:()=>dT,ZapGoal:()=>uT,ZapRequest:()=>hT,classifyKind:()=>CE,isAddressableKind:()=>xE,isEphemeralKind:()=>_E,isKind:()=>SE,isRegularKind:()=>bE,isReplaceableKind:()=>wE});var kE=0,EE=1,TE=2,RE=3,ME=4,LE=5,IE=6,PE=7,AE=8,OE=9,FE=11,zE=13,DE=14,NE=15,jE=16,BE=20,UE=21,$E=22,qE=40,VE=41,WE=42,HE=43,GE=44,KE=1040,ZE=1059,YE=1068,XE=1063,JE=1111,QE=1311,tT=1222,eT=1244,nT=1971,rT=1984,iT=1984,sT=1985,oT=4550,aT=5999,lT=6999,cT=7e3,uT=9041,hT=9734,dT=9735,pT=9802,fT=1018,gT=1e4,mT=10001,yT=10002,vT=10003,bT=10004,wT=10005,_T=10006,xT=10007,CT=10012,ST=10015,kT=10030,ET=10050,TT=10096,RT=10063,MT=13194,LT=21e3,IT=22242,PT=23194,AT=23195,OT=24133,FT=27235,zT=3e4,DT=30001,NT=30002,jT=30003,BT=30004,UT=30008,$T=30009,qT=30015,VT=30017,WT=30018,HT=30023,GT=30024,KT=30030,ZT=30078,YT=30311,XT=30315,JT=30402,QT=30403,tR=31922,eR=31923,nR=31924,rR=31925,iR=31987,sR=31989,oR=31990,aR=34550,lR=39e3;function cR(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,i=t.slice(r).indexOf('"')+r+1;return t.slice(i,i+64)}function uR(t,e){let n=e.length,r=t.indexOf(`"${e}":`)+n+3,i=t.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function hR(t){let e=t.slice(0,22).indexOf('"EVENT"');if(-1===e)return null;let n=t.slice(e+7+1).indexOf('"');if(-1===n)return null;let r=e+7+1+n,i=t.slice(r+1,80).indexOf('"');if(-1===i)return null;let s=r+1+i;return t.slice(r+1,s)}function dR(t,e){return e===cR(t,"id")}function pR(t,e){return e===cR(t,"pubkey")}function fR(t,e){return e===uR(t,"kind")}function gR(t,e){return{kind:IT,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}eE({},{getHex64:()=>cR,getInt:()=>uR,getSubscriptionId:()=>hR,matchEventId:()=>dR,matchEventKind:()=>fR,matchEventPubkey:()=>pR}),eE({},{makeAuthEvent:()=>gR});try{WebSocket}catch{}try{WebSocket}catch{}eE({},{BECH32_REGEX:()=>vR,Bech32MaxSize:()=>yR,NostrTypeGuard:()=>mR,decode:()=>wR,decodeNostrURI:()=>bR,encodeBytes:()=>ER,naddrEncode:()=>MR,neventEncode:()=>RR,noteEncode:()=>SR,nprofileEncode:()=>TR,npubEncode:()=>CR,nsecEncode:()=>xR});var mR={isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")},yR=5e3,vR=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function bR(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),wR(t)}catch(e){return{type:"invalid",data:null}}}function wR(t){let{prefix:e,words:n}=lk.decode(t,yR),r=new Uint8Array(lk.fromWords(n));switch(e){case"nprofile":{let t=_R(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:vS(t[0][0]),relays:t[1]?t[1].map(t=>iE.decode(t)):[]}}}case"nevent":{let t=_R(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(t[2]&&32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(t[3]&&4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:vS(t[0][0]),relays:t[1]?t[1].map(t=>iE.decode(t)):[],author:t[2]?.[0]?vS(t[2][0]):void 0,kind:t[3]?.[0]?parseInt(vS(t[3][0]),16):void 0}}}case"naddr":{let t=_R(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!t[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!t[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:iE.decode(t[0][0]),pubkey:vS(t[2][0]),kind:parseInt(vS(t[3][0]),16),relays:t[1]?t[1].map(t=>iE.decode(t)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:vS(r)};default:throw new Error(`unknown prefix ${e}`)}}function _R(t){let e={},n=t;for(;n.length>0;){let t=n[0],r=n[1],i=n.slice(2,2+r);if(n=n.slice(2+r),i.lengthsE.encode(t))}))}function RR(t){let e;return void 0!==t.kind&&(e=function(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=255&t,e}(t.kind)),kR("nevent",LR({0:[bS(t.id)],1:(t.relays||[]).map(t=>sE.encode(t)),2:t.author?[bS(t.author)]:[],3:e?[new Uint8Array(e)]:[]}))}function MR(t){let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,t.kind,!1),kR("naddr",LR({0:[sE.encode(t.identifier)],1:(t.relays||[]).map(t=>sE.encode(t)),2:[bS(t.pubkey)],3:[new Uint8Array(e)]}))}function LR(t){let e=[];return Object.entries(t).reverse().forEach(([t,n])=>{n.forEach(n=>{let r=new Uint8Array(n.length+2);r.set([parseInt(t)],0),r.set([n.length],1),r.set(n,2),e.push(r)})}),_S(...e)}var IR={};function PR(t,e,n){const r=t instanceof Uint8Array?vS(t):t,i=OR(YC.getSharedSecret(r,"02"+e));let s=Uint8Array.from(SS(16)),o=sE.encode(n),a=Fk(i,s).encrypt(o);return`${XS.encode(new Uint8Array(a))}?iv=${XS.encode(new Uint8Array(s.buffer))}`}function AR(t,e,n){const r=t instanceof Uint8Array?vS(t):t;let[i,s]=n.split("?iv="),o=OR(YC.getSharedSecret(r,"02"+e)),a=XS.decode(s),l=XS.decode(i),c=Fk(o,a).decrypt(l);return iE.decode(c)}function OR(t){return t.slice(1,33)}eE(IR,{decrypt:()=>AR,encrypt:()=>PR}),eE({},{NIP05_REGEX:()=>zR,isNip05:()=>DR,isValid:()=>UR,queryProfile:()=>BR,searchDomain:()=>jR,useFetchImplementation:()=>NR});var FR,zR=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,DR=t=>zR.test(t||"");try{FR=fetch}catch(F7){}function NR(t){FR=t}async function jR(t,e=""){try{const n=`https://${t}/.well-known/nostr.json?name=${e}`,r=await FR(n,{redirect:"manual"});if(200!==r.status)throw Error("Wrong response code");return(await r.json()).names}catch(F7){return{}}}async function BR(t){const e=t.match(zR);if(!e)return null;const[,n="_",r]=e;try{const t=`https://${r}/.well-known/nostr.json?name=${n}`,e=await FR(t,{redirect:"manual"});if(200!==e.status)throw Error("Wrong response code");const i=await e.json(),s=i.names[n];return s?{pubkey:s,relays:i.relays?.[s]}:null}catch(i){return null}}async function UR(t,e){const n=await BR(e);return!!n&&n.pubkey===t}function $R(t){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=t.tags.length-1;i>=0;i--){const s=t.tags[i];if("e"===s[0]&&s[1]){const[t,i,o,a,l]=s,c={id:i,relays:o?[o]:[],author:l};if("root"===a){e.root=c;continue}if("reply"===a){e.reply=c;continue}if("mention"===a){e.mentions.push(c);continue}n?r=c:n=c,e.mentions.push(c);continue}if("q"===s[0]&&s[1]){const[t,n,r]=s;e.quotes.push({id:n,relays:r?[r]:[]})}"p"===s[0]&&s[1]&&e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]})}return e.root||(e.root=r||n||e.reply),e.reply||(e.reply=n||e.root),[e.reply,e.root].forEach(t=>{if(!t)return;let n=e.mentions.indexOf(t);if(-1!==n&&e.mentions.splice(n,1),t.author){let n=e.profiles.find(e=>e.pubkey===t.author);n&&n.relays&&(t.relays||(t.relays=[]),n.relays.forEach(e=>{-1===t.relays?.indexOf(e)&&t.relays.push(e)}),n.relays=t.relays)}}),e.mentions.forEach(t=>{if(t.author){let n=e.profiles.find(e=>e.pubkey===t.author);n&&n.relays&&(t.relays||(t.relays=[]),n.relays.forEach(e=>{-1===t.relays.indexOf(e)&&t.relays.push(e)}),n.relays=t.relays)}}),e}eE({},{parse:()=>$R}),eE({},{fetchRelayInformation:()=>VR,useFetchImplementation:()=>qR});try{fetch}catch{}function qR(){}async function VR(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}function WR(t){let e=0;for(let n=0;n<64;n+=8){const r=parseInt(t.substring(n,n+8),16);if(0!==r){e+=Math.clz32(r);break}e+=32}return e}function HR(t,e){let n=0;const r=t,i=["nonce",n.toString(),e.toString()];for(r.tags.push(i);;){const t=Math.floor((new Date).getTime()/1e3);if(t!==r.created_at&&(n=0,r.created_at=t),i[1]=(++n).toString(),r.id=GR(r),WR(r.id)>=e)break}return r}function GR(t){return vS(zS(sE.encode(JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]))))}eE({},{fastEventHash:()=>GR,getPow:()=>WR,minePow:()=>HR}),eE({},{unwrapEvent:()=>vM,unwrapManyEvents:()=>bM,wrapEvent:()=>mM,wrapManyEvents:()=>yM}),eE({},{createRumor:()=>cM,createSeal:()=>uM,createWrap:()=>hM,unwrapEvent:()=>fM,unwrapManyEvents:()=>gM,wrapEvent:()=>dM,wrapManyEvents:()=>pM});var KR={};eE(KR,{decrypt:()=>nM,encrypt:()=>eM,getConversationKey:()=>XR,v2:()=>rM});var ZR=1,YR=65535;function XR(t,e){const n=YC.getSharedSecret(t,"02"+e).subarray(1,33);return r=zS,i=n,TS.hash(r),Xk(r,wS("nip44-v2"),wS(i));var r,i}function JR(t,e){const n=function(t,e,n,r=32){if(TS.hash(t),TS.number(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);void 0===n&&(n=Qk);const s=new Uint8Array(i*t.outputLen),o=Xk.create(t,e),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let c=0;cYR)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}(n),e,new Uint8Array(QR(n)-n))}(t),a=Zk(r,i,o),l=tM(s,a,n);return XS.encode(_S(new Uint8Array([2]),n,a,l))}function nM(t,e){const{nonce:n,ciphertext:r,mac:i}=function(t){if("string"!=typeof t)throw new Error("payload must be a valid string");const e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if("#"===t[0])throw new Error("unknown encryption version");let n;try{n=XS.decode(t)}catch(v5){throw new Error("invalid base64: "+v5.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(2!==i)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}(t),{chacha_key:s,chacha_nonce:o,hmac_key:a}=JR(e,n);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;rYR||n.length!==e||t.length!==2+QR(e))throw new Error("invalid padding");return iE.decode(n)}(Zk(s,o,r))}var rM={utils:{getConversationKey:XR,calcPaddedLen:QR},encrypt:eM,decrypt:nM},iM=()=>Math.round(Date.now()/1e3),sM=()=>Math.round(iM()-172800*Math.random()),oM=(t,e)=>XR(t,e),aM=(t,e,n)=>eM(JSON.stringify(t),oM(e,n)),lM=(t,e)=>JSON.parse(nM(t.content,oM(e,t.pubkey)));function cM(t,e){const n={created_at:iM(),content:"",tags:[],...t,pubkey:gE(e)};return n.id=dE(n),n}function uM(t,e,n){return mE({kind:zE,content:aM(t,e,n),created_at:sM(),tags:[]},e)}function hM(t,e){const n=fE();return mE({kind:ZE,content:aM(t,n,e),created_at:sM(),tags:[["p",e]]},n)}function dM(t,e,n){return hM(uM(cM(t,e),e,n),n)}function pM(t,e,n){if(!n||0===n.length)throw new Error("At least one recipient is required.");const r=gE(e),i=[dM(t,e,r)];return n.forEach(n=>{i.push(dM(t,e,n))}),i}function fM(t,e){const n=lM(t,e);return lM(n,e)}function gM(t,e){let n=[];return t.forEach(t=>{n.push(fM(t,e))}),n.sort((t,e)=>t.created_at-e.created_at),n}function mM(t,e,n,r,i){const s=function(t,e,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:DE,tags:[],content:e};return(Array.isArray(t)?t:[t]).forEach(({publicKey:t,relayUrl:e})=>{i.tags.push(e?["p",t,e]:["p",t])}),r&&i.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&i.tags.push(["subject",n]),i}(e,n,r,i);return dM(s,t,e.publicKey)}function yM(t,e,n,r,i){if(!e||0===e.length)throw new Error("At least one recipient is required.");return[{publicKey:gE(t)},...e].map(e=>mM(t,e,n,r,i))}var vM=fM,bM=gM;function wM(t,e,n,r){let i;const s=[...t.tags??[],["e",e.id,n],["p",e.pubkey]];return e.kind===EE?i=IE:(i=jE,s.push(["k",String(e.kind)])),mE({kind:i,tags:s,content:""===t.content||e.tags?.find(t=>"-"===t[0])?"":JSON.stringify(e),created_at:t.created_at},r)}function _M(t){if(![IE,jE].includes(t.kind))return;let e,n;for(let r=t.tags.length-1;r>=0&&(void 0===e||void 0===n);r--){const i=t.tags[r];i.length>=2&&("e"===i[0]&&void 0===e?e=i:"p"===i[0]&&void 0===n&&(n=i))}return void 0!==e?{id:e[1],relays:[e[2],n?.[2]].filter(t=>"string"==typeof t),author:n?.[1]}:void 0}function xM(t,{skipVerification:e}={}){const n=_M(t);if(void 0===n||""===t.content)return;let r;try{r=JSON.parse(t.content)}catch(v5){return}return r.id===n.id&&(e||yE(r))?r:void 0}eE({},{finishRepostEvent:()=>wM,getRepostedEvent:()=>xM,getRepostedEventPointer:()=>_M}),eE({},{NOSTR_URI_REGEX:()=>CM,parse:()=>kM,test:()=>SM});var CM=new RegExp(`nostr:(${vR.source})`);function SM(t){return"string"==typeof t&&new RegExp(`^${CM.source}$`).test(t)}function kM(t){const e=t.match(new RegExp(`^${CM.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:wR(e[1])}}function EM(t,e,n){const r=e.tags.filter(t=>t.length>=2&&("e"===t[0]||"p"===t[0]));return mE({...t,kind:PE,tags:[...t.tags??[],...r,["e",e.id],["p",e.pubkey]],content:t.content??"+"},n)}function TM(t){if(t.kind!==PE)return;let e,n;for(let r=t.tags.length-1;r>=0&&(void 0===e||void 0===n);r--){const i=t.tags[r];i.length>=2&&("e"===i[0]&&void 0===e?e=i:"p"===i[0]&&void 0===n&&(n=i))}return void 0!==e&&void 0!==n?{id:e[1],relays:[e[2],n[2]].filter(t=>void 0!==t),author:n[1]}:void 0}eE({},{finishReactionEvent:()=>EM,getReactedEventPointer:()=>TM}),eE({},{parse:()=>IM});var RM=/\W/m,MM=/[^\w\/] |[^\w\/]$|$|,| /m,LM=42;function*IM(t){let e=[];if("string"!=typeof t){for(let n=0;n=3&&e.push({type:"emoji",shortcode:r[1],url:r[2]})}t=t.content}const n=t.length;let r=0,i=0;t:for(;i=0&&aPM,channelHideMessageEvent:()=>FM,channelMessageEvent:()=>OM,channelMetadataEvent:()=>AM,channelMuteUserEvent:()=>zM});var PM=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return mE({kind:qE,tags:[...t.tags??[]],content:n,created_at:t.created_at},e)},AM=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return mE({kind:VE,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},OM=(t,e)=>{const n=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&n.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),mE({kind:WE,tags:[...n,...t.tags??[]],content:t.content,created_at:t.created_at},e)},FM=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return mE({kind:HE,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},zM=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return mE({kind:GE,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:n,created_at:t.created_at},e)};eE({},{EMOJI_SHORTCODE_REGEX:()=>jM,matchAll:()=>UM,regex:()=>BM,replaceAll:()=>$M});var DM,NM,jM=/:(\w+):/,BM=()=>new RegExp(`\\B${jM.source}\\B`,"g");function*UM(t){const e=t.matchAll(BM());for(const r of e)try{const[t,e]=r;yield{shortcode:t,name:e,start:r.index,end:r.index+t.length}}catch(n){}}function $M(t,e){return t.replaceAll(BM(),(t,n)=>e({shortcode:t,name:n}))}eE({},{useFetchImplementation:()=>qM,validateGithub:()=>VM});try{DM=fetch}catch{}function qM(t){DM=t}async function VM(t,e,n){try{return await(await DM(`https://gist.github.com/${e}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch(F7){return!1}}function WM(t){const{host:e,pathname:n,searchParams:r}=new URL(t),i=n||e,s=r.get("relay"),o=r.get("secret");if(!i||!s||!o)throw new Error("invalid connection string");return{pubkey:i,relay:s,secret:o}}async function HM(t,e,n){const r={method:"pay_invoice",params:{invoice:n}},i=PR(e,t,JSON.stringify(r)),s={kind:PT,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",t]]};return mE(s,e)}function GM(t){return t=(t=t.trim().toLowerCase()).normalize("NFKC"),Array.from(t).map(t=>/\p{Letter}/u.test(t)||/\p{Number}/u.test(t)?t:"-").join("")}eE({},{makeNwcRequestEvent:()=>HM,parseConnectionString:()=>WM}),eE({},{normalizeIdentifier:()=>GM}),eE({},{getSatoshisAmountFromBolt11:()=>QM,getZapEndpoint:()=>ZM,makeZapReceipt:()=>JM,makeZapRequest:()=>YM,useFetchImplementation:()=>KM,validateZapRequest:()=>XM});try{NM=fetch}catch{}function KM(t){NM=t}async function ZM(t){try{let e="",{lud06:n,lud16:r}=JSON.parse(t.content);if(r){let[t,n]=r.split("@");e=new URL(`/.well-known/lnurlp/${t}`,`https://${n}`).toString()}else{if(!n)return null;{let{words:t}=lk.decode(n,1e3),r=lk.fromWords(t);e=iE.decode(r)}}let i=await NM(e),s=await i.json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch(e){}return null}function YM(t){let e={kind:9734,created_at:Math.round(Date.now()/1e3),content:t.comment||"",tags:[["p","pubkey"in t?t.pubkey:t.event.pubkey],["amount",t.amount.toString()],["relays",...t.relays]]};if("event"in t){if(e.tags.push(["e",t.event.id]),wE(t.event.kind)){const n=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(n)}else if(xE(t.event.kind)){let n=t.event.tags.find(([t,e])=>"d"===t&&e);if(!n)throw new Error("d tag not found or is empty");const r=["a",`${t.event.kind}:${t.event.pubkey}:${n[1]}`];e.tags.push(r)}e.tags.push(["k",t.event.kind.toString()])}return e}function XM(t){let e;try{e=JSON.parse(t)}catch(i){return"Invalid zap request JSON."}if(!rE(e))return"Zap request is not a valid Nostr event.";if(!yE(e))return"Invalid signature on zap request.";let n=e.tags.find(([t,e])=>"p"===t&&e);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find(([t,e])=>"e"===t&&e);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([t,e])=>"relays"===t&&e)?null:"Zap request doesn't have a 'relays' tag."}function JM({zapRequest:t,preimage:e,bolt11:n,paidAt:r}){let i=JSON.parse(t),s=i.tags.filter(([t])=>"e"===t||"p"===t||"a"===t),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",t]]};return e&&o.tags.push(["preimage",e]),o}function QM(t){if(t.length<50)return 0;const e=(t=t.substring(0,50)).lastIndexOf("1");if(-1===e)return 0;const n=t.substring(0,e);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const i=r[r.length-1],s=i.charCodeAt(0)-"0".charCodeAt(0),o=s>=0&&s<=9;let a=r.length-1;if(o&&a++,a<1)return 0;const l=parseInt(r.substring(0,a));switch(i){case"m":return 1e5*l;case"u":return 100*l;case"n":return l/10;case"p":return l/1e4;default:return 1e8*l}}eE({},{Negentropy:()=>aL,NegentropyStorageVector:()=>oL,NegentropySync:()=>uL});var tL=32,eL=class{_raw;length;constructor(t){"number"==typeof t?(this._raw=new Uint8Array(t),this.length=0):t instanceof Uint8Array?(this._raw=new Uint8Array(t),this.length=t.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof eL&&(t=t.unwrap()),"number"!=typeof t.length)throw Error("bad length");const e=t.length+this.length;if(this.capacity>>=7;e.reverse();for(let n=0;n4294967295&&(n=1),r.setUint32(t,4294967295&o,!0),e=n,n=0}}negate(){let t=new DataView(this.buf.buffer);for(let n=0;n<8;n++){let e=4*n;t.setUint32(e,~t.getUint32(e,!0))}let e=new Uint8Array(tL);e[0]=1,this.add(e)}getFingerprint(t){let e=new eL;return e.extend(this.buf),e.extend(rL(t)),zS(e.unwrap()).subarray(0,16)}},oL=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");const n=yk(e);if(n.byteLength!==tL)throw Error("bad id size for added item");this.items.push({timestamp:t,id:n})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(cL);for(let t=1;t=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,n){this._checkSealed(),this._checkBounds(t,e);for(let r=t;rcL(t,n)<0)}fingerprint(t,e){let n=new sL;return n.setToZero(),this.iterate(t,e,t=>(n.add(t.id),!0)),n.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,n,r){let i=n-e;for(;i>0;){let n=e,s=Math.floor(i/2);n+=s,r(t[n])?(e=++n,i-=s+1):i=s}return e}},aL=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(t,e=6e4){if(e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}initiate(){let t=new eL;return t.extend(new Uint8Array([97])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),gk(t.unwrap())}reconcile(t,e,n){const r=new eL(yk(t));this.lastTimestampIn=this.lastTimestampOut=0;let i=new eL;i.extend(new Uint8Array([97]));let s=iL(r,1)[0];if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(97!==s)throw Error("unsupported negentropy protocol version requested: "+(s-96));let o=this.storage.size(),a=this._bound(0),l=0,c=!1;for(;0!==r.length;){let t=new eL,s=()=>{c&&(c=!1,t.extend(this.encodeBound(a)),t.extend(rL(0)))},u=this.decodeBound(r),h=nL(r),d=l,p=this.storage.findLowerBound(l,o,u);if(0===h)c=!0;else if(1===h)0!==lL(iL(r,16),this.storage.fingerprint(d,p))?(s(),this.splitRange(d,p,u,t)):c=!0;else{if(2!==h)throw Error("unexpected mode");{let t=nL(r),i={};for(let e=0;e{let n=t.id;const r=gk(n);return i[r]?delete i[gk(n)]:e?.(r),!0}),n)for(let e of Object.values(i))n(gk(e))}}if(this.exceededFrameSizeLimit(i.length+t.length)){let t=this.storage.fingerprint(p,o);i.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),i.extend(rL(1)),i.extend(t);break}i.extend(t),l=p,a=u}return 1===i.length?null:gk(i.unwrap())}splitRange(t,e,n,r){let i=e-t;if(i<32)r.extend(this.encodeBound(n)),r.extend(rL(2)),r.extend(rL(i)),this.storage.iterate(t,e,t=>(r.extend(t.id),!0));else{let s=Math.floor(i/16),o=i%16,a=t;for(let t=0;t<16;t++){let i,l=s+(t(r===a-1?t=n:e=n,!0)),i=this.getMinimalBound(t,e)}r.extend(this.encodeBound(i)),r.extend(rL(1)),r.extend(c)}}}exceededFrameSizeLimit(t){return t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=nL(t);return e=0===e?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),n=nL(t);if(n>tL)throw Error("bound key too long");return{timestamp:e,id:iL(t,n)}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,rL(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,rL(t+1)}encodeBound(t){let e=new eL;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(rL(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let n=0,r=e.id,i=t.id;for(let t=0;te[n])return 1}return t.byteLength>e.byteLength?1:t.byteLength{switch(t[0]){case"NEG-MSG":t.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${t}`);try{const e=this.neg.reconcile(t[2],this.onhave,this.onneed);e?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${e}"]`):(this.close(),r.onclose?.())}catch(v5){console.error("negentropy reconcile error:",v5),r?.onclose?.(`reconcile error: ${v5}`)}break;case"NEG-CLOSE":{const e=t[2];console.warn("negentropy error:",e),r.onclose?.(e);break}case"NEG-ERR":r.onclose?.()}}}async start(){const t=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${t}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}};eE({},{getToken:()=>dL,hashPayload:()=>bL,unpackEventFromToken:()=>fL,validateEvent:()=>_L,validateEventKind:()=>mL,validateEventMethodTag:()=>vL,validateEventPayloadTag:()=>wL,validateEventTimestamp:()=>gL,validateEventUrlTag:()=>yL,validateToken:()=>pL});var hL="Nostr ";async function dL(t,e,n,r=!1,i){const s={kind:FT,tags:[["u",t],["method",e]],created_at:Math.round((new Date).getTime()/1e3),content:""};i&&s.tags.push(["payload",bL(i)]);const o=await n(s);return(r?hL:"")+XS.encode(sE.encode(JSON.stringify(o)))}async function pL(t,e,n){const r=await fL(t).catch(t=>{throw t}),i=await _L(r,e,n).catch(t=>{throw t});return i}async function fL(t){if(!t)throw new Error("Missing token");t=t.replace(hL,"");const e=iE.decode(XS.decode(t));if(!e||0===e.length||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function gL(t){return!!t.created_at&&Math.round((new Date).getTime()/1e3)-t.created_at<60}function mL(t){return t.kind===FT}function yL(t,e){const n=t.tags.find(t=>"u"===t[0]);return!!n&&n.length>0&&n[1]===e}function vL(t,e){const n=t.tags.find(t=>"method"===t[0]);return!!n&&n.length>0&&n[1].toLowerCase()===e.toLowerCase()}function bL(t){return vS(zS(sE.encode(JSON.stringify(t))))}function wL(t,e){const n=t.tags.find(t=>"payload"===t[0]);if(!n)return!1;const r=bL(e);return n.length>0&&n[1]===r}async function _L(t,e,n,r){if(!yE(t))throw new Error("Invalid nostr event, signature invalid");if(!mL(t))throw new Error("Invalid nostr event, kind invalid");if(!gL(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!yL(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!vL(t,n))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(r)&&"object"==typeof r&&Object.keys(r).length>0&&!wL(t,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}function xL(t){return 0===t||3===t||1e4<=t&&t<2e4}function CL(t){return 3e4<=t&&t<4e4}var SL=Symbol("verified");new TextDecoder("utf-8");var kL=new TextEncoder;function EL(t){return vS(zS(kL.encode(function(t){if(!function(t){if(!(t instanceof Object))return!1;if("number"!=typeof t.kind)return!1;if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if("string"!=typeof t.pubkey)return!1;if(!t.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(t.tags))return!1;for(let e=0;ee.id===t.id?0:e.created_at===t.created_at?-1:t.created_at-e.created_at);return r||t.splice(n,0,e),t}function OL(t,e){let n=0,r=t.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=e(t[i]);if(0===s)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}new TextDecoder("utf-8"),new TextEncoder;const FL=Symbol.for("event-store"),zL=Symbol.for("event-uid"),DL=Symbol.for("replaceable-address"),NL=Symbol.for("from-cache"),jL=Symbol.for("replaceable-identifier");function BL(t){return null!=t&&64===t.id?.length&&"string"==typeof t.sig&&"string"==typeof t.pubkey&&64===t.pubkey.length&&"string"==typeof t.content&&Array.isArray(t.tags)&&"number"==typeof t.created_at&&t.created_at>0}function UL(t){return xL(t)||CL(t)}function $L(t){let e=Reflect.get(t,zL);return e||(e=UL(t.kind)?function(t){return UL(t.kind)?PL(t,DL,()=>qL(t.kind,t.pubkey,VL(t))):null}(t)??t.id:t.id,Reflect.set(t,zL,e)),e}function qL(t,e,n){return t+":"+e+":"+(n??"")}function VL(t){return PL(t,jL,()=>t.tags.find(t=>"d"===t[0])?.[1]??"")}const WL=Symbol.for("encrypted-content"),HL={[vE.EncryptedDirectMessage]:"nip04",[vE.Seal]:"nip44",[vE.GiftWrap]:"nip44"};function GL(t,e){return HL[t]=e,t}function KL(t,e,n){const r=n??HL[t];if(!r)throw new Error(`Event kind ${t} does not support encrypted content`);const i=e[r];if(!i)throw new Error(`Signer does not support ${r} encryption`);return i}const ZL=new Set([WL]);function YL(t){return t}function XL(...t){return QL(t.filter(t=>!!t),ZL)}function JL(...t){return QL(t.filter(t=>!!t))}function QL(t,e){return 0===t.length?YL:async function(n,r){return t.reduce(async(t,n)=>{const i=await n(await t,r);if(e&&"object"==typeof i&&null!==i&&"object"==typeof t&&null!==t){const t=Reflect.ownKeys(i).filter(t=>"symbol"==typeof t);for(const n of t)e.has(n)||Reflect.deleteProperty(i,n)}return i},n)}}function tI(t,e){return void 0!==t[0]&&void 0!==t[1]&&(!e||t[0]===e)}function eI(t){return tI(t,"e")}function nI(t){return tI(t,"p")}function rI(t){return tI(t,"r")}function iI(t){return tI(t,"a")}const sI=(t,...e)=>e.reduce((t,e)=>{const n=[];for(const r of t)try{const t=e(r);if(void 0===t)continue;n.push(t)}catch(v5){}return n},t);function oI(t,e,n=!0){const r=t.find(t=>t[0]===e[0]);return r?n?t.map(t=>t===r?e:t):t:[...t,e]}function aI(){return Math.round(Date.now()/1e3)}var lI=new TextDecoder("utf-8");function cI(t){let e={},n=t;for(;n.length>0;){let t=n[0],r=n[1],i=n.slice(2,2+r);if(n=n.slice(2+r),i.length=8&&fI.test(t)}function mI(t){return!!t&&64===t.length&&!!t.toLowerCase().match(/^[0-9a-f]{64}$/)}function yI(t){const e=t[1];if(!e||!mI(e))return null;const n={id:e};return t[2]&&gI(t[2])&&(n.relays=[hI(t[2])]),n}function vI(t){if(!t[1])return null;const e=function(t,e=!1){const n=t.split(":"),r=n[0]?parseInt(n[0]):void 0,i=n[1];if(void 0===r)return null;if(void 0===i||""===i||!mI(i))return null;const s=n.slice(2).join(":");return e&&""===s?null:{kind:r,pubkey:i,identifier:s}}(t[1]);return e?(t[2]&&gI(t[2])&&(e.relays=[hI(t[2])]),e):null}function bI(t){const e=t[1];if(!e||!mI(e))return null;const n={pubkey:e};return t[2]&&gI(t[2])&&(n.relays=[hI(t[2])]),n}function wI(t){return"object"==typeof t&&null!==t&&"id"in t&&"string"==typeof t.id}function _I(t,e){return wI(e)?t.id===e.id&&(!e.author||t.pubkey===e.author):t.kind===e.kind&&t.pubkey===e.pubkey&&VL(t)===(e.identifier??"")}const xI=WL,CI=KL,SI=new Set([GL(vE.DraftLong,"nip04")]);function kI(t,e){return SI.add(GL(t,e)),t}function EI(t){return function(t){return void 0!==HL[t]}(t)&&SI.has(t)}function TI(t){if(EI(t.kind))return xI in t?Reflect.get(t,xI):function(t){return Reflect.get(t,WL)}(t)}function RI(t,e){if(!EI(t.kind))throw new Error("Event kind does not support hidden content");!function(t,e){Reflect.set(t,WL,e),function(t){if(!BL(t))return;const e=function(t){return Reflect.get(t,FL)}(t);e&&e.update(t)}(t)}(t,e)}const MI=Symbol.for("hidden-tags"),LI=new Set([kI(vE.BookmarkList,"nip04"),kI(vE.InterestsList,"nip04"),kI(vE.Mutelist,"nip04"),kI(vE.CommunitiesList,"nip04"),kI(vE.PublicChatsList,"nip04"),kI(vE.SearchRelaysList,"nip04"),kI(10009,"nip04"),kI(vE.Bookmarksets,"nip04"),kI(vE.Relaysets,"nip04"),kI(vE.Followsets,"nip04"),kI(vE.Curationsets,"nip04"),kI(vE.Interestsets,"nip04")]);function II(t){return EI(t)&&LI.has(t)}function PI(t){return II(t.kind)&&function(t){return EI(t.kind)&&function(t){return t.content.length>0}(t)}(t)}function AI(t){if(!II(t.kind))return;if(MI in t)return t[MI];const e=TI(t);if(void 0===e)return;const n=JSON.parse(e);if(!Array.isArray(n))throw new Error("Content is not an array of tags");const r=n.filter(t=>Array.isArray(t)).map(t=>t.map(t=>String(t)));return Reflect.set(t,MI,r),r}const OI=Symbol.for("public-contacts"),FI=Symbol.for("hidden-contacts");var zI=function(t,e){return zI=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},zI(t,e)};function DI(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}zI(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var NI=function(){return NI=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function UI(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(v5){i={error:v5}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function $I(t,e,n){if(n||2===arguments.length)for(var r,i=0,s=e.length;i0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var e=this,n=this,r=n.hasError,i=n.isStopped,s=n.observers;return r||i?ZI:(this.currentObservers=null,s.push(t),new KI(function(){e.currentObservers=null,GI(s,t)}))},e.prototype._checkFinalizedStatuses=function(t){var e=this,n=e.hasError,r=e.thrownError,i=e.isStopped;n?t.error(r):i&&t.complete()},e.prototype.asObservable=function(){var t=new lP;return t.source=this,t},e.create=function(t,e){return new gP(t,e)},e}(lP),gP=function(t){function e(e,n){var r=t.call(this)||this;return r.destination=e,r.source=n,r}return DI(e,t),e.prototype.next=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===n||n.call(e,t)},e.prototype.error=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===n||n.call(e,t)},e.prototype.complete=function(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)},e.prototype._subscribe=function(t){var e,n;return null!==(n=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==n?n:ZI},e}(fP),mP=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return DI(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){var t=this,e=t.hasError,n=t.thrownError,r=t._value;if(e)throw n;return this._throwIfClosed(),r},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(fP),yP={now:function(){return(yP.delegate||Date).now()},delegate:void 0},vP=function(t){function e(e,n,r){void 0===e&&(e=1/0),void 0===n&&(n=1/0),void 0===r&&(r=yP);var i=t.call(this)||this;return i._bufferSize=e,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,e),i._windowTime=Math.max(1,n),i}return DI(e,t),e.prototype.next=function(e){var n=this,r=n.isStopped,i=n._buffer,s=n._infiniteTimeWindow,o=n._timestampProvider,a=n._windowTime;r||(i.push(e),!s&&i.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),n=this._infiniteTimeWindow,r=this._buffer.slice(),i=0;i1||a(t,e)})},e&&(r[t]=e(r[t])))}function a(t,e){try{(n=i[t](e)).value instanceof qI?Promise.resolve(n.value.v).then(l,c):u(s[0][2],n)}catch(ej){u(s[0][3],ej)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}}(this,arguments)}function DP(t){return VI(null==t?void 0:t.getReader)}function NP(t){if(t instanceof lP)return t;if(null!=t){if(IP(t))return r=t,new lP(function(t){var e=r[oP]();if(VI(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if(MP(t))return function(t){return new lP(function(e){for(var n=0;n0&&h(r)},void 0,void 0,function(){(null==o?void 0:o.closed)||null==o||o.unsubscribe(),l=null})),!u&&h(null!=n?"number"==typeof n?n:+n-a.now():r)})}function tA(t){throw new JP(t)}function eA(t,e){return uP(function(n,r){var i=0;n.subscribe(hP(r,function(n){r.next(t.call(e,n,i++))}))})}var nA=Array.isArray,rA=Array.isArray,iA=Object.getPrototypeOf,sA=Object.prototype,oA=Object.keys;function aA(){for(var t=[],e=0;e=0?BP(n,s,c,o,!0):i=!0,c();var u=hP(n,function(t){var e,n,i=r.slice();try{for(var s=BI(i),o=s.next();!o.done;o=s.next()){var c=o.value,u=c.buffer;u.push(t),a<=u.length&&l(c)}}catch(h){e={error:h}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(e)throw e.error}}},function(){for(;null==r?void 0:r.length;)n.next(r.shift().buffer);null==u||u.unsubscribe(),n.complete(),n.unsubscribe()},void 0,function(){return r=null});e.subscribe(u)})}function vA(t){return uP(function(e,n){var r,i=null,s=!1;i=e.subscribe(hP(n,void 0,void 0,function(o){r=NP(t(o,vA(t)(e))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0})),s&&(i.unsubscribe(),i=null,r.subscribe(n))})}function bA(t,e,n,r,i){return function(s,o){var a=n,l=e,c=0;s.subscribe(hP(o,function(e){var n=c++;l=a?t(l,e,n):(a=!0,e),r&&o.next(l)},i&&function(){a&&o.next(l),o.complete()}))}}var wA=function(t,e){return t.push(e),t};function _A(t){return t<=0?function(){return SP}:uP(function(e,n){var r=0;e.subscribe(hP(n,function(e){++r<=t&&(n.next(e),t<=r&&n.complete())}))})}function xA(){return uP(function(t,e){t.subscribe(hP(e,QI))})}function CA(t,e){return void 0===e&&(e=aP),t=null!=t?t:SA,uP(function(n,r){var i,s=!0;n.subscribe(hP(r,function(n){var o=e(n);!s&&t(i,o)||(s=!1,i=o,r.next(n))}))})}function SA(t,e){return t===e}function kA(){for(var t=[],e=0;e=2,!0))}function PA(t){void 0===t&&(t={});var e=t.connector,n=void 0===e?function(){return new fP}:e,r=t.resetOnError,i=void 0===r||r,s=t.resetOnComplete,o=void 0===s||s,a=t.resetOnRefCountZero,l=void 0===a||a;return function(t){var e,r,s,a=0,c=!1,u=!1,h=function(){null==r||r.unsubscribe(),r=void 0},d=function(){h(),e=s=void 0,c=u=!1},p=function(){var t=e;d(),null==t||t.unsubscribe()};return uP(function(t,f){a++,u||c||h();var g=s=null!=s?s:n();f.add(function(){0!==--a||u||c||(r=AA(p,l))}),g.subscribe(f),!e&&a>0&&(e=new rP({next:function(t){return g.next(t)},error:function(t){u=!0,h(),r=AA(d,i,t),g.error(t)},complete:function(){c=!0,h(),r=AA(d,o),g.complete()}}),NP(t).subscribe(e))})(t)}}function AA(t,e){for(var n=[],r=2;r{"%%"!==t&&(r++,"%c"===t&&(i=r))}),e.splice(i,0,n)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(v5){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(v5){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=n.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(v5){}}(),e.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=(VA||(VA=1,qA=function(t){function e(t){let r,i,s,o=null;function a(...t){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,t[0]=e.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let o=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";o++;const s=e.formatters[i];if("function"==typeof s){const e=t[o];r=s.call(n,e),t.splice(o,1),o--}return r}),e.formatArgs.call(n,t),(n.log||e.log).apply(n,t)}return a.namespace=t,a.useColors=e.useColors(),a.color=e.selectColor(t),a.extend=n,a.destroy=e.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==e.namespaces&&(i=e.namespaces,s=e.enabled(t)),s),set:t=>{o=t}}),"function"==typeof e.init&&e.init(a),a}function n(t,n){const r=e(this.namespace+(void 0===n?":":n)+t);return r.log=this.log,r}function r(t,e){let n=0,r=0,i=-1,s=0;for(;n"-"+t)].join(",");return e.enable(""),t},e.enable=function(t){e.save(t),e.namespaces=t,e.names=[],e.skips=[];const n=("string"==typeof t?t:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const r of n)"-"===r[0]?e.skips.push(r.slice(1)):e.names.push(r)},e.enabled=function(t){for(const n of e.skips)if(r(t,n))return!1;for(const n of e.names)if(r(t,n))return!0;return!1},e.humanize=function(){if($A)return UA;$A=1;var t=1e3,e=60*t,n=60*e,r=24*n,i=7*r;function s(t,e,n,r){var i=e>=1.5*n;return Math.round(t/n)+" "+r+(i?"s":"")}return UA=function(o,a){a=a||{};var l=typeof o;if("string"===l&&o.length>0)return function(s){if(!((s=String(s)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*r;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*e;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(o);if("number"===l&&isFinite(o))return a.long?function(i){var o=Math.abs(i);return o>=r?s(i,o,r,"day"):o>=n?s(i,o,n,"hour"):o>=e?s(i,o,e,"minute"):o>=t?s(i,o,t,"second"):i+" ms"}(o):function(i){var s=Math.abs(i);return s>=r?Math.round(i/r)+"d":s>=n?Math.round(i/n)+"h":s>=e?Math.round(i/e)+"m":s>=t?Math.round(i/t)+"s":i+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}(),e.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(t).forEach(n=>{e[n]=t[n]}),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(t){let n=0;for(let e=0;e{const e=t.tags.find(t=>"expiration"===t[0])?.[1];return e?parseInt(e):void 0})}var QA,tO,eO=(tO||(tO=1,QA=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var r,i,s;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!==i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(s=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!==i--;)if(!Object.prototype.hasOwnProperty.call(n,s[i]))return!1;for(i=r;0!==i--;){var o=s[i];if(!t(e[o],n[o]))return!1}return!0}return e!=e&&n!=n}),QA);const nO=BA(eO),rO="abcdefghijklmnopqrstuvwxyz",iO=new Set((rO+rO.toUpperCase()).split("")),sO=Symbol.for("indexable-tags");function oO(t){let e=Reflect.get(t,sO);if(!e){const n=new Set;for(const e of t.tags)e.length>=2&&1===e[0].length&&iO.has(e[0])&&n.add(e[0]+":"+e[1]);e=n,Reflect.set(t,sO,n)}return e}function aO(t,e){if(t.ids&&-1===t.ids.indexOf(e.id))return!1;if(t.kinds&&-1===t.kinds.indexOf(e.kind))return!1;if(t.authors&&-1===t.authors.indexOf(e.pubkey))return!1;if(t.since&&e.created_att.until)return!1;for(let n in t)if("&"===n[0]){let r=n.slice(1),i=t[n];if(i&&i.length>0){const t=oO(e);for(const e of i)if(!t.has(r+":"+e))return!1}}for(let n in t)if("#"===n[0]){let r=n.slice(1),i=t[n];if(i){const n=t[`&${r}`],s=n?i.filter(t=>!n.includes(t)):i;if(0===s.length)continue;const o=oO(e);if(!1===s.some(t=>o.has(r+":"+t)))return!1}}return!0}function lO(t,e){for(let n=0;n[t,this.get(t)])}evict(t=!1){if(t||this.size>0){const t=this.first;delete this.items[t.key],0===--this.size?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null)}return this}expiresAt(t){let e;return this.has(t)&&(e=this.items[t].expiry),e}get(t){let e;if(this.has(t)){const n=this.items[t];this.ttl>0&&n.expiry<=Date.now()?this.delete(t):(e=n.value,this.set(t,e,!0))}return e}has(t){return t in this.items}keys(){const t=[];let e=this.first;for(;null!==e;)t.push(e.key),e=e.next;return t}set(t,e,n=!1,r=this.resetTtl){let i;if(n||this.has(t)){if(i=this.items[t],i.value=e,!1===n&&r&&(i.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.last!==i){const t=this.last,e=i.next,n=i.prev;this.first===i&&(this.first=i.next),i.next=null,i.prev=this.last,t.next=i,null!==n&&(n.next=e),null!==e&&(e.prev=n)}}else this.max>0&&this.size===this.max&&this.evict(!0),i=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e},1===++this.size?this.first=i:this.last.next=i;return this.last=i,this}values(t=this.keys()){return t.map(t=>this.get(t))}}const hO=Symbol.for("mailboxes-inboxes"),dO=Symbol.for("mailboxes-outboxes");function pO(t){return PL(t,hO,()=>{const e=[];for(const n of t.tags)if(rI(n))try{const[,t,r]=n;!t||!gI(t)||e.includes(t)||"read"!==r&&void 0!==r||e.push(hI(t))}catch{}return e})}function fO(t){return PL(t,dO,()=>{const e=[];for(const n of t.tags)if(rI(n))try{const[t,r,i]=n;"r"!==t||!gI(r)||e.includes(r)||"write"!==i&&void 0!==i||e.push(hI(r))}catch{}return e})}const gO=Symbol.for("profile-content");function mO(t){return PL(t,gO,()=>{const e=function(t){try{return JSON.parse(t)}catch(v5){return}}(t.content);if(e)return e.nip05&&"string"!=typeof e.nip05&&(e.nip05=String(e.nip05)),e.website&&e.website?.length>0&&!1===e.website?.startsWith("http")&&(e.website="https://"+e.website),e})}function yO(t){return!(!t||t.kind!==vE.Metadata&&t.kind!==vE.Handlerinformation||!mO(t))}function vO(t,e){return Object.fromEntries(Array.from(Object.entries(t)).map(([t,n])=>[t,{authors:n.map(t=>t.pubkey),...e}]))}function bO(...t){return async(e,n)=>({...e,tags:await JL(...t)(Array.from(e.tags),n)})}function wO(){return t=>{const e={...t};return Reflect.deleteProperty(e,"sig"),e}}function _O(){return t=>{const e={...t};return Reflect.deleteProperty(e,"id"),Reflect.deleteProperty(e,"pubkey"),e}}function xO(){return async(t,e)=>{if(!e.signer)throw new Error("Missing signer");Reflect.deleteProperty(t,"id"),Reflect.deleteProperty(t,"sig");const n=await e.signer.getPublicKey(),r={...t,pubkey:n};return Reflect.has(t,WL)&&Reflect.set(r,WL,Reflect.get(t,WL)),r}}const CO=[vE.EncryptedDirectMessage,vE.GiftWrap,vE.Seal,vE.PrivateDirectMessage];function SO(...t){return XL((e=[WL],t=>{const n={...t};for(const r of Reflect.ownKeys(n))"string"==typeof r||e?.includes(r)||Reflect.deleteProperty(n,r);return n}),function(t=Rx){return e=>{if(!CL(e.kind))return e;if(n=e,!n.tags.find(t=>"d"===t[0])?.[1]){let n=Array.from(e.tags);return n=oI(n,["d","string"==typeof t?t:t()],!0),{...e,tags:n}}var n;return e}}(),...t,(t,e)=>e.client?function(t,e,n=!0){return(r,i)=>{if(CO.includes(r.kind))return r;{const s=e?function(t){return t.kind+":"+t.pubkey+":"+t.identifier}({pubkey:e.pubkey,identifier:e.identifier,kind:vE.Handlerinformation}):void 0;return function(t,e=!0){return bO(function(t,e=!0){return n=>oI(n,t,e)}(t,e))}(function(t,e=2){for(let n=(t=t.slice()).length-1;n>=0;n--)void 0!==t[n]&&null!==t[n]&&""!==t[n]||(n+1===t.length&&n>=e?t.pop():t[n]="");return t}(["client",t,s]),n)(r,i)}}}(e.client.name,e.client.address)(t,e):t);var e}class kO{context;constructor(t={}){this.context=t}async build(t,...e){return await async function(t,e,...n){return await SO(wO(),_O(),...n)({created_at:aI(),tags:[],content:"",...t},e)}(t,this.context,...e)}async create(t,...e){if(1===arguments.length)return await t(this.context);{const n=t;return await n(...e)(this.context)}}async modify(t,...e){return await async function(t,e,...n){return"event"in t&&BL(t.event)&&(t=t.event),await SO(wO(),_O(),t=>({...t,created_at:aI()}),...n)(t,e)}(t,this.context,...e)}async modifyTags(t,e,n){let r=[];return void 0===n?r=[]:"function"==typeof n?r=[n]:Array.isArray(n)&&(r=n.filter(t=>!!t)),await this.modify(t,function(t){let e=[],n=[];return void 0===t?e=n=[]:Array.isArray(t)?e=t:"function"==typeof t?e=[t]:("function"==typeof t.public?e=[t.public]:t.public&&(e=t.public),"function"==typeof t.hidden?n=[t.hidden]:t.hidden&&(n=t.hidden)),XL(e.length>0?bO(...e):void 0,n.length>0?function(...t){return 0===(t=t.filter(t=>!!t)).length?t=>t:async(e,n)=>{if(!n.signer)throw new Error("Missing signer for hidden tags");if(!II(e.kind))throw new Error("Event kind does not support hidden tags");let r,i;if(PI(e)?(i=AI(e),void 0===i&&(PI(e)?(r=await n.signer.getPublicKey(),i=await async function(t,e,n){if(!II(t.kind))throw new Error("Event kind does not support hidden tags");if(function(t){if(!II(t.kind))return!1;try{return MI in t||function(t){return!!EI(t.kind)&&function(t){return!0===Reflect.has(t,WL)}(t)&&!0===Reflect.has(t,xI)}(t)&&void 0!==AI(t)}catch{}return!1}(t))return t[MI];await async function(t,e,n){if(!EI(t.kind))throw new Error("Event kind does not support hidden content");if(xI in t)return Reflect.get(t,xI);const r=KL(t.kind,e,n),i=await r.decrypt(t.pubkey,t.content);return RI(t,i),i}(t,e,n);const r=AI(t);if(void 0===r)throw new Error("Failed to unlock hidden tags");return function(t,e){if(!II(t.kind))throw new Error("Event kind does not support hidden tags");Reflect.set(t,MI,e),RI(t,JSON.stringify(e))}(t,r),r}({...e,pubkey:r},n.signer)):i=[])):i=[],void 0===i)throw new Error("Failed to find hidden tags");const s=await JL(...t)(i,n),o=(a=e.kind,l=n.signer,CI(a,l));var a,l;r||(r=await n.signer.getPublicKey());const c=JSON.stringify(s),u=await o.encrypt(r,c);return{...e,content:u,[WL]:c}}}(...n):void 0)}(e),...r)}async stamp(t){return await xO()(t,this.context)}async sign(t){return await(async(t,e)=>{if(!e.signer)throw new Error("Missing signer");t=await xO()(t,e);const n=await e.signer.signEvent(t);return Reflect.has(t,WL)&&Reflect.set(n,WL,Reflect.get(t,WL)),n})(t,this.context)}setSigner(t){this.context.signer=t}clearSigner(){this.context.signer=void 0}setClient(t){this.context.client=t}clearClient(){this.context.client=void 0}}class EO{deleted$;deletedSubject=new fP;deletedIds=new Map;deletedIdentifiers=new Map;constructor(){this.deleted$=this.deletedSubject.asObservable()}add(t){if(t.kind!==vE.EventDeletion)return[];const e=t.pubkey,n=[],r=function(t){return t.tags.filter(eI).map(yI).filter(t=>null!==t).map(e=>(e.author=t.pubkey,e))}(t);if(r.length>0){let i=this.deletedIds.get(e);i||(i=new Set,this.deletedIds.set(e,i));for(const e of r){i.add(e.id);const r={pointer:e,until:t.created_at};n.push(r),this.deletedSubject.next(r)}}const i=function(t){return t.tags.filter(iI).map(vI).filter(t=>null!==t).filter(e=>e.pubkey===t.pubkey)}(t);if(i.length>0){let r=this.deletedIdentifiers.get(e);r||(r=new Map,this.deletedIdentifiers.set(e,r));for(const e of i){const i=e.kind+"|"+e.identifier;r.set(i,t.created_at);const s={pointer:e,until:t.created_at};n.push(s),this.deletedSubject.next(s)}}return n}check(t){const e=t.pubkey;if(xL(t.kind)||CL(t.kind)){const n=this.deletedIdentifiers.get(e);if(!n)return!1;const r=VL(t),i=t.kind+"|"+r,s=n.get(i);return void 0!==s&&s>=t.created_at}{const n=this.deletedIds.get(e);return!!n&&n.has(t.id)}}filter(t){return t.filter(t=>!1===this.check(t))}}class TO{log=ZA.extend("EventMemory");kinds=new Map;authors=new Map;tags=new uO;created_at=[];kindAuthor=new Map;events=new uO;replaceable=new Map;get size(){return this.events.size}hasEvent(t){return this.events.has(t)}getEvent(t){return this.events.get(t)}hasReplaceable(t,e,n){const r=this.replaceable.get(qL(t,e,n));return!!r&&r.length>0}getReplaceable(t,e,n){const r=qL(t,e,n),i=this.replaceable.get(r);return i?.[0]}getReplaceableHistory(t,e,n){const r=qL(t,e,n);return this.replaceable.get(r)}getByFilters(t){return Array.from(this.getEventsForFilters(Array.isArray(t)?t:[t]))}getTimeline(t){const e=[],n=this.getByFilters(t);for(const r of n)AL(e,r);return e}add(t){const e=t.id,n=this.events.get(e);if(n)return n;this.events.set(e,t),this.getKindIndex(t.kind).add(t),this.getAuthorsIndex(t.pubkey).add(t),this.getKindAuthorIndex(t.kind,t.pubkey).add(t);for(const r of oO(t))this.tags.has(r)&&this.getTagIndex(r).add(t);if(AL(this.created_at,t),UL(t.kind)){const e=t.tags.find(t=>"d"===t[0])?.[1],n=qL(t.kind,t.pubkey,e);let r=this.replaceable.get(n);this.replaceable.has(n)||(r=[],this.replaceable.set(n,r)),AL(r,t)}return t}remove(t){let e="string"==typeof t?this.events.get(t):t;if(!e)return!1;const n=e.id;if(!this.events.has(n))return!1;this.getAuthorsIndex(e.pubkey).delete(e),this.getKindIndex(e.kind).delete(e);const r=`${e.kind}:${e.pubkey}`;this.kindAuthor.has(r)&&this.kindAuthor.get(r).delete(e);for(const i of oO(e))this.tags.has(i)&&this.getTagIndex(i).delete(e);if(this.removeFromSortedArray(this.created_at,e),this.events.delete(n),UL(e.kind)){const t=e.tags.find(t=>"d"===t[0])?.[1],n=qL(e.kind,e.pubkey,t),r=this.replaceable.get(n);r&&this.removeFromSortedArray(r,e)}return this.claims.delete(e),!0}removeByFilters(t){const e=this.getByFilters(t);let n=0;for(const r of e)this.remove(r)&&n++;return n}update(t){}claims=new WeakMap;touch(t){this.events.has(t.id)&&this.events.set(t.id,t)}claim(t){const e=this.claims.get(t)||0;this.claims.set(t,e+1),this.touch(t)}isClaimed(t){const e=this.claims.get(t);return void 0!==e&&e>0}removeClaim(t){const e=this.claims.get(t);if(void 0!==e&&e>0){const n=e-1;0===n?this.claims.delete(t):this.claims.set(t,n)}}clearClaim(t){this.claims.delete(t)}*unclaimed(){let t=this.events.first;for(;t;){const e=t.value;this.isClaimed(e)||(yield e),t=t.next}return 0}prune(t){let e=0;const n=this.unclaimed();for(const r of n)if(this.remove(r),e++,t&&e>=t)break;return e}getKindIndex(t){return this.kinds.has(t)||this.kinds.set(t,new Set),this.kinds.get(t)}getAuthorsIndex(t){return this.authors.has(t)||this.authors.set(t,new Set),this.authors.get(t)}getKindAuthorIndex(t,e){const n=`${t}:${e}`;return this.kindAuthor.has(n)||this.kindAuthor.set(n,new Set),this.kindAuthor.get(n)}getTagIndex(t){if(!this.tags.has(t)){const e=new Set,n=Date.now();for(const i of this.events.values())oO(i).has(t)&&e.add(i);const r=Date.now()-n;r>100&&this.log(`Built index ${t} took ${r}ms`),this.tags.set(t,e)}return this.tags.get(t)}removeFromSortedArray(t,e){if(0===t.length)return;const n=OL(t,t=>t.created_at-e.created_at);if(n){let r=n[0],i=!1;if(t[r]===e)return void t.splice(r,1);for(let n=r-1;n>=0&&t[n].created_at===e.created_at;n--)if(t[n]===e){t.splice(n,1),i=!0;break}if(i)return;for(let n=r+1;nt.created_at-e):void 0;i&&(n=Math.max(0,Math.min(i[0],this.created_at.length-1)));const s=t?OL(this.created_at,e=>e.created_at-t):void 0;if(s&&(r=Math.max(0,Math.min(s[0],this.created_at.length-1))),!(n>r))for(let o=n;o<=r;o++){const n=this.created_at[o];if(!(void 0!==e&&n.created_at>e)){if(void 0!==t&&n.created_at{const r=t instanceof Set?t:new Set(t);if(e)n=r,e=!1;else for(const e of n)r.has(e)||n.delete(e);return n};t.ids&&r(this.iterateIds(t.ids));let i=null;void 0!==t.since&&(i=Array.from(this.iterateTime(t.since,t.until)),r(i));for(const s of iO){const e=t[`&${s}`];if(e?.length)for(const t of e)r(this.iterateTag(s,[t]))}for(const s of iO){const e=t[`#${s}`];if(e?.length){const n=t[`&${s}`],i=n?e.filter(t=>!n.includes(t)):e;i.length>0&&r(this.iterateTag(s,i))}}if(t.authors&&t.kinds&&t.authors.length*t.kinds.length<=20){const e=new Set;for(const n of t.kinds)for(const r of t.authors){const t=`${n}:${r}`,i=this.kindAuthor.get(t);if(i)for(const n of i)e.add(n)}r(e)}else t.authors&&r(this.iterateAuthors(t.authors)),t.kinds&&r(this.iterateKinds(t.kinds));if(void 0===t.since&&void 0!==t.until&&(i=Array.from(this.iterateTime(t.since,t.until)),r(i)),e)return new Set(this.events.values());if(t.limit&&i){const e=new Set;for(const r of i){if(e.size>=t.limit)break;n.has(r)&&e.add(r)}return e}return n}getEventsForFilters(t){if(0===t.length)return new Set;let e=new Set;for(const n of t){const t=this.getEventsForFilter(n);for(const n of t)e.add(n)}return e}reset(){this.events.clear(),this.kinds.clear(),this.authors.clear(),this.kindAuthor.clear(),this.tags.clear(),this.created_at=[],this.replaceable.clear(),this.claims=new WeakMap}}var RO,MO,LO=function(){if(MO)return RO;function t(t,e){var n,r;if(0===e.length)return t;for(n=0,r=e.length;n{const n=new Set;return e.pipe(jA(e=>{if(void 0!==e)if(Array.isArray(e))for(const r of e)n.has(r)||(n.add(r),t.claim(r));else n.has(e)||(n.add(e),t.claim(e))}),EA(()=>{for(const e of n)t.removeClaim(e)}))}}function AO(t){return e=>{let n;return e.pipe(jA(e=>{n!==e&&(n&&t.removeClaim(n),e&&t.claim(e),n=e)}),EA(()=>{n&&t.removeClaim(n)}))}}function OO(t,e){return zA(n=>n?WP(n):t.eventLoader?VP(t.eventLoader(e)).pipe(FA(void 0)):WP(n))}function FO(t){return"string"==typeof t&&(t={id:t}),e=>fA(dA(()=>function(t,e){const n=t.getEvent(e.id);return n instanceof Promise?VP(n):WP(n)}(e,t)).pipe(e.eventLoader?OO(e,t):aP),e.insert$.pipe(mA(e=>e.id===t.id)),e.remove$.pipe(mA(e=>e.id===t.id),_A(1),eA(()=>{}))).pipe(CA((t,e)=>t?.id===e?.id),AO(e))}function zO(t){return e=>{let n;return fA(dA(()=>function(t,e){const n=t.getReplaceable(e.kind,e.pubkey,e.identifier);return n instanceof Promise?VP(n):WP(n)}(e,t)).pipe(e.eventLoader?OO(e,t):aP),e.insert$.pipe(mA(e=>e.pubkey==t.pubkey&&e.kind===t.kind&&(void 0===t.identifier||VL(e)===t.identifier)))).pipe(jA(t=>n=t),RA(e.remove$.pipe(mA(t=>t.id===n?.id),eA(()=>{}))),CA((t,e)=>void 0===t||void 0===e?t===e:e.created_at{const r=new Map;return dA(()=>{const e=n.getTimeline(t);return e instanceof Promise?VP(e):WP(e)}).pipe(PO(n),RA(n.insert$.pipe(mA(e=>lO(t,e)),PO(n))),RA(n.remove$.pipe(mA(e=>lO(t,e)),eA(t=>t.id))),IA((t,n)=>{if("string"==typeof n)return t.filter(t=>t.id!==n);if(Array.isArray(n)){if(!e)for(const t of n)UL(t.kind)&&r.set($L(t),t);return[...n]}let i=[...t];if(!e&&UL(n.kind)){const e=$L(n),s=r.get(e);if(s&&n.created_atr.clear()))}}function NO(t,e=!1){return t=Array.isArray(t)?t:[t],n=>{const r=e?SP:dA(()=>function(t,e){const n=t.getByFilters(e);return n instanceof Promise?VP(n).pipe(cA(t=>VP(t))):VP(n)}(n,t));return fA(r,n.insert$.pipe(mA(e=>lO(t,e))))}}function jO(t){return"string"==typeof t&&(t={pubkey:t}),e=>{return e.replaceable({kind:vE.Contacts,pubkey:t.pubkey,relays:t.relays}).pipe((n=e,t=>{let e;return fA(t.pipe(jA(t=>e=t)),n.update$.pipe(mA(t=>t.id===e?.id)))}),eA(t=>{return t?function(...t){const e=new Map;for(const n of t)if(Array.isArray(n))for(const t of n)t&&e.set(t.pubkey,t);else n&&e.set(n.pubkey,n);return Array.from(e.values())}(function(t){return PL(t,OI,()=>sI(t.tags,t=>nI(t)?t:void 0,t=>bI(t)??void 0))}(e=t),function(t){if(FI in t)return t[FI];const e=AI(t);if(!e)return;const n=sI(e,t=>nI(t)?t:void 0,t=>bI(t)??void 0);return Reflect.set(t,FI,n),n}(e)):[];var e}));var n}}function BO(t){return"string"==typeof t&&(t={pubkey:t}),e=>e.replaceable({kind:vE.RelayList,pubkey:t.pubkey,relays:t.relays}).pipe(eA(t=>t&&{inboxes:pO(t),outboxes:fO(t)}))}function UO(t){return"string"==typeof t&&(t={pubkey:t}),e=>e.replaceable({kind:vE.Metadata,pubkey:t.pubkey,relays:t.relays}).pipe(mA(yO),eA(t=>t&&mO(t)))}class $O{models=new Map;modelKeepWarm=6e4;model(t,...e){let n=this.models.get(t);n||(n=new Map,this.models.set(t,n));const r=t.getKey?t.getKey(...e):IO(e);let i=n.get(r);if(!i){const s=()=>{n.get(r)===i&&n.delete(r)};i=t(...e)(this).pipe(EA(s),PA({connector:()=>new vP(1),resetOnComplete:()=>pA(this.modelKeepWarm),resetOnRefCountZero:()=>pA(this.modelKeepWarm)})),n.set(r,i)}return i}filters(t,e=!1){return Array.isArray(t)||(t=[t]),this.model(NO,t,e)}event(t){return"string"==typeof t||wI(t)?this.model(FO,t):this.replaceable(t)}replaceable(...t){let e;if(1===t.length)e=t[0];else if(3===t.length||2===t.length){let[n,r,i]=t;e={kind:n,pubkey:r,identifier:i}}if(!e)throw new Error("Invalid arguments, expected address pointer or kind, pubkey, identifier");return this.model(zO,e)}addressable(t){return this.replaceable(t)}timeline(t,e=!1){return this.model(DO,t,e)}profile(t){return this.model(UO,t)}contacts(t){return"string"==typeof t&&(t={pubkey:t}),this.model(jO,t)}mailboxes(t){return"string"==typeof t&&(t={pubkey:t}),this.model(BO,t)}}class qO{expired$;expiredSubject;expirations=new Map;timer=null;nextCheck=null;constructor(){this.expiredSubject=new fP,this.expired$=this.expiredSubject.asObservable()}track(t){const e=JA(t);if(!e||!Number.isFinite(e))return;const n=aI();if(e<=n)return;if(this.expirations.set(t.id,e),this.timer&&this.nextCheck&&this.nextCheck<=e)return;this.timer&&clearTimeout(this.timer);const r=e-n;r>0&&(this.timer=setTimeout(this.emitNotifications.bind(this),1e3*r+10),this.nextCheck=e)}forget(t){this.expirations.delete(t)}check(t){const e=JA(t);return!!e&&e<=aI()}emitNotifications(){const t=aI();let e=1/0;for(const[n,r]of this.expirations)r<=t?(this.expirations.delete(n),this.expiredSubject.next(n)):r0&&(this.timer=setTimeout(this.emitNotifications.bind(this),1e3*n+10),this.nextCheck=e)}}}class VO extends $O{database;memory;deletes;expiration;keepOldVersions=!1;keepExpired=!1;keepDeleted=!1;_verifyEventMethod=IL;get verifyEvent(){return this._verifyEventMethod}set verifyEvent(t){this._verifyEventMethod=t,void 0===t&&console.warn("[applesauce-core] EventStore.verifyEvent is undefined; signature checks are disabled.")}insert$=new fP;update$=new fP;remove$=new fP;eventLoader;constructor(t){super(),t?.database?(this.database=t.database,this.memory=new TO):this.database=this.memory=new TO,void 0!==t?.keepDeleted&&(this.keepDeleted=t.keepDeleted),void 0!==t?.keepExpired&&(this.keepExpired=t.keepExpired),void 0!==t?.keepOldVersions&&(this.keepOldVersions=t.keepOldVersions),t?.verifyEvent&&(this.verifyEvent=t.verifyEvent),this.deletes=t?.deleteManager??new EO,this.deletes.deleted$.subscribe(this.handleDeleteNotification.bind(this)),this.expiration=t?.expirationManager??new qO,this.expiration.expired$.subscribe(this.handleExpiredNotification.bind(this))}mapToMemory(t){if(void 0!==t)return this.memory?this.memory.add(t):t}handleDeleteNotification({pointer:t,until:e}){if(!this.keepDeleted)if(wI(t)){const n=this.getEvent(t.id);n&&e>=n.created_at&&_I(n,t)&&this.remove(n)}else if(function(t){return"object"==typeof t&&null!==t&&"identifier"in t&&"pubkey"in t&&"kind"in t&&"string"==typeof t.identifier&&"string"==typeof t.pubkey&&"number"==typeof t.kind}(t)){const n=this.getReplaceableHistory(t.kind,t.pubkey,t.identifier);if(n)for(const r of n)e>=r.created_at&&_I(r,t)&&this.remove(r)}}handleExpiredNotification(t){this.keepExpired||this.remove(t)}static copySymbolsToDuplicateEvent(t,e){if(t.kind!==e.kind)throw new Error("Source and destination events must have the same kind");if((n=t.kind)<1e4&&0!==n&&3!==n&&t.id!==e.id)throw new Error("Source and destination events must have the same ID");var n;if(UL(t.kind)&&t.pubkey!==e.pubkey&&VL(t)!==VL(e))throw new Error("Source and destination events must have the same pubkey and replaceable identifier");let r=!1;const i=(s=t,Reflect.get(s,dI));var s;if(i){for(const t of i)pI(e,t);r=!0}const o=[NL,SL,WL];for(const a of o)a in t&&!(a in e)&&(Reflect.set(e,a,Reflect.get(t,a)),r=!0);return r}add(t,e){if(t.kind===vE.EventDeletion)return this.deletes.add(t),t;if(this.deletes.check(t))return t;const n=JA(t);if(!1===this.keepExpired&&n&&n<=aI())return null;e&&pI(t,e);const r=UL(t.kind)?VL(t):void 0;if(!1===this.keepOldVersions&&UL(t.kind)){const e=this.database.getReplaceableHistory(t.kind,t.pubkey,r);if(e&&e.length>0&&e[0].created_at>=t.created_at)return VO.copySymbolsToDuplicateEvent(t,e[0])&&this.update(e[0]),e[0]}if(this.verifyEvent&&!1===this.verifyEvent(t))return null;const i=this.memory.add(t);if(i&&i!==t)return VO.copySymbolsToDuplicateEvent(t,i)&&this.update(i),i;const s=this.mapToMemory(this.database.add(t));if(s===t?(Reflect.set(s,FL,this),this.insert$.next(s)):VO.copySymbolsToDuplicateEvent(t,s)&&this.update(s),!1===this.keepOldVersions&&UL(t.kind)){const e=this.database.getReplaceableHistory(t.kind,t.pubkey,r);if(e&&e.length>0){const n=Array.from(e).filter(e=>e.created_atthis.mapToMemory(t)??t)}getByFilters(t){const e=this.database.getByFilters(t);return this.memory?e.map(t=>this.mapToMemory(t)):e}getTimeline(t){const e=this.database.getTimeline(t);return this.memory?e.map(t=>this.mapToMemory(t)):e}touch(t){return this.memory.touch(t)}claim(t){return this.memory.claim(t)}isClaimed(t){return this.memory.isClaimed(t)??!1}removeClaim(t){return this.memory.removeClaim(t)}clearClaim(t){return this.memory.clearClaim(t)}unclaimed(){return this.memory.unclaimed()||function*(){}()}prune(t){return this.memory.prune(t)??0}}function WO(t,e=!0){return n=>{const r=n.pipe(PA());return r.pipe(cA(e=>{if("string"==typeof e)return SP;const n=t.add(e);return n instanceof Promise?VP(n):WP(n)}),vA(()=>WP(null)),mA(t=>null!==t),e?uP(function(t,e){var n=new Set;t.subscribe(hP(e,function(t){var r=t;n.has(r)||(n.add(r),e.next(t))}))}):aP,RA(r.pipe(mA(t=>"string"==typeof t))))}}function HO(t){return WO(t,!0)}class GO extends Error{}function KO(t){return QP({first:t,with:()=>HP(()=>new GO("Timeout"))})}function ZO(t,e,n=""){const r=(i=t)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name&&"BYTES_PER_ELEMENT"in i&&1===i.BYTES_PER_ELEMENT;var i;const s=t?.length;if(!r||void 0!==e){const e=(n&&`"${n}" `)+"expected Uint8Array, got "+(r?`length=${s}`:"type="+typeof t);if(!r)throw new TypeError(e);throw new RangeError(e)}return t}function YO(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function XO(...t){for(let e=0;e>>e}function tF(t,e={}){const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const eF=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function nF(t,e,n){return t&e^~t&n}function rF(t,e,n){return t&e^t&n^e&n}class iF{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,r){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(t),this.view=JO(this.buffer)}update(t){YO(this),ZO(t);const{view:e,buffer:n,blockLen:r}=this,i=t.length;for(let s=0;s='+n)}(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;e[s++]=128,XO(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let u=s;uc.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,r=QO(e,17)^QO(e,19)^e>>>10;aF[u]=r+aF[u-7]+n+aF[u-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:l,H:c}=this;for(let u=0;u<64;u++){const t=c+(QO(o,6)^QO(o,11)^QO(o,25))+nF(o,a,l)+oF[u]+aF[u]|0,e=(QO(n,2)^QO(n,13)^QO(n,22))+rF(n,r,i)|0;c=l,l=a,a=o,o=s+t|0,s=i,i=r,r=n,n=t+e|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,r,i,s,o,a,l,c)}roundClean(){XO(aF)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),XO(this.buffer)}}class cF extends lF{A=0|sF[0];B=0|sF[1];C=0|sF[2];D=0|sF[3];E=0|sF[4];F=0|sF[5];G=0|sF[6];H=0|sF[7];constructor(){super(32)}}const uF=tF(()=>new cF,eF(1)),hF=new WeakMap;function dF(t,e,n,r){let i={configurable:!0,enumerable:!0,writable:!0,initializer:null};r&&(i.initializer=r);for(let s of n)i=s(t,e,i)||i;void 0===i.initializer?Object.defineProperty(t,e,i):function(t,e,n){let r=hF.get(t);r||(r=new Map,hF.set(t,r)),r.set(e,n)}(t,e,i)}function pF(t,e,n){let r={...Object.getOwnPropertyDescriptor(t,e)};for(let i of n)r=i(t,e,r)||r;void 0!==r.initializer&&(r.value=r.initializer?r.initializer.call(t):void 0,r.initializer=void 0),Object.defineProperty(t,e,r)}function fF(t,e){let n=function(t,e){var n;let r=t.prototype;for(;r;){let t=null==(n=hF.get(r))?void 0:n.get(e);if(t)return t;r=r.prototype}}(t.constructor,e);n&&Object.defineProperty(t,e,{enumerable:n.enumerable,configurable:n.configurable,writable:n.writable,value:n.initializer?n.initializer.call(t):void 0})}const gF="https://blossom.nostr.build";function mF(t,e){let n=t||gF;return n.endsWith("/")&&(n=n.slice(0,-1)),e.startsWith("/")?`${n}${e}`:`${n}/${e}`}class yF extends qf{static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");get servers(){const t=this.nostrData.blossomServers,e=t.length?t:[gF];return this.settings.nostrPhotoFallbackUploads?e:[e[0]]}async _getAuthHeader(t,e,n){const r=new kO({signer:this.nostrAuth.signer}),i=Math.floor(Date.now()/1e3),s=new URL(n).hostname,o={kind:24242,created_at:i,content:"upload"===t?"Upload photo for place":"Delete photo",tags:[["t",t],["x",e],["expiration",String(i+3600)],["server",s]]},a=await r.sign(o);return`Nostr ${btoa(JSON.stringify(a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}async _uploadToServer(t,e,n){const r=mF(n,"upload"),i=await this._getAuthHeader("upload",e,n),s=await fetch(r,{method:"PUT",headers:{Authorization:i,"X-SHA-256":e},body:t});if(!s.ok){const t=await s.text();throw new Error(`Upload failed (${s.status}): ${t}`)}return s.json()}async upload(t,e={sequential:!1}){if(!this.nostrAuth.isConnected)throw new Error("Not connected");const n=await t.arrayBuffer();let r;r="undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest?await crypto.subtle.digest("SHA-256",n):uF(new Uint8Array(n));const i=function(t){return Array.from(new Uint8Array(t)).map(t=>t.toString(16).padStart(2,"0")).join("")}(r),s=this.servers,o=s[0],a=s.slice(1),l=[];let c;if(e.sequential){c=await this._uploadToServer(t,i,o);for(const e of a)try{const n=await this._uploadToServer(t,i,e);l.push(n.url)}catch(v5){console.warn(`Fallback upload to ${e} failed:`,v5)}}else{const e=this._uploadToServer(t,i,o),n=a.map(e=>this._uploadToServer(t,i,e));c=await e;const r=await Promise.allSettled(n);for(let t=0;tthis._deleteFromServer(t,e));await i;const o=await Promise.allSettled(s);for(let a=0;a{const r=new Image,i=URL.createObjectURL(t);r.onload=()=>{const t={width:r.width,height:r.height};URL.revokeObjectURL(i),e(t)},r.onerror=()=>{URL.revokeObjectURL(i),n(new Error("Could not read image dimensions"))},r.src=i})}async process(t,e,n,r=!1){if(!this._worker)throw new Error("Image processor worker is not available.");try{const{width:i,height:s}=await this._getImageDimensions(t);let o=i,a=s;return i>s?i>e&&(a=Math.round(s*(e/i)),o=e):s>e&&(o=Math.round(i*(e/s)),a=e),new Promise((e,i)=>{const s=++this._msgId;this._callbacks.set(s,{resolve:e,reject:i}),this._worker.postMessage({type:"PROCESS_IMAGE",id:s,file:t,targetWidth:o,targetHeight:a,quality:n,computeBlurhash:r})})}catch(ej){throw new Error(`Failed to process image: ${ej.message}`)}}willDestroy(){super.willDestroy(...arguments),this._worker&&(this._worker.terminate(),this._worker=null),this._callbacks.clear()}}},Symbol.toStringTag,{value:"Module"}));class _F extends qf{static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"selectedPlace",[Is],function(){return null})}#P=void fF(this,"selectedPlace");static{dF(this.prototype,"isSearching",[Is],function(){return!1})}#A=void fF(this,"isSearching");static{dF(this.prototype,"isCreating",[Is],function(){return!1})}#O=void fF(this,"isCreating");static{dF(this.prototype,"creationCoordinates",[Is],function(){return null})}#F=void fF(this,"creationCoordinates");static{dF(this.prototype,"returnToSearch",[Is],function(){return!1})}#z=void fF(this,"returnToSearch");static{dF(this.prototype,"currentCenter",[Is],function(){return null})}#D=void fF(this,"currentCenter");static{dF(this.prototype,"currentBounds",[Is],function(){return null})}#N=void fF(this,"currentBounds");static{dF(this.prototype,"searchBoxHasFocus",[Is],function(){return!1})}#j=void fF(this,"searchBoxHasFocus");static{dF(this.prototype,"selectionOptions",[Is],function(){return{}})}#B=void fF(this,"selectionOptions");static{dF(this.prototype,"preventNextZoom",[Is],function(){return!1})}#U=void fF(this,"preventNextZoom");static{dF(this.prototype,"searchResults",[Is],function(){return[]})}#$=void fF(this,"searchResults");static{dF(this.prototype,"currentSearch",[Is],function(){return null})}#q=void fF(this,"currentSearch");static{dF(this.prototype,"loadingState",[Is],function(){return null})}#V=void fF(this,"loadingState");selectPlace(t,e={}){this.selectedPlace=t,this.selectionOptions=e,this.nostrData.loadPhotosForPlace(t)}clearSelection(){this.selectedPlace=null,this.selectionOptions={},this.preventNextZoom=!1,this.nostrData.loadPhotosForPlace(null)}setSearchResults(t){this.searchResults=t||[]}clearSearchResults(){this.searchResults=[],this.currentSearch=null}startSearch(){this.isSearching=!0,this.isCreating=!1,this.preventNextZoom=!1}stopSearch(){this.isSearching=!1}startCreating(){this.isCreating=!0,this.isSearching=!1}stopCreating(){this.isCreating=!1,this.creationCoordinates=null}updateCreationCoordinates(t,e){this.creationCoordinates={lat:t,lon:e}}setSearchBoxFocus(t){this.searchBoxHasFocus=t}updateCenter(t,e){this.currentCenter={lat:t,lon:e}}updateBounds(t){this.currentBounds=t}startLoading(t,e){this.loadingState={type:t,value:e}}stopLoading(t=null,e=null){t||e?this.loadingState&&this.loadingState.type===t&&this.loadingState.value===e&&(this.loadingState=null):this.loadingState=null}}const xF=Object.freeze(Object.defineProperty({__proto__:null,default:_F},Symbol.toStringTag,{value:"Module"}));function CF(){let t,e;const n=new Promise((n,r)=>{t=n,e=r});return n.resolve=t,n.reject=e,n}"navigator"in globalThis&&navigator.userAgent.includes("Android")&&navigator.clipboard&&navigator.clipboard.readText;class SF extends Error{}class kF{get nip04(){return window.nostr?.nip04}get nip44(){return window.nostr?.nip44}pubkey=void 0;async getPublicKey(){if(!window.nostr)throw new SF("Signer extension missing");if(this.pubkey)return this.pubkey;const t=await window.nostr.getPublicKey();if(!mI(t))throw new Error("Extension returned an invalid public key");return this.pubkey=t,this.pubkey}async signEvent(t){if(!window.nostr)throw new SF("Signer extension missing");const e=await window.nostr.signEvent(t);if(!IL(e))throw new Error("Extension returned an invalid event");return e}}var EF,TF;kI(vE.NostrConnect,"nip44"),function(t){t.GetPublicKey="get_pubic_key",t.SignEvent="sign_event",t.Ping="ping",t.Nip04Encrypt="nip04_encrypt",t.Nip04Decrypt="nip04_decrypt",t.Nip44Encrypt="nip44_encrypt",t.Nip44Decrypt="nip44_decrypt",t.SwitchRelays="switch_relays"}(EF||(EF={})),function(t){t.Connect="connect",t.CreateAccount="create_account",t.GetPublicKey="get_public_key",t.SignEvent="sign_event",t.Ping="ping",t.Nip04Encrypt="nip04_encrypt",t.Nip04Decrypt="nip04_decrypt",t.Nip44Encrypt="nip44_encrypt",t.Nip44Decrypt="nip44_decrypt",t.SwitchRelays="switch_relays"}(TF||(TF={}));class RF{key;constructor(t){this.key=t||RL()}async getPublicKey(){return ML(this.key)}async signEvent(t){return LL(t,this.key)}nip04={encrypt:async(t,e)=>IR.encrypt(this.key,t,e),decrypt:async(t,e)=>IR.decrypt(this.key,t,e)};nip44={encrypt:async(t,e)=>KR.v2.encrypt(e,KR.v2.utils.getConversationKey(this.key,t)),decrypt:async(t,e)=>KR.v2.decrypt(e,KR.v2.utils.getConversationKey(this.key,t))};static fromKey(t){const e=function(t){if(t instanceof Uint8Array)return 32!==t.length?null:t;if(mI(t))return bS(t);try{const e=function(t){let{prefix:e,words:n}=lk.decode(t,5e3),r=new Uint8Array(lk.fromWords(n));switch(e){case"nprofile":{let t=cI(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:vS(t[0][0]),relays:t[1]?t[1].map(t=>lI.decode(t)):[]}}}case"nevent":{let t=cI(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(t[2]&&32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(t[3]&&4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:vS(t[0][0]),relays:t[1]?t[1].map(t=>lI.decode(t)):[],author:t[2]?.[0]?vS(t[2][0]):void 0,kind:t[3]?.[0]?parseInt(vS(t[3][0]),16):void 0}}}case"naddr":{let t=cI(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!t[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!t[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:lI.decode(t[0][0]),pubkey:vS(t[2][0]),kind:parseInt(vS(t[3][0]),16),relays:t[1]?t[1].map(t=>lI.decode(t)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:vS(r)};default:throw new Error(`unknown prefix ${e}`)}}(t);return"nsec"!==e.type?null:e.data}catch{return null}}(t);if(!e)throw new Error("Invalid private key");return new RF(e)}}async function MF(t){window.open(t,"auth","width=400,height=600,resizable=no,status=no,location=no,toolbar=no,menubar=no")}class LF{static subscriptionMethod=void 0;static publishMethod=void 0;static pool=void 0;publishMethod;subscriptionMethod;log=ZA.extend("NostrConnectSigner");signer;listening=!1;isConnected=!1;pubkey;relays;remote;get clientPubkey(){return ML(this.signer.key)}onAuth=MF;verifyEvent=IL;secret;nip04;nip44;constructor(t){this.relays=t.relays,this.pubkey=t.pubkey,this.remote=t.remote,this.secret=t.secret||Rx(12);const{subscriptionMethod:e,publishMethod:n}=function(t,e){const n=t.subscriptionMethod||t.pool?.subscription.bind(t.pool)||e?.subscriptionMethod||e?.pool?.subscription.bind(e.pool);if(!n)throw new Error("Missing subscriptionMethod, either pass a method or set subscriptionMethod globally on the class");const r=t.publishMethod||t.pool?.publish.bind(t.pool)||e?.publishMethod||e?.pool?.publish.bind(e.pool);if(!r)throw new Error("Missing publishMethod, either pass a method or set publishMethod globally on the class");return{subscriptionMethod:n,publishMethod:r}}(t,LF);this.subscriptionMethod=(t,n)=>e(t,n),this.publishMethod=(t,e)=>n(t,e),t.onAuth&&(this.onAuth=t.onAuth),this.signer=t?.signer||new RF,this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)},this.nip44={encrypt:this.nip44Encrypt.bind(this),decrypt:this.nip44Decrypt.bind(this)}}req;async open(){if(this.listening)return;this.listening=!0;const t=await this.signer.getPublicKey();this.req=VP(this.subscriptionMethod(this.relays,[{kinds:[vE.NostrConnect],"#p":[t]}])).pipe(MA(),LA(),mA(t=>"string"!=typeof t)).subscribe(this.handleEvent.bind(this)),this.log("Opened",this.relays)}async close(){this.listening=!1,this.isConnected=!1,this.req&&(this.req.unsubscribe(),this.req=void 0),this.waitingPromise&&(this.waitingPromise.reject(new Error("Closed")),this.waitingPromise=null),this.log("Closed")}requests=new Map;auths=new Set;async handleEvent(t){if(this.verifyEvent(t)&&(!this.remote||t.pubkey===this.remote))try{const e=TI(t)??(function(t){const e=t.length;return!(e<28)&&"?"==t[e-28]&&"i"==t[e-27]&&"v"==t[e-26]&&"="==t[e-25]}(t.content)?await this.signer.nip04.decrypt(t.pubkey,t.content):await this.signer.nip44.decrypt(t.pubkey,t.content));if(!e)return;const n=JSON.parse(e);if(!this.remote&&("ack"===n.result||this.secret&&n.result===this.secret))return this.log("Got ack response from",t.pubkey,n.result),this.isConnected=!0,this.remote=t.pubkey,this.waitingPromise?.resolve(),void(this.waitingPromise=null);if(n.id){const t=this.requests.get(n.id);if(!t)return;if(n.error)if(this.log("Got Error",n.id,n.result,n.error),"auth_url"===n.result){if(!this.auths.has(n.id)&&(this.auths.add(n.id),this.onAuth))try{await this.onAuth(n.error)}catch(ej){t.reject(ej)}}else t.reject(new Error(n.error));else n.result&&(this.log("Got Response",n.id,n.result),t.resolve(n.result))}}catch(ej){}}async createRequestEvent(t,e=this.remote,n=vE.NostrConnect){if(!e)throw new Error("Missing target pubkey");return await this.signer.signEvent({kind:n,created_at:aI(),tags:[["p",e]],content:t})}async makeRequest(t,e,n=vE.NostrConnect){if(!this.remote)throw new Error("Missing remote signer pubkey");const r=Rx(8),i={id:r,method:t,params:e},s=await this.signer.nip44.encrypt(this.remote,JSON.stringify(i)),o=await this.createRequestEvent(s,this.remote,n);this.log(`Sending ${r} (${t}) ${JSON.stringify(e)}`);const a=CF();this.requests.set(r,a);const l=this.publishMethod?.(this.relays,o);return l instanceof Promise?await l:"subscribe"in l&&await new Promise(t=>l.subscribe({complete:t})),this.log(`Sent ${r} (${t})`),a}async connect(t,e){if(!this.remote&&this.pubkey&&(this.remote=this.pubkey),!this.remote)throw new Error("Missing remote signer pubkey");await this.open();try{const n=await this.makeRequest(TF.Connect,[this.remote,t||"",e?.join(",")??""]);return this.isConnected=!0,n}catch(ej){throw this.isConnected=!1,this.close(),ej}}waitingPromise=null;waitForSigner(t){return this.isConnected?Promise.resolve():(this.open(),this.waitingPromise=CF(),t?.addEventListener("abort",()=>{this.waitingPromise?.reject(new Error("Aborted")),this.waitingPromise=null,this.close()},!0),this.waitingPromise)}async createAccount(t,e,n,r){if(!this.remote)throw new Error("Remote pubkey must be set");await this.open();try{const i=await this.makeRequest(TF.CreateAccount,[t,e,n??"",r?.join(",")??""]);return this.pubkey=i,this.isConnected=!0,i}catch(ej){throw this.isConnected=!1,this.close(),ej}}async requireConnection(){this.isConnected||await this.connect()}async getPublicKey(){if(this.pubkey)return this.pubkey;await this.requireConnection();const t=await this.makeRequest(TF.GetPublicKey,[]);if(!mI(t))throw new Error("Remote signer returned an invalid public key");return t}async signEvent(t){await this.requireConnection();const e=await this.makeRequest(TF.SignEvent,[JSON.stringify(t)]),n=JSON.parse(e);if(!this.verifyEvent(n))throw new Error("Invalid event");return n}async nip04Encrypt(t,e){return await this.requireConnection(),this.makeRequest(TF.Nip04Encrypt,[t,e])}async nip04Decrypt(t,e){await this.requireConnection();const n=await this.makeRequest(TF.Nip04Decrypt,[t,e]);return n.startsWith('["')&&n.endsWith('"]')?JSON.parse(n)[0]:n}async nip44Encrypt(t,e){return await this.requireConnection(),this.makeRequest(TF.Nip44Encrypt,[t,e])}async nip44Decrypt(t,e){await this.requireConnection();const n=await this.makeRequest(TF.Nip44Decrypt,[t,e]);return n.startsWith('["')&&n.endsWith('"]')?JSON.parse(n)[0]:n}async ping(){return await this.requireConnection(),this.makeRequest(TF.Ping,[])}async switchRelays(){await this.requireConnection();const t=await this.makeRequest(TF.SwitchRelays,[]);return null!==t&&Array.isArray(t)&&t.length>0&&(this.log("Switching relays from",this.relays,"to",t),this.relays=t,this.listening&&(await this.close(),await this.open())),t}getNostrConnectURI(t){return function(t){const e=new URLSearchParams;e.set("secret",t.secret),t.metadata?.name&&e.set("name",t.metadata.name),t.metadata?.url&&e.set("url",String(t.metadata.url)),t.metadata?.image&&e.set("image",t.metadata.image),t.metadata?.permissions&&e.set("perms",t.metadata.permissions.join(","));for(const n of t.relays)e.append("relay",n);return`nostrconnect://${t.client}?`+e.toString()}({client:ML(this.signer.key),secret:this.secret,relays:this.relays,metadata:t})}static parseBunkerURI(t){return function(t){const e=new URL(t),n=e.host||e.pathname.replace("//","");if(!mI(n))throw new Error("Invalid bunker URI: remote is not a valid hex key");const r=e.searchParams.getAll("relay");if(0===r.length)throw new Error("Invalid bunker URI: missing relays");return{remote:n,relays:r,secret:e.searchParams.get("secret")??void 0}}(t)}static buildSigningPermissions(t){return function(t){return[EF.GetPublicKey,...t.map(t=>`${EF.SignEvent}:${t}`)]}(t)}static async fromBunkerURI(t,e){const{remote:n,relays:r,secret:i}=LF.parseBunkerURI(t),s=new LF({relays:r,remote:n,...e});return await s.connect(i,e?.permissions),s}} -/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const IF=BigInt(0),PF=BigInt(1),AF=BigInt(2),OF=BigInt(3),FF=BigInt(8),zF=Object.freeze({a:IF,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:PF,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),DF=(t,e)=>(t+e/AF)/e,NF={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){const{n:e}=zF,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-PF*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=DF(s*t,e),l=DF(-r*t,e);let c=lz(t-a*n-l*i,e),u=lz(-a*r-l*s,e);const h=c>o,d=u>o;if(h&&(c=e-c),d&&(u=e-u),c>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:h,k1:c,k2neg:d,k2:u}}};function jF(t){const{a:e,b:n}=zF,r=lz(t*t),i=lz(r*t);return lz(i+e*t+n)}const BF=zF.a===IF;function UF(t){if(!(t instanceof $F))throw new TypeError("JacobianPoint expected")}class $F{constructor(t,e,n){this.x=t,this.y=e,this.z=n}static fromAffine(t){if(!(t instanceof WF))throw new TypeError("JacobianPoint#fromAffine: expected Point");return t.equals(WF.ZERO)?$F.ZERO:new $F(t.x,t.y,PF)}static toAffineBatch(t){const e=function(t,e=zF.P){const n=new Array(t.length),r=t.reduce((t,r,i)=>r===IF?t:(n[i]=t,lz(t*r,e)),PF),i=uz(r,e);return t.reduceRight((t,r,i)=>r===IF?t:(n[i]=lz(t*n[i],e),lz(t*r,e)),i),n}(t.map(t=>t.z));return t.map((t,n)=>t.toAffine(e[n]))}static normalizeZ(t){return $F.toAffineBatch(t).map($F.fromAffine)}equals(t){UF(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t,a=lz(r*r),l=lz(o*o),c=lz(e*l),u=lz(i*a),h=lz(lz(n*o)*l),d=lz(lz(s*r)*a);return c===u&&h===d}negate(){return new $F(this.x,lz(-this.y),this.z)}double(){const{x:t,y:e,z:n}=this,r=lz(t*t),i=lz(e*e),s=lz(i*i),o=t+i,a=lz(AF*(lz(o*o)-r-s)),l=lz(OF*r),c=lz(l*l),u=lz(c-AF*a),h=lz(l*(a-u)-FF*s),d=lz(AF*e*n);return new $F(u,h,d)}add(t){UF(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t;if(i===IF||s===IF)return this;if(e===IF||n===IF)return t;const a=lz(r*r),l=lz(o*o),c=lz(e*l),u=lz(i*a),h=lz(lz(n*o)*l),d=lz(lz(s*r)*a),p=lz(u-c),f=lz(d-h);if(p===IF)return f===IF?this.double():$F.ZERO;const g=lz(p*p),m=lz(p*g),y=lz(c*g),v=lz(f*f-m-AF*y),b=lz(f*(y-v)-h*m),w=lz(r*o*p);return new $F(v,b,w)}subtract(t){return this.add(t.negate())}multiplyUnsafe(t){const e=$F.ZERO;if("bigint"==typeof t&&t===IF)return e;let n=az(t);if(n===PF)return this;if(!BF){let t=e,r=this;for(;n>IF;)n&PF&&(t=t.add(r)),r=r.double(),n>>=PF;return t}let{k1neg:r,k1:i,k2neg:s,k2:o}=NF.splitScalar(n),a=e,l=e,c=this;for(;i>IF||o>IF;)i&PF&&(a=a.add(c)),o&PF&&(l=l.add(c)),c=c.double(),i>>=PF,o>>=PF;return r&&(a=a.negate()),s&&(l=l.negate()),l=new $F(lz(l.x*NF.beta),l.y,l.z),a.add(l)}precomputeWindow(t){const e=BF?128/t+1:256/t+1,n=[];let r=this,i=r;for(let s=0;s>=u,n>a&&(n-=c,t+=PF);const o=e,d=e+Math.abs(n)-1,p=h%2!=0,f=n<0;0===n?s=s.add(qF(p,r[o])):i=i.add(qF(f,r[d]))}return{p:i,f:s}}multiply(t,e){let n,r,i=az(t);if(BF){const{k1neg:t,k1:s,k2neg:o,k2:a}=NF.splitScalar(i);let{p:l,f:c}=this.wNAF(s,e),{p:u,f:h}=this.wNAF(a,e);l=qF(t,l),u=qF(o,u),u=new $F(lz(u.x*NF.beta),u.y,u.z),n=l.add(u),r=c.add(h)}else{const{p:t,f:s}=this.wNAF(i,e);n=t,r=s}return $F.normalizeZ([n,r])[0]}toAffine(t){const{x:e,y:n,z:r}=this,i=this.equals($F.ZERO);null==t&&(t=i?FF:uz(r));const s=t,o=lz(s*s),a=lz(o*s),l=lz(e*o),c=lz(n*a),u=lz(r*s);if(i)return WF.ZERO;if(u!==PF)throw new Error("invZ was invalid");return new WF(l,c)}}function qF(t,e){const n=e.negate();return t?n:e}$F.BASE=new $F(zF.Gx,zF.Gy,PF),$F.ZERO=new $F(IF,PF,IF);const VF=new WeakMap;let WF=class t{constructor(t,e){this.x=t,this.y=e}_setWindowSize(t){this._WINDOW_SIZE=t,VF.delete(this)}hasEvenY(){return this.y%AF===IF}static fromCompressedHex(e){const n=32===e.length,r=sz(n?e:e.subarray(1));if(!dz(r))throw new Error("Point is not on curve");let i=function(t){const{P:e}=zF,n=BigInt(6),r=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=t*t*t%e,c=l*l*t%e,u=cz(c,OF)*c%e,h=cz(u,OF)*c%e,d=cz(h,AF)*l%e,p=cz(d,r)*d%e,f=cz(p,i)*p%e,g=cz(f,o)*f%e,m=cz(g,a)*g%e,y=cz(m,o)*f%e,v=cz(y,OF)*c%e,b=cz(v,s)*p%e,w=cz(b,n)*l%e,_=cz(w,AF);if(_*_%e!==t)throw new Error("Cannot find square root");return _}(jF(r));const s=(i&PF)===PF;n?s&&(i=lz(-i)):!(1&~e[0])!==s&&(i=lz(-i));const o=new t(r,i);return o.assertValidity(),o}static fromUncompressedHex(e){const n=sz(e.subarray(1,33)),r=sz(e.subarray(33,65)),i=new t(n,r);return i.assertValidity(),i}static fromHex(t){const e=oz(t),n=e.length,r=e[0];if(32===n)return this.fromCompressedHex(e);if(33===n&&(2===r||3===r))return this.fromCompressedHex(e);if(65===n&&4===r)return this.fromUncompressedHex(e);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return t.BASE.multiply(function(t){let e;if("bigint"==typeof t)e=t;else if("number"==typeof t&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if("string"==typeof t){if(64!==t.length)throw new Error("Expected 32 bytes of private key");e=iz(t)}else{if(!ZF(t))throw new TypeError("Expected valid private key");if(32!==t.length)throw new Error("Expected 32 bytes of private key");e=sz(t)}if(!hz(e))throw new Error("Expected private key: 0 < key < n");return e}(e))}static fromSignature(e,n,r){const{r:i,s:s}=function(t){if(t instanceof KF)return t.assertValidity(),t;try{return KF.fromDER(t)}catch(v5){return KF.fromCompact(t)}}(n);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const o=function(t,e=!1){const n=function(t){const e=8*t.length-256,n=sz(t);return e>0?n>>BigInt(e):n}(t);if(e)return n;const{n:r}=zF;return n>=r?n-r:n}(oz(e)),{n:a}=zF,l=2===r||3===r?i+a:i,c=uz(l,a),u=lz(-o*c,a),h=lz(s*c,a),d=1&r?"03":"02",p=t.fromHex(d+nz(l)),f=t.BASE.multiplyAndAddUnsafe(p,u,h);if(!f)throw new Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(t=!1){return tz(this.toHex(t))}toHex(t=!1){const e=nz(this.x);return t?`${this.hasEvenY()?"02":"03"}${e}`:`04${e}${nz(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const t="Point is not on elliptic curve",{x:e,y:n}=this;if(!dz(e)||!dz(n))throw new Error(t);const r=lz(n*n);if(lz(r-jF(e))!==IF)throw new Error(t)}equals(t){return this.x===t.x&&this.y===t.y}negate(){return new t(this.x,lz(-this.y))}double(){return $F.fromAffine(this).double().toAffine()}add(t){return $F.fromAffine(this).add($F.fromAffine(t)).toAffine()}subtract(t){return this.add(t.negate())}multiply(t){return $F.fromAffine(this).multiply(t,this).toAffine()}multiplyAndAddUnsafe(e,n,r){const i=$F.fromAffine(this),s=n===IF||n===PF||this!==t.BASE?i.multiplyUnsafe(n):i.multiply(n),o=$F.fromAffine(e).multiplyUnsafe(r),a=s.add(o);return a.equals($F.ZERO)?void 0:a.toAffine()}};function HF(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function GF(t){if(t.length<2||2!==t[0])throw new Error(`Invalid signature integer tag: ${XF(t)}`);const e=t[1],n=t.subarray(2,e+2);if(!e||n.length!==e)throw new Error("Invalid signature integer: wrong length");if(0===n[0]&&n[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:sz(n),left:t.subarray(e+2)}}WF.BASE=new WF(zF.Gx,zF.Gy),WF.ZERO=new WF(IF,IF);class KF{constructor(t,e){this.r=t,this.s=e,this.assertValidity()}static fromCompact(t){const e=ZF(t),n="Signature.fromCompact";if("string"!=typeof t&&!e)throw new TypeError(`${n}: Expected string or Uint8Array`);const r=e?XF(t):t;if(128!==r.length)throw new Error(`${n}: Expected 64-byte hex`);return new KF(iz(r.slice(0,64)),iz(r.slice(64,128)))}static fromDER(t){const e=ZF(t);if("string"!=typeof t&&!e)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:n,s:r}=function(t){if(t.length<2||48!=t[0])throw new Error(`Invalid signature tag: ${XF(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");const{data:e,left:n}=GF(t.subarray(2)),{data:r,left:i}=GF(n);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${XF(i)}`);return{r:e,s:r}}(e?t:tz(t));return new KF(n,r)}static fromHex(t){return this.fromDER(t)}assertValidity(){const{r:t,s:e}=this;if(!hz(t))throw new Error("Invalid Signature: r must be 0 < r < n");if(!hz(e))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const t=zF.n>>PF;return this.s>t}normalizeS(){return this.hasHighS()?new KF(this.r,lz(-this.s,zF.n)):this}toDERRawBytes(){return tz(this.toDERHex())}toDERHex(){const t=HF(rz(this.s)),e=HF(rz(this.r)),n=t.length/2,r=e.length/2,i=rz(n),s=rz(r);return`30${rz(r+n+4)}02${s}${e}02${i}${t}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return tz(this.toCompactHex())}toCompactHex(){return nz(this.r)+nz(this.s)}}function ZF(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}const YF=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function XF(t){!function(t){if(!ZF(t))throw new Error("Uint8Array expected")}(t);let e="";for(let n=0;n=JF._0&&t<=JF._9?t-JF._0:t>=JF.A&&t<=JF.F?t-(JF.A-10):t>=JF.a&&t<=JF.f?t-(JF.a-10):void 0}function tz(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i0)return BigInt(t);if("bigint"==typeof t&&hz(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function lz(t,e=zF.P){const n=t%e;return n>=IF?n:e+n}function cz(t,e){const{P:n}=zF;let r=t;for(;e-- >IF;)r*=r,r%=n;return r}function uz(t,e=zF.P){if(t===IF||e<=IF)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=lz(t,e),r=e,i=IF,s=PF;for(;n!==IF;){const t=r%n,e=i-s*(r/n);r=n,n=t,i=s,s=e}if(r!==PF)throw new Error("invert: does not exist");return lz(i,e)}function hz(t){return IFt.charCodeAt(0)))}class vz{log=ZA.extend("SerialPortSigner");writer=null;pubkey;get isConnected(){return!!this.writer}verifyEvent=IL;nip04;constructor(){this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)}}lastCommand=null;async callMethodOnDevice(t,e,n={}){if(!vz.SUPPORTED)throw new Error("Serial devices are not supported");if(this.writer||await this.connectToDevice(n),this.lastCommand)throw new Error("Previous command to device still pending!");const r=CF();return this.lastCommand=r,this.sendCommand(t,e),setTimeout(()=>{r.reject(new Error("Device timeout")),this.lastCommand===r&&(this.lastCommand=null)},6e3),this.lastCommand}async connectToDevice({onConnect:t,onDisconnect:e,onError:n,onDone:r}){let i,s=await window.navigator.serial.requestPort();await s.open({baudRate:9600}),await new Promise(t=>setTimeout(t,1e3)),(async()=>{for(;s&&s.readable;){const t=new window.TextDecoderStream;s.readable.pipeTo(t.writable),i=t.readable.getReader();const e=this.readFromSerialPort(i);try{for(;;){const{value:t,done:n}=await e("\n");if(t){const{method:e,data:n}=this.parseResponse(t);if("/ping"===e&&this.log("Pong"),-1===vz.PUBLIC_METHODS.indexOf(e))continue;this.log("Received: ",e,n),this.lastCommand&&(this.lastCommand.resolve(n),this.lastCommand=null)}if(n)return this.lastCommand=null,this.writer=null,void(r&&r())}}catch(v5){if(v5 instanceof Error)throw this.writer=null,n&&n(v5),this.lastCommand&&(this.lastCommand.reject(v5),this.lastCommand=null),v5}}})();const o=new window.TextEncoderStream;o.readable.pipeTo(s.writable),this.writer=o.writable.getWriter(),await this.sendCommand(vz.METHOD_PING),await this.sendCommand(vz.METHOD_PING,[window.location.host]),t&&t(),s.addEventListener("disconnect",()=>{this.log("Disconnected"),this.lastCommand=null,this.writer=null,e&&e()})}async sendCommand(t,e=[]){if(!this.writer)return;this.log("Send command",t,e);const n=[t].concat(e).join(" ");await this.writer.write(n+"\n")}readFromSerialPort(t){let e,n=[];return async(r="\n")=>{if(n.length)return{value:n.shift().trim(),done:!1};const i=[];for(e&&(i.push(e),e=void 0);;){const{value:s,done:o}=await t.read();if(s){const t=s.split(r);if(t.length>1)return i.push(t.shift()),e=t.pop(),n=t,{value:i.join("").trim(),done:!1};i.push(s)}if(o)return{value:i.join("").trim(),done:!0}}}}parseResponse(t){const e=t.split(" ")[0];return{method:e,data:t.substring(e.length).trim()}}async nip04Encrypt(t,e){const n=bS(await this.callMethodOnDevice(vz.METHOD_SHARED_SECRET,[pz(t)]));let r=Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(16))),i=gz.encode(e),s=await crypto.subtle.importKey("raw",n,{name:"AES-CBC"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-CBC",iv:r},s,i);return`${mz(new Uint8Array(o))}?iv=${mz(new Uint8Array(r.buffer))}`}async nip04Decrypt(t,e){let[n,r]=e.split("?iv=");const i=bS(await this.callMethodOnDevice(vz.METHOD_SHARED_SECRET,[pz(t)]));let s=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["decrypt"]),o=yz(n),a=yz(r),l=await crypto.subtle.decrypt({name:"AES-CBC",iv:a},s,o);return fz.decode(l)}async getPublicKey(){const t=await this.callMethodOnDevice(vz.METHOD_PUBLIC_KEY,[]);return this.pubkey=t,t}async restore(t){await this.callMethodOnDevice(vz.METHOD_RESTORE,[vS(t)])}async signEvent(t){const e=t.pubkey||this.pubkey;if(!e)throw new Error("Unknown signer pubkey");const n={...t,id:EL({...t,pubkey:e})},r=await this.callMethodOnDevice(vz.METHOD_SIGN_MESSAGE,[n.id]),i={...n,sig:r,pubkey:e};if(!this.verifyEvent(i))throw new Error("Invalid signature");return i}ping(){this.sendCommand(vz.METHOD_PING,[window.location.host])}static SUPPORTED="navigator"in globalThis&&!!navigator.serial;static METHOD_PING="/ping";static METHOD_LOG="/log";static METHOD_SIGN_MESSAGE="/sign-message";static METHOD_SHARED_SECRET="/shared-secret";static METHOD_PUBLIC_KEY="/public-key";static METHOD_RESTORE="/restore";static PUBLIC_METHODS=[vz.METHOD_PUBLIC_KEY,vz.METHOD_SIGN_MESSAGE,vz.METHOD_SHARED_SECRET,vz.METHOD_RESTORE]}function bz(){return"undefined"!=typeof navigator&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)}const wz=Object.freeze(Object.defineProperty({__proto__:null,isMobile:bz},Symbol.toStringTag,{value:"Module"})),_z="marco:nostr_pubkey",xz="marco:nostr_signer_type",Cz="marco:nostr_connect_local_key",Sz="marco:nostr_connect_remote_pubkey",kz="marco:nostr_connect_relay",Ez="wss://relay.nsec.app";class Tz extends qf{static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"pubkey",[Is],function(){return null})}#H=void fF(this,"pubkey");static{dF(this.prototype,"signerType",[Is],function(){return null})}#G=void fF(this,"signerType");static{dF(this.prototype,"connectStatus",[Is],function(){return null})}#K=void fF(this,"connectStatus");static{dF(this.prototype,"connectUri",[Is],function(){return null})}#Z=void fF(this,"connectUri");_signerInstance=null;constructor(){super(...arguments),"undefined"!=typeof localStorage&&(localStorage.debug="applesauce:*");const t=localStorage.getItem(_z),e=localStorage.getItem(xz);t&&(this.pubkey=t,this.signerType=e||"extension",this._verifyPubkey())}async _verifyPubkey(){if("extension"===this.signerType){if(void 0===window.nostr)return void this.disconnect();try{const t=new kF,e=await t.getPublicKey();e!==this.pubkey&&(this.pubkey=e,localStorage.setItem(_z,this.pubkey)),this.nostrData.loadProfile(this.pubkey)}catch(ej){console.warn("Failed to verify extension nostr pubkey, logging out",ej),this.disconnect()}}else if("connect"===this.signerType)try{await this._initConnectSigner()}catch(ej){console.warn("Failed to verify connect nostr pubkey, logging out",ej),this.disconnect()}}get isMobile(){return bz()}get isConnected(){return!!this.pubkey&&("extension"!==this.signerType||void 0!==window.nostr)}get signer(){return this._signerInstance?this._signerInstance:"extension"===this.signerType&&void 0!==window.nostr?new kF:(this.signerType,null)}async connectWithExtension(){if(void 0===window.nostr)throw new Error("No NIP-07 Nostr extension found (e.g., Alby, nos2x).");try{return this._signerInstance=new kF,this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="extension",localStorage.setItem(_z,this.pubkey),localStorage.setItem(xz,"extension"),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(v5){throw console.error("Failed to get public key from extension:",v5),v5}}_getLocalSigner(){let t,e=localStorage.getItem(Cz);return e?t=RF.fromKey(e):(t=new RF,e=Array.from(t.key).map(t=>t.toString(16).padStart(2,"0")).join(""),localStorage.setItem(Cz,e)),t}async connectWithApp(){this.connectStatus="waiting";try{const e=this._getLocalSigner(),n=Ez;localStorage.setItem(kz,n),this.nostrRelay.pool.relay(n).eoseTimeout=18e4,this._signerInstance=new LF({pool:this.nostrRelay.pool,relays:[n],signer:e,onAuth:async t=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${t}`)&&window.open(t,"_blank")}}),this.connectUri=this._signerInstance.getNostrConnectURI({name:"Marco",url:window.location.origin,description:"An unhosted maps application.",icons:[]}),this.isMobile&&(console.debug("Mobile detected, triggering deep link intent."),window.location.href=this.connectUri),console.debug("Opening signer connection to relay..."),await this._signerInstance.open(),console.debug("Signer connection opened successfully."),console.debug("Waiting for remote signer to ack via relay...");try{await this._signerInstance.waitForSigner(),console.debug("Remote signer ack received!")}catch(t){throw console.error("Error while waiting for remote signer ack:",t),t}return this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="connect",this.connectStatus="connected",localStorage.setItem(_z,this.pubkey),localStorage.setItem(xz,"connect"),localStorage.setItem(Sz,this._signerInstance.remote),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(v5){throw this.connectStatus=null,console.error("Failed to connect via Nostr Connect:",v5),v5}}async _initConnectSigner(){const t=localStorage.getItem(Sz),e=localStorage.getItem(kz)||Ez;if(!t)throw new Error("Missing Nostr Connect remote pubkey.");const n=this._getLocalSigner();if(this.nostrRelay.pool.relay(e).eoseTimeout=18e4,this._signerInstance=new LF({pool:this.nostrRelay.pool,relays:[e],signer:n,remote:t,onAuth:async t=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${t}`)&&window.open(t,"_blank")}}),await this._signerInstance.open(),await this._signerInstance.getPublicKey()!==this.pubkey)throw new Error("Remote signer pubkey mismatch");this.nostrData.loadProfile(this.pubkey)}async signEvent(t){if(!this.signer)throw new Error("Not connected or extension missing. Please connect Nostr again.");return await this.signer.signEvent(t)}async disconnect(){this.pubkey=null,this.nostrData?.loadProfile(null),this.signerType=null,this.connectStatus=null,this.connectUri=null,this._signerInstance&&"function"==typeof this._signerInstance.close&&await this._signerInstance.close(),this._signerInstance=null,localStorage.removeItem(_z),localStorage.removeItem(xz),localStorage.removeItem(Cz),localStorage.removeItem(Sz),localStorage.removeItem(kz)}}const Rz=Object.freeze(Object.defineProperty({__proto__:null,default:Tz},Symbol.toStringTag,{value:"Module"})),Mz=(t,e)=>e.some(e=>t instanceof e);let Lz,Iz;const Pz=new WeakMap,Az=new WeakMap,Oz=new WeakMap;let Fz={get(t,e,n){if(t instanceof IDBTransaction){if("done"===e)return Pz.get(t);if("store"===e)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Dz(t[e])},set:(t,e,n)=>(t[e]=n,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function zz(t){Fz=t(Fz)}function Dz(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,n)=>{const r=()=>{t.removeEventListener("success",i),t.removeEventListener("error",s)},i=()=>{e(Dz(t.result)),r()},s=()=>{n(t.error),r()};t.addEventListener("success",i),t.addEventListener("error",s)});return Oz.set(e,t),e}(t);if(Az.has(t))return Az.get(t);const e=function(t){return"function"==typeof t?(e=t,(Iz||(Iz=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Nz(this),t),Dz(this.request)}:function(...t){return Dz(e.apply(Nz(this),t))}):(t instanceof IDBTransaction&&function(t){if(Pz.has(t))return;const e=new Promise((e,n)=>{const r=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",s),t.removeEventListener("abort",s)},i=()=>{e(),r()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),r()};t.addEventListener("complete",i),t.addEventListener("error",s),t.addEventListener("abort",s)});Pz.set(t,e)}(t),Mz(t,Lz||(Lz=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,Fz):t);var e}(t);return e!==t&&(Az.set(t,e),Oz.set(e,t)),e}const Nz=t=>Oz.get(t),jz=["get","getKey","getAll","getAllKeys","count"],Bz=["put","add","delete","clear"],Uz=new Map;function $z(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(Uz.get(e))return Uz.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,i=Bz.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!jz.includes(n))return;const s=async function(t,...e){const s=this.transaction(t,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(e.shift())),(await Promise.all([o[n](...e),i&&s.done]))[0]};return Uz.set(e,s),s}zz(t=>({...t,get:(e,n,r)=>$z(e,n)||t.get(e,n,r),has:(e,n)=>!!$z(e,n)||t.has(e,n)}));const qz=["continue","continuePrimaryKey","advance"],Vz={},Wz=new WeakMap,Hz=new WeakMap,Gz={get(t,e){if(!qz.includes(e))return t[e];let n=Vz[e];return n||(n=Vz[e]=function(...t){Wz.set(this,Hz.get(this)[e](...t))}),n}};async function*Kz(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;const n=new Proxy(e,Gz);for(Hz.set(n,e),Oz.set(n,Nz(e));e;)yield n,e=await(Wz.get(n)||e.continue()),Wz.delete(n)}function Zz(t,e){return e===Symbol.asyncIterator&&Mz(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===e&&Mz(t,[IDBIndex,IDBObjectStore])}function Yz(t){return 0===t||3===t||t>=1e4&&t<2e4}function Xz(t){return t>=3e4&&t<4e4}function Jz(t){return t>=2e4&&t<3e4}zz(t=>({...t,get:(e,n,r)=>Zz(e,n)?Kz:t.get(e,n,r),has:(e,n)=>Zz(e,n)||t.has(e,n)}));const Qz=Symbol.for("indexable-tags");function tD(t,e){if(t.ids&&-1===t.ids.indexOf(e.id))return!1;if(t.kinds&&-1===t.kinds.indexOf(e.kind))return!1;if(t.authors&&-1===t.authors.indexOf(e.pubkey))return!1;if(t.since&&e.created_att.until)return!1;const n=function(t){let e=Reflect.get(t,Qz);if(!e){e=new Set;for(const n of t.tags)n.length>=2&&1===n[0].length&&e.add(n[0]+":"+n[1]);Reflect.set(t,Qz,e)}return e}(e);for(const r in t)if("&"===r[0]){const e=r.slice(1),i=t[r];if(i&&i.length>0)for(const t of i)if(!n.has(e+":"+t))return!1}for(const r in t)if("#"===r[0]){const e=r.slice(1),i=t[r];if(i){const r=t[`&${e}`],s=r?i.filter(t=>!r.includes(t)):i;if(0===s.length)continue;if(!s.some(t=>n.has(e+":"+t)))return!1}}return!0}function eD(t,e){for(let n=0;nt.length>=2&&1===t[0].length&&rD.includes(t[0])).map(t=>t[0]+t[1])}function oD(t){if(Reflect.has(t,iD))return Reflect.get(t,iD);let e;if(Yz(t.kind)||Xz(t.kind)){const n=t.tags.find(t=>"d"===t[0])?.[1];e=t.kind+":"+t.pubkey+":"+(n??"")}else e=t.id;return Reflect.set(t,iD,e),e}async function aD(t="nostr-idb",e){return await function(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(t,e),a=Dz(o);return r&&o.addEventListener("upgradeneeded",t=>{r(Dz(o.result),t.oldVersion,t.newVersion,Dz(o.transaction),t)}),n&&o.addEventListener("blocked",t=>n(t.oldVersion,t.newVersion,t)),a.then(t=>{s&&t.addEventListener("close",()=>s()),i&&t.addEventListener("versionchange",t=>i(t.oldVersion,t.newVersion,t))}).catch(()=>{}),a}(t,3,{...e,async upgrade(t,e,n,r,i){if(0===e){const e=t.createObjectStore("events");e.createIndex("id","event.id",{unique:!0}),e.createIndex("pubkey","event.pubkey"),e.createIndex("kind","event.kind"),e.createIndex("created_at","event.created_at"),e.createIndex("tags","tags",{multiEntry:!0}),t.createObjectStore("used",{keyPath:"uid"}).createIndex("date","date")}1===e&&(t.deleteObjectStore("events"),t.deleteObjectStore("used"),t.deleteObjectStore("seen")),e<=2&&await async function(t){const e=t.objectStore("events");let n=await e.openCursor();const r=[];for(;n;){const t=n.primaryKey,e=n.value,i=e.event;if(Yz(i.kind)||Xz(i.kind)){const n=oD(i);t!==n&&r.push({oldKey:t,newKey:n,value:e})}n=await n.continue()}for(const{oldKey:i,newKey:s,value:o}of r)await e.delete(i),await e.put(o,s)}(r)}})}function lD(t,e){return e.created_at-t.created_at}function cD(t,e=[],n){const r=[],i=new Set;if(n)for(const l of e){const t=n.getPubkeyIndex(l);if(t){for(const e of t)i.add(e);r.push(l)}}if(r.length===e.length)return Promise.resolve(i);const s=t.transaction("events","readonly"),o=s.objectStore("events").index("pubkey"),a=e.filter(t=>!r.includes(t)).map(t=>o.getAllKeys(t).then(e=>((t,e)=>{for(const n of e)i.add(n);n&&n.setPubkeyIndex(t,new Set(e))})(t,e)));return s.commit(),Promise.all(a).then(()=>i)}function uD(t,e,n,r){const i=[],s=new Set;if(r)for(const c of n){const t=r.getTagIndex(e+c);if(t){for(const e of t)s.add(e);i.push(c)}}if(i.length===n.length)return Promise.resolve(s);const o=t.transaction("events","readonly"),a=o.objectStore("events").index("tags"),l=n.map(t=>a.getAllKeys(e+t).then(n=>((t,n)=>{for(const e of n)s.add(e);r&&r.setTagIndex(e+t,new Set(n))})(t,n)));return o.commit(),Promise.all(l).then(()=>s)}function hD(t,e,n,r){if(0===n.length)return Promise.resolve(new Set);if(1===n.length)return uD(t,e,n,r);const i=[],s=[];if(r)for(const c of n){const t=r.getTagIndex(e+c);t&&(s.push(t),i.push(c))}if(i.length===n.length)return Promise.resolve(dD(s));const o=t.transaction("events","readonly"),a=o.objectStore("events").index("tags"),l=n.filter(t=>!i.includes(t)).map(t=>a.getAllKeys(e+t).then(n=>((t,n)=>{const i=new Set(n);s.push(i),r&&r.setTagIndex(e+t,i)})(t,n)));return o.commit(),Promise.all(l).then(()=>dD(s))}function dD(t){if(0===t.length)return new Set;const e=t.slice().sort((t,e)=>t.size-e.size);let n=e[0];for(let r=1;r!r.includes(t)).map(t=>o.getAllKeys(t).then(e=>((t,e)=>{for(const n of e)i.add(n);n&&n.setKindIndex(t,new Set(e))})(t,e)));return s.commit(),Promise.all(a).then(()=>i)}async function fD(t,e,n){let r;if(void 0!==e&&void 0!==n)r=IDBKeyRange.bound(e,n);else if(void 0!==e)r=IDBKeyRange.lowerBound(e);else{if(void 0===n)throw new Error("Missing since or until");r=IDBKeyRange.upperBound(n)}return(await t.getAllKeysFromIndex("events","created_at",r)).reverse()}async function gD(t,e,n){if(e.search)return new Set;if(e.ids)return new Set(e.ids);let r=null;const i=t=>{const e=t instanceof Set?t:new Set(t);if(r)for(const n of r)e.has(n)||r.delete(n);else r=e;return r};let s=null;void 0!==e.since&&(s=await fD(t,e.since,e.until),i(s));for(const o of rD){const r=e[`&${o}`],s=e[`#${o}`];if(r?.length&&i(await hD(t,o,r,n)),s?.length){const e=r?.length?s.filter(t=>!r.includes(t)):s;e.length>0&&i(await uD(t,o,e,n))}}if(e.authors&&i(await cD(t,e.authors,n)),e.kinds&&i(await pD(t,e.kinds,n)),void 0===e.since&&void 0!==e.until&&(s=await fD(t,e.since,e.until),i(s)),e.limit&&s){const t=new Set;for(const n of s){if(t.size>=e.limit)break;r.has(n)&&t.add(n)}return t}if(null===r)throw new Error("Empty filter");return r}async function mD(t,e,n){if(0===e.length)throw new Error("No Filters");let r=new Set;for(const i of e){const e=await gD(t,i,n);for(const t of e)r.add(t)}return r}async function yD(t,e,n,r){const i=await mD(t,e,n);return await async function(t,e,n,r){const i=[];let s=[];if(r)for(const d of e){const t=r.get(d);t?i.push(t):s.push(d)}else s=e;const o=t.transaction("events","readonly"),a=o.objectStore("events"),l=t=>t&&i.push(t.event),c=Array.from(s).map(t=>a.get(t).then(l));o.commit();const u=await Promise.all(c).then(()=>i.sort(lD));let h=1/0;for(const d of n)d.limit&&d.limith&&(u.length=h),u}(t,Array.from(i),e,r)}async function vD(t,e,n){return(await mD(t,e,n)).size}const bD=Object.freeze(Object.defineProperty({__proto__:null,countEventsForFilters:vD,getEventsForFilters:yD,getIdsForFilter:gD,getIdsForFilters:mD,queryForKinds:pD,queryForPubkeys:cD,queryForTag:uD,queryForTagAnd:hD,queryForTime:fD},Symbol.toStringTag,{value:"Module"})),wD=KA("nostr-idb"),_D=wD.extend("prune");async function xD(t,e,n){const r=t.transaction("events","readwrite"),i=r.objectStore("events"),s=await i.get(e);if(!s)return await r.commit(),!1;if(await i.delete(e),await r.commit(),n){const t=s.event;n.removeEvent(t)}return!0}const CD=wD.extend("WriteQueue");class SD{db;queuedIds=new Set;eventQueue=[];lastUsedQueue=new Set;processEvents=null;constructor(t){this.db=t}addEvent(t){this.queuedIds.has(t.id)||(this.eventQueue.push(t),this.queuedIds.add(t.id),this.touch(t))}addEvents(t){const e=t.filter(t=>!this.queuedIds.has(t.id));0!==e.length&&(this.eventQueue.push(...e),this.touch(e))}touch(t){if(Array.isArray(t))for(const e of t)this.lastUsedQueue.add(oD(e));else this.lastUsedQueue.add(oD(t))}matchPending(t){return this.eventQueue.filter(e=>eD(t,e))}async flush(t=1e3){if(this.eventQueue.length>0){let e=[];for(let n=0;nfunction(t){if("object"!=typeof t||null===t)return!1;if("number"!=typeof t.kind)return!1;if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if("string"!=typeof t.pubkey)return!1;if(!/^[a-f0-9]{64}$/.test(t.pubkey))return!1;if(!Array.isArray(t.tags))return!1;for(const e of t.tags){if(!Array.isArray(e))return!1;for(const t of e)if("string"!=typeof t)return!1}return!0}(t))).filter(t=>Yz(t.kind)||Xz(t.kind)),r={};if(n.length>0){const e=t.transaction("events","readonly"),i=n.map(t=>{const n=oD(t);return e.store.get(n).then(t=>t&&(r[n]=t.event.created_at))});e.commit(),await Promise.all(i)}const i=t.transaction("events","readwrite");for(const s of e){const t=oD(s);(!r[t]||s.created_at>r[t])&&i.objectStore("events").put({event:s,tags:sD(s)},t)}await i.commit()}(this.db,e),CD(`Wrote ${e.length} to database`),this.eventQueue.length>0&&CD(`${this.eventQueue.length} left`)}this.lastUsedQueue.size>0&&(await async function(t,e){const n=t.transaction("used","readwrite"),r=Math.floor((new Date).valueOf()/1e3);for(const i of e)n.objectStore("used").put({uid:i,date:r});await n.commit()}(this.db,this.lastUsedQueue),this.lastUsedQueue.clear())}clear(){this.eventQueue=[]}}const kD=wD.extend("cache:indexes");class ED extends Set{type;key;constructor(t,e,n){super(t),this.type=e,this.key=n}}class TD{kinds=new Map;pubkeys=new Map;tags=new Map;get count(){return this.kinds.size+this.pubkeys.size+this.tags.size}max=1e3;lastUsed=[];useIndex(t){const e=this.lastUsed.indexOf(t);-1!==e&&this.lastUsed.splice(e,e+1),this.lastUsed.push(t)}getKindIndex(t){const e=this.kinds.get(t);return e&&this.useIndex(e),e}setKindIndex(t,e){const n=new ED(e,"kind",t);this.kinds.set(t,n),this.useIndex(n),this.pruneIndexes()}getPubkeyIndex(t){const e=this.pubkeys.get(t);return e&&this.useIndex(e),e}setPubkeyIndex(t,e){const n=new ED(e,"pubkey",t);this.pubkeys.set(t,n),this.useIndex(n),this.pruneIndexes()}getTagIndex(t){const e=this.tags.get(t);return e&&this.useIndex(e),e}setTagIndex(t,e){const n=new ED(e,"tag",t);this.tags.set(t,n),this.useIndex(n),this.pruneIndexes()}addEventToIndexes(t){this.getKindIndex(t.kind)?.add(t.id),this.getPubkeyIndex(t.pubkey)?.add(t.id);const e=sD(t);for(const n of e)this.getTagIndex(n)?.add(t.id)}removeEvent(t){this.getKindIndex(t.kind)?.delete(t.id),this.getPubkeyIndex(t.pubkey)?.delete(t.id);const e=sD(t);for(const n of e)this.getTagIndex(n)?.delete(t.id)}clear(){this.kinds.clear(),this.pubkeys.clear(),this.tags.clear(),this.lastUsed=[]}pruneIndexes(){for(;this.lastUsed.length>0&&this.lastUsed.length>this.max;){const t=this.lastUsed.shift();if(!t)return;switch(kD(`Forgetting ${t.type}:${t.key}`),t.type){case"kind":this.kinds.delete(t.key);break;case"pubkey":this.pubkeys.delete(t.key);break;case"tag":this.tags.delete(t.key)}}}}const RD={},MD=function(t,e){let n=Promise.resolve();if(e&&e.length>0){document.getElementsByTagName("link");const t=document.querySelector("meta[property=csp-nonce]"),i=t?.nonce||t?.getAttribute("nonce");r=e.map(t=>{if((t=function(t){return"/"+t}(t))in RD)return;RD[t]=!0;const e=t.endsWith(".css"),n=e?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${t}"]${n}`))return;const r=document.createElement("link");return r.rel=e?"stylesheet":"modulepreload",e||(r.as="script"),r.crossOrigin="",r.href=t,i&&r.setAttribute("nonce",i),document.head.appendChild(r),e?new Promise((e,n)=>{r.addEventListener("load",e),r.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${t}`)))}):void 0}),n=Promise.all(r.map(t=>Promise.resolve(t).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var r;function i(t){const e=new Event("vite:preloadError",{cancelable:!0});if(e.payload=t,window.dispatchEvent(e),!e.defaultPrevented)throw t}return n.then(e=>{for(const t of e||[])"rejected"===t.status&&i(t.reason);return t().catch(i)})},LD={batchWrite:1e3,writeInterval:100,cacheIndexes:1e3,pruneInterval:6e4,maxEvents:1e4},ID=wD.extend("nostridb");class PD{options;running=!1;writeInterval;pruneInterval;eventMap=new Map;writeQueue=null;indexCache;db=null;baseEoseTimeout=4400;subscriptions=new Map;constructor(t,e={}){this.options={...LD,...e},t&&(this.db=t,this.writeQueue=new SD(t)),this.indexCache=new TD,this.indexCache.max=this.options.cacheIndexes,this.start()}async getDb(){return this.db||(this.db=await aD()),this.db}async getWriteQueue(){if(this.writeQueue)return this.writeQueue;const t=await this.getDb();return this.writeQueue=new SD(t),this.writeQueue}async flush(){const t=await this.getWriteQueue();await t.flush(),this.writeInterval=setTimeout(this.flush.bind(this),this.options.writeInterval)}async start(){if(this.running)return;ID("Starting"),this.running=!0;const t=await this.getDb();await this.flush(),this.pruneInterval=setInterval(()=>{!async function(t,e){const n=await function(t){return t.transaction("events","readonly").store.count()}(t);if(n<=e)return;const r=n-e;if(r<=0)return;_D(`Pruning database to ${e}`);const i=(await t.getAll("used")).sort((t,e)=>t.date-e.date),s=[];let o=r;for(const u of i){if(o<=0)break;const t=u.uid;s.push(t),o--}if(0===s.length)return;const a=t.transaction("events","readwrite"),l=t.transaction("used","readwrite"),c=[];for(const u of s)c.push(a.store.delete(u)),c.push(l.store.delete(u));a.commit(),l.commit(),await Promise.all(c),_D(`Removed ${s.length} old events`)}(t,this.options.maxEvents)},this.options.pruneInterval)}async stop(){this.running&&(this.writeInterval&&(clearTimeout(this.writeInterval),this.writeInterval=void 0),this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0),this.running=!1,ID("Stopped"))}async add(t){Jz(t.kind)||((await this.getWriteQueue()).addEvent(t),this.indexCache.addEventToIndexes(t));const e=oD(t);if(!this.eventMap.has(e)){Jz(t.kind)||this.eventMap.set(e,t);for(const[e,n]of this.subscriptions)n.event&&eD(n.filters,t)&&n.event(t)}return!0}async event(t){const e=await this.getDb(),n=await e.get("events",t);return n?.event}async replaceable(t,e,n){return this.event([t,e,n??""].join(":"))}async count(t){const e=Array.isArray(t)?t:[t],n=await this.getDb();return await vD(n,e)}async query(t){const e=Array.isArray(t)?t:[t],n=await this.getDb(),r=(await this.getWriteQueue()).matchPending(e),i=await yD(n,e,this.indexCache,this.eventMap);this.addToEventMaps(i);const s=new Set(r.map(t=>t.id));return r.length>0?[...i.filter(t=>!s.has(t.id)),...r].sort(lD):i}async*subscribe(t){const e=Array.isArray(t)?t:[t],n=[],r=new Set;let i=null,s=!1;const o=this.subscribeInternal(e,{event:t=>{if(!r.has(t.id)&&(r.add(t.id),n.push(t),i)){const t=i;i=null,t()}},complete:()=>{if(s=!0,i){const t=i;i=null,t()}}});try{for(;;){for(;n.length>0;)yield n.shift();if(s)break;await new Promise(t=>{i=t})}}finally{o.close()}}async supports(){return[]}async deleteEvent(t){const e=await this.getDb(),n=await xD(e,t,this.indexCache);return this.eventMap.delete(t),n}async deleteReplaceable(t,e,n){const r=await this.getDb(),i=await async function(t,e,n,r,i){if(!Yz(n)&&!Xz(n))throw new Error(`Kind ${n} is not replaceable`);const s=`${n}:${e}:${r??""}`;return await xD(t,s,i)}(r,t,e,n,this.indexCache);if(i){const r=`${e}:${t}:${n??""}`;this.eventMap.delete(r)}return i}async deleteByFilters(t){const e=Array.isArray(t)?t:[t],n=await this.getDb(),r=await this.getEventIdsForFilters(e),i=await async function(t,e,n){const r=await mD(t,e,n);return await async function(t,e,n){if(0===e.length)return 0;const r=t.transaction("events","readwrite"),i=r.objectStore("events");let s=0;const o=[];for(const a of e){const t=await i.get(a);t&&(o.push(t.event),await i.delete(a),s++)}if(await r.commit(),n&&o.length>0)for(const a of o)n.removeEvent(a);return s}(t,Array.from(r),n)}(n,e,this.indexCache);if(i>0)for(const s of r)this.eventMap.delete(s);return i}async deleteAllEvents(){const t=await this.getDb();await async function(t,e){const n=t.transaction("events","readwrite");await n.objectStore("events").clear(),await n.commit(),e&&e.clear()}(t,this.indexCache),this.eventMap.clear()}async getEventIdsForFilters(t){const e=await this.getDb(),{getIdsForFilters:n}=await MD(async()=>{const{getIdsForFilters:t}=await Promise.resolve().then(()=>bD);return{getIdsForFilters:t}},void 0),r=await n(e,t,this.indexCache);return Array.from(r)}addToEventMaps(t){for(const e of t)this.eventMap.set(oD(e),e)}subscribeInternal(t,e){const n=((t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((t,e)=>t+((e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e>62?"-":"_"),""))(),r={id:n,filters:t,closed:!1,close:()=>this.unsubscribe(n),...e};return this.subscriptions.set(n,r),this.executeSubscription(r),r}async executeSubscription(t){const e=(new Date).valueOf();ID(`Running ${t.id}`,t.filters);const n=(await this.getWriteQueue()).matchPending(t.filters);return new Promise(async r=>{const i=await this.getDb(),s=setTimeout(()=>{t.eose&&!t.closed&&t.eose(),r()},this.baseEoseTimeout);yD(i,t.filters,this.indexCache,this.eventMap).then(i=>{if(clearTimeout(s),this.addToEventMaps(i),t.event&&!t.closed){const r=new Set(n.map(t=>t.id)),s=n.length>0?[...i.filter(t=>!r.has(t.id)),...n].sort(lD):i;for(const e of s)try{t.event(e)}catch(v5){ID("event handler failed with error",v5)}const o=(new Date).valueOf()-e;ID(`Finished ${t.id} took ${o}ms and got ${s.length} events`)}t.eose&&!t.closed&&t.eose(),r()})})}unsubscribe(t){const e=this.subscriptions.get(t);e&&(ID(`Closing ${t}`),e.closed=!0,e.complete?.(),this.subscriptions.delete(t))}}function AD(t){if(!t)return"";let e=t.trim().toLowerCase();if(!e)return"";for(e.startsWith("ws://")||e.startsWith("wss://")||(e="wss://"+e);e.endsWith("/");)e=e.slice(0,-1);return e}function OD(t){if(!t||0===t.length)return[];const e=[...t].sort((t,e)=>t.created_at-e.created_at),n=[];for(const i of e){const t=i.tags.filter(t=>"imeta"===t[0]);for(const e of t){let t=null,r=null,s=null,o=!1,a=16/9;for(const n of e.slice(1))if(n.startsWith("url "))t=n.substring(4);else if(n.startsWith("thumb "))r=n.substring(6);else if(n.startsWith("blurhash "))s=n.substring(9);else if(n.startsWith("dim ")){const t=n.substring(4),[e,r]=t.split("x").map(Number);e&&r&&(a=e/r,e>r&&(o=!0))}t&&n.push({eventId:i.id,pubkey:i.pubkey,createdAt:i.created_at,url:t,thumbUrl:r,blurhash:s,isLandscape:o,aspectRatio:a})}}if(0===n.length)return[];const r=n.findIndex(t=>t.isLandscape);if(r>0){const[t]=n.splice(r,1);n.unshift(t)}return n}const FD=Object.freeze(Object.defineProperty({__proto__:null,normalizeRelayUrl:AD,parsePlacePhotos:OD},Symbol.toStringTag,{value:"Module"})),zD="0123456789bcdefghjkmnpqrstuvwxyz";class DD{static encode(t,e,n){if(void 0===n){for(let n=1;n<=12;n++){const r=DD.encode(t,e,n),i=DD.decode(r);if(i.lat==t&&i.lon==e)return r}n=12}if(t=Number(t),e=Number(e),n=Number(n),isNaN(t)||isNaN(e)||isNaN(n))throw new Error("Invalid geohash");let r=0,i=0,s=!0,o="",a=-90,l=90,c=-180,u=180;for(;o.length=t?(r=2*r+1,c=t):(r*=2,u=t)}else{const e=(a+l)/2;t>=e?(r=2*r+1,a=e):(r*=2,l=e)}s=!s,5==++i&&(o+=zD.charAt(r),i=0,r=0)}return o}static decode(t){const e=DD.bounds(t),n=e.sw.lat,r=e.sw.lon,i=e.ne.lat,s=e.ne.lon;let o=(n+i)/2,a=(r+s)/2;return o=o.toFixed(Math.floor(2-Math.log(i-n)/Math.LN10)),a=a.toFixed(Math.floor(2-Math.log(s-r)/Math.LN10)),{lat:Number(o),lon:Number(a)}}static bounds(t){if(0==t.length)throw new Error("Invalid geohash");t=t.toLowerCase();let e=!0,n=-90,r=90,i=-180,s=180;for(let o=0;o=0;t--){const o=l>>t&1;if(e){const t=(i+s)/2;1==o?i=t:s=t}else{const t=(n+r)/2;1==o?n=t:r=t}e=!e}}return{sw:{lat:n,lon:i},ne:{lat:r,lon:s}}}static adjacent(t,e){if(t=t.toLowerCase(),e=e.toLowerCase(),0==t.length)throw new Error("Invalid geohash");if(-1=="nsew".indexOf(e))throw new Error("Invalid direction");const n=t.slice(-1);let r=t.slice(0,-1);const i=t.length%2;return-1!={n:["prxz","bcfguvyz"],s:["028b","0145hjnp"],e:["bcfguvyz","prxz"],w:["0145hjnp","028b"]}[e][i].indexOf(n)&&""!=r&&(r=DD.adjacent(r,e)),r+zD.charAt({n:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],s:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],e:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],w:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]}[e][i].indexOf(n))}static neighbours(t){return{n:DD.adjacent(t,"n"),ne:DD.adjacent(DD.adjacent(t,"n"),"e"),e:DD.adjacent(t,"e"),se:DD.adjacent(DD.adjacent(t,"s"),"e"),s:DD.adjacent(t,"s"),sw:DD.adjacent(DD.adjacent(t,"s"),"w"),w:DD.adjacent(t,"w"),nw:DD.adjacent(DD.adjacent(t,"n"),"w")}}}function ND(t){const{minLat:e,minLon:n,maxLat:r,maxLon:i}=t,s=new Set;if(Math.abs(r-e)>20||Math.abs(i-n)>20)return console.warn("BBox too large for 4-char geohash scanning, aborting fine scan."),[];for(let o=e;o<=r+.1;o+=.1)for(let t=n;t<=i+.1;t+=.1){const e=Math.min(o,r),n=Math.min(t,i);try{const t=DD.encode(e,n,4);s.add(t)}catch(ej){}}try{s.add(DD.encode(e,n,4))}catch(ej){}try{s.add(DD.encode(r,i,4))}catch(ej){}try{s.add(DD.encode(e,i,4))}catch(ej){}try{s.add(DD.encode(r,n,4))}catch(ej){}return Array.from(s)}const jD=Object.freeze(Object.defineProperty({__proto__:null,getGeohashPrefixesInBbox:ND},Symbol.toStringTag,{value:"Module"})),BD=["wss://purplepag.es","wss://relay.damus.io","wss://nos.lol"],UD=["wss://nostr.kosmos.org"],$D=[];class qD extends qf{static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");store=new VO;static{dF(this.prototype,"profile",[Is],function(){return null})}#Y=void fF(this,"profile");static{dF(this.prototype,"mailboxes",[Is],function(){return null})}#X=void fF(this,"mailboxes");static{dF(this.prototype,"blossomServers",[Is],function(){return[]})}#J=void fF(this,"blossomServers");static{dF(this.prototype,"placePhotos",[Is],function(){return[]})}#Q=void fF(this,"placePhotos");_profileSub=null;_mailboxesSub=null;_blossomSub=null;_photosSub=null;_requestSub=null;_cachePromise=null;loadedGeohashPrefixes=new Set;constructor(){super(...arguments),this._cachePromise=aD("applesauce-events").then(async t=>{this.cache=new PD(t,{cacheIndexes:1e3,maxEvents:1e4}),await this.cache.start(),this._stopPersisting=function(t,e,n){const r=n?.batchTime??5e3,i=t.insert$.pipe(mA(t=>{return e=t,!(!0===Reflect.get(e,NL));var e}),n?.maxBatchSize?yA(r,void 0,n?.maxBatchSize??100):yA(r),mA(t=>t.length>0)).subscribe(t=>{e(t).then(()=>YA(`Saved ${t.length} events to cache`)).catch(e=>YA(`Failed to save ${t.length} events to cache`,e))});return()=>i.unsubscribe()}(this.store,async t=>{const e=t.filter(t=>0===t.kind||10002===t.kind||10063===t.kind||360===t.kind);e.length>0&&await Promise.all(e.map(t=>this.cache.add(t)))},{batchTime:1e3,maxBatchSize:100})}),this.nostrRelay.pool.relays$.subscribe(()=>{})}get defaultReadRelays(){const t=(this.mailboxes?.inboxes||[]).map(AD).filter(Boolean),e=UD.map(AD).filter(Boolean);return Array.from(new Set([...e,...t]))}get defaultWriteRelays(){const t=(this.mailboxes?.outboxes||[]).map(AD).filter(Boolean),e=$D.map(AD).filter(Boolean);return Array.from(new Set([...e,...t]))}get activeReadRelays(){return this.settings.nostrReadRelays?Array.from(new Set(this.settings.nostrReadRelays.map(AD).filter(Boolean))):this.defaultReadRelays}get activeWriteRelays(){return this.settings.nostrWriteRelays?Array.from(new Set(this.settings.nostrWriteRelays.map(AD).filter(Boolean))):this.defaultWriteRelays}async loadPlacesInBounds(t){const e=ND(t).filter(t=>!this.loadedGeohashPrefixes.has(t));if(0!==e.length){console.debug("[nostr-data] Loading place photos for prefixes:",e);try{await this._cachePromise;const t=await this.cache.query([{kinds:[360],"#g":e}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(ej){console.warn("[nostr-data] Failed to read photos from local Nostr IDB cache",ej)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#g":e}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("[nostr-data] Error fetching place photos by geohash:",t)}});for(const t of e)this.loadedGeohashPrefixes.add(t)}}async loadPhotosForPlace(t){if(this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null),this.placePhotos=[],!t||!t.osmId||!t.osmType)return;const e=`osm:${t.osmType}:${t.osmId}`;this._photosSub=this.store.timeline([{kinds:[360],"#i":[e]}]).subscribe(t=>{this.placePhotos=t});try{await this._cachePromise;const t=await this.cache.query([{kinds:[360],"#i":[e]}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(ej){console.warn("[nostr-data] Failed to read photos for place from local Nostr IDB cache",ej)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#i":[e]}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("[nostr-data] Error fetching place photos for place:",t)}})}async loadProfile(t){if(!t)return;this.profile=null,this.mailboxes=null,this.blossomServers=[],this._cleanupSubscriptions(),this._profileSub=this.store.model(UO,t).subscribe(t=>{this.profile=t}),this._mailboxesSub=this.store.model(BO,t).subscribe(t=>{this.mailboxes=t}),this._blossomSub=this.store.replaceable(10063,t).subscribe(t=>{t&&t.tags?this.blossomServers=t.tags.filter(t=>"server"===t[0]&&t[1]).map(t=>t[1]):this.blossomServers=[]});try{await this._cachePromise;const e=await this.cache.query([{authors:[t],kinds:[0,10002,10063]}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(ej){console.warn("Failed to read from local Nostr IDB cache",ej)}const e=Array.from(new Set([...BD,...this.activeWriteRelays]));this._requestSub=this.nostrRelay.pool.request(e,[{authors:[t],kinds:[0,10002,10063]}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("Error fetching profile events:",t)}})}get userDisplayName(){if(this.profile){if(this.profile.nip05)return this.profile.nip05;if(this.profile.displayName||this.profile.display_name)return this.profile.displayName||this.profile.display_name;if(this.profile.name)return this.profile.name}if(this.nostrAuth.pubkey)try{const t=function(t,e){return function(t,e){let n=lk.toWords(e);return lk.encode("npub",n,5e3)}(0,e)}(0,bS(this.nostrAuth.pubkey));return`${t.slice(0,9)}...${t.slice(-4)}`}catch{return this.nostrAuth.pubkey}return"Not connected"}_cleanupSubscriptions(){this._requestSub&&(this._requestSub.unsubscribe(),this._requestSub=null),this._profileSub&&(this._profileSub.unsubscribe(),this._profileSub=null),this._mailboxesSub&&(this._mailboxesSub.unsubscribe(),this._mailboxesSub=null),this._blossomSub&&(this._blossomSub.unsubscribe(),this._blossomSub=null),this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null)}willDestroy(){super.willDestroy(...arguments),this._cleanupSubscriptions(),this._stopPersisting&&this._stopPersisting(),this.cache&&this.cache.stop()}}const VD=Object.freeze(Object.defineProperty({__proto__:null,default:qD},Symbol.toStringTag,{value:"Module"}));function WD(t){return NA(t=>"EOSE"!==t,t)}function HD(t){return vA(e=>WP({ok:!1,from:t.url,message:e?.message||"Unknown error"}))}class GD{relays$=new mP([]);status$;get relays(){if(this.relays$ instanceof mP)return this.relays$.value;throw new Error("This group was created with an observable, relays are not available")}constructor(t){this.relays$=Array.isArray(t)?new mP(t):t,this.status$=this.relays$.pipe(zA(t=>0===t.length?WP({}):fA(...t.map(t=>t.status$)).pipe(IA((t,e)=>({...t,[e.url]:e}),{}),FA({}))),OA(1))}get controlled(){return this.relays$ instanceof mP==0}has(t){if(this.controlled)throw new Error("This group was created with an observable, relays are not available");return"string"==typeof t?this.relays.some(e=>e.url===t):this.relays.includes(t)}add(t){this.has(t)||this.relays$.next([...this.relays,t])}remove(t){this.has(t)&&this.relays$.next(this.relays.filter(e=>e!==t))}internalSubscription(t,e=aP){const n=new WeakMap,r=this.relays$.pipe(function(t){return uP((e,n)=>{let r=null,i=!1;const s=()=>{i&&!r&&n.complete()};e.subscribe(hP(n,e=>{const i=r,o=r=hP(n,t=>n.next(t),()=>{r!==o&&null!==r||(r=null,s())});VP(t(e)).subscribe(r),i?.unsubscribe()},()=>{i=!0,s()}))})}(e=>{const r=[];for(const i of e){if(n.has(i)){r.push(n.get(i));continue}const e=t(i).pipe(vA(()=>WP("EOSE")),eA(t=>[i,t]));r.push(e),n.set(i,e)}return fA(...r)}),PA()),i=r.pipe(eA(([t,e])=>e),t=>t.pipe(mA(t=>"EOSE"!==t)),e),s=this.relays$.pipe(zA(t=>r.pipe(mA(([t,e])=>"EOSE"===e),IA((t,[e])=>[...t,e],[]),NA(e=>t.some(t=>!e.includes(t))),xA(),kA("EOSE"))));return fA(i,s).pipe(PA())}internalPublish(t){const e=new WeakMap;return this.relays$.pipe(_A(1),zA(n=>{const r=[];for(const i of n){if(e.has(i)){r.push(e.get(i));continue}const n=t(i).pipe(HD(i));r.push(n),e.set(i,n)}return fA(...r)}))}req(t,e=Rx(),n){return this.internalSubscription(n=>n.req(t,e),n?.eventStore?HO(n?.eventStore):aP)}event(t){return this.internalPublish(e=>e.event(t)).pipe(PA())}async negentropy(t,e,n,r){const i=(await Promise.all(this.relays.map(async t=>[t,await t.getSupported()]))).filter(([t,e])=>e?.includes(77)).map(([t])=>t);if(0===i.length)throw new Error("No relays support NIP-77 negentropy sync");if(!r?.parallel)throw new Error("Negentropy sync must be parallel (for now)");return await Promise.allSettled(i.map(i=>i.negentropy(t,e,n,r))),!0}publish(t,e){return ZP(this.internalPublish(n=>VP(n.publish(t,e))).pipe(uP(function(t,e){(function(t,e){return uP(bA(t,e,arguments.length>=2,!1,!0))})(wA,[])(t).subscribe(e)}),(n=[],uP(function(t,e){var r=!1;t.subscribe(hP(e,function(t){r=!0,e.next(t)},function(){r||e.next(n),e.complete()}))}))));var n}request(t,e){return this.internalSubscription(n=>n.request(t,e).pipe(kA("EOSE")),null==e?.eventStore?aP:HO(e?.eventStore??new TO)).pipe(WD())}subscription(t,e){return this.internalSubscription(n=>n.subscription(t,e),null==e?.eventStore?aP:HO(e?.eventStore??new TO))}count(t,e=Rx()){return this.relays$.pipe(zA(n=>aA(Object.fromEntries(n.map(n=>[n.url,n.count(t,e)])))),PA())}sync(t,e,n){return dA(async()=>{const t=(await Promise.all(this.relays.map(async t=>[t,await t.getSupported()]))).filter(([t,e])=>e?.includes(77)).map(([t])=>t);if(0===t.length)throw new Error("No relays support NIP-77 negentropy sync");return t}).pipe(zA(r=>fA(...r.map(r=>r.sync(t,e,n)))),PA())}}var KD={url:"",deserializer:function(t){return JSON.parse(t.data)},serializer:function(t){return JSON.stringify(t)}},ZD=function(t){function e(e,n){var r=t.call(this)||this;if(r._socket=null,e instanceof lP)r.destination=n,r.source=e;else{var i=r._config=NI({},KD);if(r._output=new fP,"string"==typeof e)i.url=e;else for(var s in e)e.hasOwnProperty(s)&&(i[s]=e[s]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw new Error("no WebSocket constructor can be found");r.destination=new vP}return r}return DI(e,t),e.prototype.lift=function(t){var n=new e(this._config,this.destination);return n.operator=t,n.source=this,n},e.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new vP),this._output=new fP},e.prototype.multiplex=function(t,e,n){var r=this;return new lP(function(i){try{r.next(t())}catch(o){i.error(o)}var s=r.subscribe({next:function(t){try{n(t)&&i.next(t)}catch(o){i.error(o)}},error:function(t){return i.error(t)},complete:function(){return i.complete()}});return function(){try{r.next(e())}catch(o){i.error(o)}s.unsubscribe()}})},e.prototype._connectSocket=function(){var t=this,e=this._config,n=e.WebSocketCtor,r=e.protocol,i=e.url,s=e.binaryType,o=this._output,a=null;try{a=r?new n(i,r):new n(i),this._socket=a,s&&(this._socket.binaryType=s)}catch(ej){return void o.error(ej)}var l=new KI(function(){t._socket=null,a&&1===a.readyState&&a.close()});a.onopen=function(e){if(!t._socket)return a.close(),void t._resetState();var n=t._config.openObserver;n&&n.next(e);var r=t.destination;t.destination=eP.create(function(e){if(1===a.readyState)try{var n=t._config.serializer;a.send(n(e))}catch(ej){t.destination.error(ej)}},function(e){var n=t._config.closingObserver;n&&n.next(void 0),e&&e.code?a.close(e.code,e.reason):o.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }")),t._resetState()},function(){var e=t._config.closingObserver;e&&e.next(void 0),a.close(),t._resetState()}),r&&r instanceof vP&&l.add(r.subscribe(t.destination))},a.onerror=function(e){t._resetState(),o.error(e)},a.onclose=function(e){a===t._socket&&t._resetState();var n=t._config.closeObserver;n&&n.next(e),e.wasClean?o.complete():o.error(e)},a.onmessage=function(e){try{var n=t._config.deserializer;o.next(n(e))}catch(r){o.error(r)}}},e.prototype._subscribe=function(t){var e=this,n=this.source;return n?n.subscribe(t):(this._socket||this._connectSocket(),this._output.subscribe(t),t.add(function(){var t=e._socket;0===e._output.observers.length&&(!t||1!==t.readyState&&0!==t.readyState||t.close(),e._resetState())}),t)},e.prototype.unsubscribe=function(){var e=this._socket;!e||1!==e.readyState&&0!==e.readyState||e.close(),this._resetState(),t.prototype.unsubscribe.call(this)},e}(gP);const YD="auth-required:",XD={count:3,delay:1e3,resetOnSuccess:!0};var JD;!function(t){t[t.RECEIVE=1]="RECEIVE",t[t.SEND=2]="SEND",t[t.BOTH=3]="BOTH"}(JD||(JD={}));class QD extends Error{}const tN={ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0};class eN{url;log=ZA.extend("Relay");socket;_ready$=new mP(!0);ready$=this._ready$.asObservable();reconnectTimer;attempts$=new mP(0);connected$=new mP(!1);challenge$=new mP(null);authenticated$;authenticatedAs$;authentication$=new mP(null);authenticationResponse$=new mP(null);notices$=new mP([]);error$=new mP(null);message$;notice$;lastMessageReceivedAt=0;_lastMessageAt$=new mP(0);lastMessageAt$=this._lastMessageAt$.asObservable();status$;information$;_nip11=null;icon$;limitations$;supported$;open$=new fP;close$=new fP;closing$=new fP;reqs$=new mP({});get ready(){return this._ready$.value}get connected(){return this.connected$.value}get challenge(){return this.challenge$.value}get notices(){return this.notices$.value}get authenticated(){return!0===this.authenticationResponse?.ok}get authentication(){return this.authentication$.value}get authenticatedAs(){return this.authenticated?this.authentication?.pubkey??null:null}get authenticationResponse(){return this.authenticationResponse$.value}get information(){return this._nip11}get lastMessageAt(){return this._lastMessageAt$.value}get reqs(){return this.reqs$.value}eoseTimeout=1e4;eventTimeout=1e4;publishTimeout=3e4;keepAlive=3e4;enablePing=!1;pingFrequency=29e3;pingTimeout=2e4;subscriptionReconnect;requestReconnect;publishRetry;onUnresponsive;receivedAuthRequiredForReq=new mP(!1);receivedAuthRequiredForEvent=new mP(!1);authRequiredForRead$;authRequiredForPublish$;resetState(){null!==this.challenge$.value&&this.challenge$.next(null),this.authenticationResponse$.value&&this.authenticationResponse$.next(null),null!==this.authentication$.value&&this.authentication$.next(null),this.notices$.value.length>0&&this.notices$.next([]),this.receivedAuthRequiredForReq.value&&this.receivedAuthRequiredForReq.next(!1),this.receivedAuthRequiredForEvent.value&&this.receivedAuthRequiredForEvent.next(!1)}watchTower;constructor(t,e){var n;this.url=t,this.log=this.log.extend(t),void 0!==e?.eoseTimeout&&(this.eoseTimeout=e.eoseTimeout),void 0!==e?.eventTimeout&&(this.eventTimeout=e.eventTimeout),void 0!==e?.publishTimeout&&(this.publishTimeout=e.publishTimeout),void 0!==e?.keepAlive&&(this.keepAlive=e.keepAlive),void 0!==e?.enablePing&&(this.enablePing=e.enablePing),void 0!==e?.pingFrequency&&(this.pingFrequency=e.pingFrequency),void 0!==e?.pingTimeout&&(this.pingTimeout=e.pingTimeout),void 0!==e?.onUnresponsive&&(this.onUnresponsive=e.onUnresponsive),this.subscriptionReconnect={...XD,...e?.subscriptionRetry??{}},this.requestReconnect={...XD,...e?.requestRetry??{}},this.publishRetry={...XD,...e?.publishRetry??{}},this.authenticated$=this.authenticationResponse$.pipe(eA(t=>!0===t?.ok)),this.authenticatedAs$=aA([this.authenticated$,this.authentication$]).pipe(eA(([t,e])=>t&&e?e.pubkey:null)),this.reconnectTimer=eN.createReconnectTimer(t),this.open$.subscribe(()=>{this.log("Connected"),this.connected$.next(!0),this.attempts$.next(0),this.error$.next(null),this.resetState()}),this.close$.subscribe(t=>{this.connected$.value?this.log("Disconnected"):this.log("Failed to connect"),this.connected$.value&&this.connected$.next(!1),this.attempts$.next(this.attempts$.value+1),this.resetState(),t.wasClean||this.startReconnectTimer(t)}),this.socket=(n={url:t,openObserver:this.open$,closeObserver:this.close$,closingObserver:this.closing$,WebSocketCtor:e?.WebSocket},new ZD(n)),this.information$=dA(()=>(this.log("Fetching NIP-11 information document"),eN.fetchInformationDocument(this.url))).pipe(vA(()=>WP(null)),jA(t=>this._nip11=t),OA(1)),this.limitations$=this.information$.pipe(eA(t=>t?t.limitation:null)),this.supported$=this.information$.pipe(eA(t=>t&&Array.isArray(t.supported_nips)?t.supported_nips.filter(t=>"number"==typeof t):null)),this.icon$=this.information$.pipe(eA(t=>t?.icon||new URL("/favicon.ico",uI(this.url)).toString())),this.authRequiredForRead$=this.receivedAuthRequiredForReq,this.authRequiredForPublish$=this.receivedAuthRequiredForEvent,this.authRequiredForRead$.pipe(mA(t=>!0===t),_A(1)).subscribe(()=>this.log("Auth required for REQ")),this.authRequiredForPublish$.pipe(mA(t=>!0===t),_A(1)).subscribe(()=>this.log("Auth required for EVENT")),this.status$=aA({url:WP(this.url),connected:this.connected$,authenticated:this.authenticated$,authenticatedAs:this.authenticatedAs$,ready:this._ready$,authRequiredForRead:this.authRequiredForRead$,authRequiredForPublish:this.authRequiredForPublish$,challenge:this.challenge$.asObservable()}).pipe(OA(1));const r=this.socket.pipe(mA(t=>Array.isArray(t)&&"NOTICE"===t[0]),eA(t=>t[1]),IA((t,e)=>[...t,e],[]),jA(t=>this.notices$.next(t))),i=this.socket.pipe(mA(t=>"AUTH"===t[0]),eA(t=>t[1]),jA(t=>{this.log("Received AUTH challenge",t),this.challenge$.next(t)})),s=new fP,o=this.socket.pipe(jA(t=>{const e=Date.now();this.lastMessageReceivedAt=e,this._lastMessageAt$.next(e),s.next(t)}));this.message$=s.asObservable(),this.notice$=this.message$.pipe(mA(t=>Array.isArray(t)&&"NOTICE"===t[0]),eA(t=>t[1]));const a=this.connected$.pipe(zA(t=>t&&this.enablePing?pA(this.pingFrequency,this.pingFrequency).pipe(cA(()=>{if(Date.now()-this.lastMessageReceivedAtArray.isArray(e)&&("EOSE"===e[0]||"CLOSED"===e[0])&&e[1]===t),_A(1),QP({first:this.pingTimeout,with:()=>{const t=Date.now(),e=this.onUnresponsive?.({url:this.url,lastMessageAt:this.lastMessageReceivedAt,now:t,attempts:this.attempts$.value})??"reconnect",n=new Error(`Relay ping timeout after ${this.pingTimeout}ms`);return"reconnect"===e?(this.log("Relay connection has become unresponsive, triggering reconnect"),this.startReconnectTimer(n)):"close"===e?(this.log("Relay connection has become unresponsive, closing connection"),this.error$.next(n),this.socket.complete()):this.log("Relay connection has become unresponsive (ignoring per policy)"),gA}}),EA(()=>this.send(["CLOSE",t])))})):gA),vA(()=>gA));this.watchTower=this.ready$.pipe(zA(t=>t?fA(o,r,i,this.information$,a).pipe(xA(),vA(t=>(this.startReconnectTimer(t instanceof Error?t:new Error("Connection error")),gA)),PA({resetOnRefCountZero:()=>pA(this.keepAlive)})):gA),PA())}startReconnectTimer(t){this.ready&&(this.error$.next(t instanceof Error?t:new Error("Connection error")),this._ready$.next(!1),this.reconnectTimer(t,this.attempts$.value).pipe(_A(1)).subscribe(()=>{this._ready$.next(!0)}))}waitForAuth(t,e){return aA([t,this.authenticated$]).pipe(RA(this.watchTower),mA(([t,e])=>!t||e),_A(1),zA(()=>e))}waitForReady(t){return this.ready?t:this.ready$.pipe(mA(t=>t),_A(1),zA(()=>t))}multiplex(t,e,n){return this.socket.multiplex(t,e,n)}send(t){this.socket.next(t)}req(t,e=Rx()){let n;if("function"==typeof t){const e=t(this);n=(GP(e)?e:fA(WP(e),gA)).pipe(eA(t=>Array.isArray(t)?t:[t]))}else n=(GP(t)?t:fA(WP(t),gA)).pipe(eA(t=>Array.isArray(t)?t:[t]));const r=n.pipe(xA(),kA(null)),i=this.socket.pipe(mA(t=>Array.isArray(t)&&("EVENT"===t[0]||"CLOSED"===t[0]||"EOSE"===t[0])&&t[1]===e),PA()),s=n.pipe(jA(t=>{this.socket.next(["REQ",e,...t]),this.reqs$.next({...this.reqs$.value,[e]:t})}),EA(()=>{this.socket.next(["CLOSE",e]);const{[e]:t,...n}=this.reqs$.value;this.reqs$.next(n)}),zA(()=>i)),o=fA(this.watchTower,s).pipe(DA(i.pipe(xA(),kA(!0))),DA(r),eA(t=>{if("EOSE"===t[0])return"EOSE";if("CLOSED"===t[0])throw new QD(t[2]);return t[2]}),this.handleAuthRequiredForReq("REQ"),(a=this.url,t=>t.pipe(jA(t=>{"string"!=typeof t&&pI(t,a)}))),QP({first:this.eoseTimeout,with:()=>fA(WP("EOSE"),gA)}),PA());var a;return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,o))}count(t,e=Rx()){const n=this.socket.pipe(mA(t=>Array.isArray(t)&&("COUNT"===t[0]||"CLOSED"===t[0])&&t[1]===e)),r=dA(()=>(this.socket.next(Array.isArray(t)?["COUNT",e,...t]:["COUNT",e,t]),fA(this.watchTower,n))).pipe(eA(t=>{if("COUNT"===t[0])return t[2];throw new QD(t[2])}),this.handleAuthRequiredForReq("COUNT"),_A(1),QP({first:this.eoseTimeout,with:()=>HP(()=>new Error("COUNT timeout"))}));return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,r)).pipe(PA())}event(t,e="EVENT"){const n=dA(()=>(this.socket.next([e,t]),this.socket.pipe(mA(e=>"OK"===e[0]&&e[1]===t.id),eA(t=>({ok:t[2],message:t[3],from:this.url}))))).pipe(PA()),r=fA(this.watchTower,n).pipe(DA(n.pipe(xA(),kA(!0))),_A(1),jA(({ok:t,message:e})=>{!1===t&&e?.startsWith(YD)&&!this.receivedAuthRequiredForEvent.value&&(this.log("Auth required for publish"),this.receivedAuthRequiredForEvent.next(!0))}),QP({first:this.eventTimeout,with:()=>WP({ok:!1,from:this.url,message:"Timeout"})}));return"AUTH"===e?this.waitForReady(r).pipe(PA()):this.waitForReady(this.waitForAuth(this.authRequiredForPublish$,r)).pipe(PA())}auth(t){return this.authentication$.next(t),ZP(this.event(t,"AUTH").pipe(jA(t=>this.authenticationResponse$.next(t))))}async negentropy(t,e,n,r){if(!1===(await this.getSupported())?.includes(77))throw new Error("Relay does not support NIP-77");const{buildStorageVector:i,buildStorageFromFilter:s,negentropySync:o}=await MD(async()=>{const{buildStorageVector:t,buildStorageFromFilter:e,negentropySync:n}=await import("./negentropy-Baf3_xbt.js");return{buildStorageVector:t,buildStorageFromFilter:e,negentropySync:n}},[]);return o(Array.isArray(t)?i(t):await s(t,e),this.socket,e,n,r)}authenticate(t){if(!this.challenge)throw new Error("Have not received authentication challenge");const e=t.signEvent(function(t,e){return{kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}(this.url,this.challenge));return ZP((e instanceof Promise?VP(e):WP(e)).pipe(zA(t=>this.auth(t))))}customRetryOperator(t,e){return!1===t?aP:"number"==typeof t?LA({...e,count:t}):!0===t?e?LA(e):LA():LA({...e,...t})}customRepeatOperator(t){return!1===t||void 0===t?aP:!0===t?MA():MA(t)}customTimeoutOperator(t,e){return!1===t?aP:KO(!0===t?e:t??e)}handleAuthRequiredForReq(t){return vA(e=>(e instanceof QD&&e.message.startsWith(YD)&&!this.receivedAuthRequiredForReq.value&&(this.log(`Auth required for ${t}`),this.receivedAuthRequiredForReq.next(!0)),HP(()=>e)))}subscription(t,e){return this.req(t,e?.id).pipe(this.customRetryOperator(e?.reconnect??!0,this.subscriptionReconnect),this.customRepeatOperator(e?.resubscribe),PA())}request(t,e){return this.req(t,e?.id).pipe(this.customRetryOperator(e?.reconnect??!0,this.requestReconnect),this.customRepeatOperator(e?.resubscribe),WD(),PA())}publish(t,e){return ZP(this.event(t).pipe(cA(t=>!1===t.ok&&t.message?.startsWith(YD)?HP(()=>new Error(t.message)):WP(t)),this.customRetryOperator(e?.retries??e?.reconnect??!0,this.publishRetry),this.customTimeoutOperator(e?.timeout,this.publishTimeout)))}sync(t,e,n=JD.RECEIVE){return new lP(r=>{const i=new AbortController;let s=!1;return this.negentropy(t,e,async(e,i)=>{if(n&JD.SEND&&e.length>0){const n=await(async e=>Array.isArray(t)?t.filter(t=>e.includes(t.id)):t.getByFilters({ids:e}))(e);await Promise.allSettled(n.map(t=>ZP(this.event(t))))}n&JD.RECEIVE&&i.length>0&&await ZP(this.req({ids:i}).pipe(WD(),Reflect.has(t,"add")?WO(t):aP,jA(t=>r.next(t))))},{signal:i.signal}).then(()=>{s||r.complete()}).catch(t=>{s||r.error(t)}),()=>{s||(s=!0,i.abort())}}).pipe(PA())}close(){this.socket.unsubscribe()}async getInformation(){return YP(this.information$)}async getLimitations(){return YP(this.limitations$)}async getSupported(){return YP(this.supported$)}static fetchInformationDocument(t){return VP(fetch(uI(t),{headers:{Accept:"application/nostr+json"}}).then(t=>t.json())).pipe(vA(()=>WP(null)),KO(1e4))}static createReconnectTimer(t){return(t,e=0)=>pA(Math.min(1e3*Math.pow(1.5,e),3e5))}}class nN{options;relays$=new mP(new Map);get relays(){return this.relays$.value}status$;ignoreOffline=!0;add$=new fP;remove$=new fP;constructor(t){this.options=t,this.status$=this.relays$.pipe(eA(t=>Array.from(t.values())),zA(t=>0===t.length?WP({}):fA(...t.map(t=>t.status$)).pipe(IA((t,e)=>({...t,[e.url]:e}),{}),FA({}))),OA(1))}relay(t){t=hI(t);let e=this.relays.get(t);return e||(e=new eN(t,this.options),this.relays.set(t,e),this.relays$.next(this.relays),e)}group(t,e=this.ignoreOffline){let n=Array.isArray(t)?t.map(t=>this.relay(t)):t.pipe(eA(t=>t.map(t=>this.relay(t))));return e&&(n=Array.isArray(n)?n.filter(t=>t.ready):n.pipe(eA(t=>t.filter(t=>t.ready)))),new GD(n)}remove(t,e=!0){let n;if("string"==typeof t){if(n=this.relays.get(t),!n)return}else{if(!Array.from(this.relays.values()).some(e=>e===t))return;n=t}e&&n?.close(),this.relays.delete(n.url),this.relays$.next(this.relays),this.remove$.next(n)}req(t,e,n){return this.group(t,!1).req(e,n)}event(t,e){return this.group(t,!1).event(e)}negentropy(t,e,n,r,i){return this.group(t,!1).negentropy(e,n,r,i)}publish(t,e,n){return this.group(t).publish(e,n)}request(t,e,n){return this.group(t).request(e,n)}subscription(t,e,n){return this.group(t).subscription(e,n)}subscriptionMap(t,e){const n=GP(t)?t:WP(t);return this.group(n.pipe(eA(t=>Object.keys(t)))).subscription(t=>n.pipe(eA(e=>e[t.url]),CA(cO)),e)}outboxSubscription(t,e,n){const r=GP(t)?t.pipe(eA(t=>vO(t,e))):vO(t,e);return this.subscriptionMap(r,n)}count(t,e,n){return this.group(t).count(e,n)}sync(t,e,n,r){return this.group(t).sync(e,n,r)}}const rN=Object.freeze(Object.defineProperty({__proto__:null,default:class extends qf{pool=new nN;async publish(t,e){if(!t||0===t.length)throw new Error("No relays provided to publish the event.");const n=await this.pool.publish(t,e);if(!n.some(t=>t.ok))throw new Error(`Failed to publish event. Responses: ${JSON.stringify(n)}`);return n}}},Symbol.toStringTag,{value:"Module"}));class iN{}class sN extends iN{constructor(t){super(),this.message=t}}class oN extends iN{}class aN extends iN{}class lN extends iN{}class cN extends iN{}class uN extends iN{}const hN={invalid_request:class extends iN{},invalid_grant:class extends uN{},unauthorized_client:class extends cN{},access_denied:class extends cN{},unsupported_response_type:class extends cN{},invalid_scope:class extends iN{},server_error:class extends cN{},temporarily_unavailable:class extends cN{},invalid_client:class extends uN{},unsupported_grant_type:class extends uN{},invalid_token:class extends iN{}},dN=t=>{const e=hN[t];return e?new e:new sN(t)},pN="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",fN=t=>{const e=t.slice(7).replace(/"/g,"").split(",").map(t=>{const[e,n]=t.trim().split("=");return{[e]:n}}).reduce((t,e)=>Object.assign(Object.assign({},t),e),{});return{realm:e.realm,error:e.error,errorDescription:e.error_description,errorUri:e.error_uri}},gN=t=>{let e=btoa(t);return e=e.replace(/\+/g,"-"),e=e.replace(/\//g,"_"),e=e.replace(/=/g,""),e},mN=(t,e)=>{let n=e.split("?");if(n.length<2)return;n=n[1].split("#");const r=n[0].split("&");for(const i of r){const[e,n]=i.split("=");if(e===t)return decodeURIComponent(n)}},yN=t=>Object.entries(t).map(([t,e])=>`${t}=${encodeURIComponent(e)}`).join("&");var vN=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(ej){s(ej)}}function a(t){try{l(r.throw(t))}catch(ej){s(ej)}}function l(t){t.done?i(t.value):function(t){return t instanceof n?t:new n(function(e){e(t)})}(t.value).then(o,a)}l((r=r.apply(t,e||[])).next())})};const bN="WWW-Authenticate";class wN{constructor(t,e){this.state={},this.config=t,this.storage=e||xN,this.ready=new Promise(t=>this.setReady=t),this.recoverState()}reset(){return vN(this,void 0,void 0,function*(){this.state={},yield this.saveState(),this.authCodeForAccessTokenPromise=void 0,this.refreshTokenForAccessTokenPromise=void 0})}requestAuthorizationCode(t){return vN(this,void 0,void 0,function*(){const{clientId:e,extraAuthorizationParams:n,redirectUrl:r,scopes:i}=this.config,{codeChallenge:s,codeVerifier:o}=yield(l=void 0,c=function*(){const t=new Uint32Array(96);crypto.getRandomValues(t);const e=gN(Array.from(t).map(t=>pN[t%66]).join("")),n=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=new Uint8Array(n);let i="";const s=r.byteLength;for(let o=0;o{const t=new Uint32Array(32);return crypto.getRandomValues(t),Array.from(t).map(t=>pN[t%66]).join("")})();var l,c;this.state=Object.assign(Object.assign({},this.state),{codeChallenge:s,codeVerifier:o,stateQueryParam:a}),this.saveState();let u=this.config.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(e)}&`+`redirect_uri=${encodeURIComponent(r)}&`+`state=${a}&`+`code_challenge=${encodeURIComponent(s)}&code_challenge_method=S256`;if(i&&(u+=`&scope=${encodeURIComponent(i.join(" "))}`),n||t){const e=Object.assign(Object.assign({},n),t);u+=`&${yN(e)}`}location.replace(u)})}isReturningFromAuthServer(){return!!mN("code",location.href)}receiveCode(){return vN(this,void 0,void 0,function*(){yield this.ready;const t=mN("error",location.href);if(t)throw dN(t);if(mN("state",location.href)!==this.state.stateQueryParam)throw console.warn('"state" parameter doesn\'t match the one sent! Possible malicious activity.'),new lN;if(this.state.authorizationCode=mN("code",location.href),!this.state.authorizationCode)throw new aN;this.saveState()})}getTokens(t){return vN(this,void 0,void 0,function*(){const{accessToken:e,authorizationCode:n,idToken:r,refreshToken:i,scopes:s}=this.state;if(n)return this.exchangeAuthCodeForAccessToken(t);if(!e)throw new oN;return this.isAccessTokenExpired()&&this.config.onAccessTokenExpiry?this.config.onAccessTokenExpiry():Promise.resolve({accessToken:e,idToken:r,refreshToken:i,scopes:s})})}exchangeAuthCodeForAccessToken(t){return vN(this,void 0,void 0,function*(){this.authCodeForAccessTokenPromise||(this.authCodeForAccessTokenPromise=this.fetchAccessTokenUsingCode(t));const e=yield this.authCodeForAccessTokenPromise;return this.authCodeForAccessTokenPromise=void 0,this.state.authorizationCode=void 0,this.setTokens(e)})}exchangeRefreshTokenForAccessToken(){return vN(this,void 0,void 0,function*(){this.refreshTokenForAccessTokenPromise||(this.refreshTokenForAccessTokenPromise=this.fetchAccessTokenUsingRefreshToken());const t=yield this.refreshTokenForAccessTokenPromise;return this.refreshTokenForAccessTokenPromise=void 0,this.setTokens(t)})}makeRetryFetchFunction(t){return(e,...n)=>vN(this,void 0,void 0,function*(){const r=yield t(e,...n);if(401===r.status){const i=r.headers.get(bN.toLowerCase());if(i&&"invalid_token"===fN(i).error)return yield this.exchangeRefreshTokenForAccessToken(),e=yield this.requestInterceptor(e),t(e,...n)}return r})}decorateFetchWithInterceptors(t){return(e,...n)=>vN(this,void 0,void 0,function*(){"string"==typeof e&&(e=new Request(e)),e=yield this.requestInterceptor(e);const r=yield t(e,...n);return this.responseInterceptor(r)})}requestInterceptor(t){return vN(this,void 0,void 0,function*(){const e=yield this.getTokens();return t.headers.set("Authorization",`Bearer ${e.accessToken}`),t})}responseInterceptor(t){return vN(this,void 0,void 0,function*(){if(401!==t.status)return t;const e=t.headers.get(bN.toLowerCase());if(e){const t=fN(e).error;throw"invalid_grant"===t&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),"invalid_token"===t&&this.config.onInvalidToken&&(yield this.config.onInvalidToken()),dN(t)}return t})}getGrantedScopes(){return this.state.scopes}isAuthorized(){return!!this.state.accessToken}isAccessTokenExpired(){const{accessTokenExpiry:t}=this.state;return Boolean(t&&new Date>=new Date(t))}fetchAccessTokenUsingCode(t){return vN(this,void 0,void 0,function*(){const{authorizationCode:e,codeVerifier:n=""}=this.state,{clientId:r,redirectUrl:i}=this.config;n?e||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const s=this.config.tokenUrl,o=Object.assign({grant_type:"authorization_code",code:e,redirect_uri:i,client_id:r,code_verifier:n},t),a=new URLSearchParams(o).toString();return this.makeTokenRequest(s,a)})}fetchAccessTokenUsingRefreshToken(){const{extraRefreshParams:t,clientId:e,tokenUrl:n}=this.config,{refreshToken:r}=this.state;r||console.warn("No refresh token is present.");const i=n;let s=`grant_type=refresh_token&refresh_token=${r}&client_id=${e}`;return t&&(s=`${i}&${yN(t)}`),this.makeTokenRequest(i,s)}makeTokenRequest(t,e){return vN(this,void 0,void 0,function*(){const n=yield fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),r=yield n.json();if(!n.ok)throw"invalid_grant"===r.error&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),dN(r.error);const{access_token:i,expires_in:s,id_token:o,refresh_token:a,scope:l}=r;return{accessToken:i,expiresIn:s,idToken:o,refreshToken:a,scope:l}})}setTokens(t){return vN(this,void 0,void 0,function*(){const{accessToken:e,expiresIn:n,idToken:r,refreshToken:i,scope:s}=t;return this.state.accessToken=e,this.state.accessTokenExpiry=new Date(Date.now()+1e3*parseInt(n,10)).toString(),r&&(this.state.idToken=r),i&&(this.state.refreshToken=i),s&&(this.state.scopes=s.split(" ")),yield this.saveState(),{accessToken:this.state.accessToken,idToken:this.state.idToken,refreshToken:this.state.refreshToken,scopes:s?this.state.scopes:[]}})}recoverState(){return vN(this,void 0,void 0,function*(){this.state=JSON.parse((yield this.storage.loadState())||"{}"),this.setReady(),this.config.storeRefreshToken||(this.state.refreshToken=this.refreshToken)})}saveState(){return vN(this,void 0,void 0,function*(){this.refreshToken=this.state.refreshToken;const t=Object.assign({},this.state);this.config.storeRefreshToken||delete t.refreshToken,yield this.storage.saveState(JSON.stringify(t))})}}const _N="oauth2authcodepkce-state",xN={saveState:t=>localStorage.setItem(_N,t),loadState:()=>localStorage.getItem(_N)};class CN{saveState(t){localStorage.setItem("marco:osm_auth_state",t)}loadState(){const t=localStorage.getItem("marco:osm_auth_state");if(!t)return!1;try{return JSON.parse(t),t}catch(ej){return console.warn("Failed to parse OSM auth state",ej),!1}}}class SN extends qf{static{dF(this.prototype,"isConnected",[Is],function(){return!1})}#tt=void fF(this,"isConnected");static{dF(this.prototype,"userDisplayName",[Is],function(){return null})}#et=void fF(this,"userDisplayName");oauthClient;constructor(){super(...arguments);const t="https://www.openstreetmap.org",e=`${window.location.origin}/oauth/osm/callback`;this.oauthClient=new wN({scopes:["read_prefs","write_api"],authorizationUrl:`${t}/oauth2/authorize`,tokenUrl:`${t}/oauth2/token`,clientId:"jIn8l5mT8FZOGYiIYXG1Yvj_2FZKB9TJ1edZwOJPsRU",redirectUrl:e,storeRefreshToken:!0},new CN),this.restoreSession()}async restoreSession(){try{await this.oauthClient.ready}catch(ej){console.warn("oauthClient.ready failed",ej)}if(await this.oauthClient.isAuthorized()){this.isConnected=!0;const t=localStorage.getItem("marco:osm_user_display_name");t?this.userDisplayName=t:await this.fetchUserInfo()}}async login(){await this.oauthClient.requestAuthorizationCode()}async handleCallback(){await this.oauthClient.receiveCode(),await this.oauthClient.getTokens(),this.isConnected=!0,await this.fetchUserInfo()}async logout(){await this.oauthClient.reset(),this.isConnected=!1,this.userDisplayName=null,localStorage.removeItem("marco:osm_user_display_name")}async fetchUserInfo(){try{const t=await this.oauthClient.getTokens(),e=await fetch("https://api.openstreetmap.org/api/0.6/user/details.json",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(e.ok){const t=await e.json();console.debug("OSM data:",t);const n=t.user.display_name;this.userDisplayName=n,localStorage.setItem("marco:osm_user_display_name",n)}else console.error("Failed to fetch OSM user info",e.status)}catch(ej){console.error("Error fetching OSM user info",ej)}}}const kN=Object.freeze(Object.defineProperty({__proto__:null,default:SN},Symbol.toStringTag,{value:"Module"}));function EN(t){return"string"==typeof t&&t?t.replace(/[_-]/g," ").replace(/\w\S*/g,t=>t.replace(/^\w/,t=>t.toUpperCase())):""}const TN=Object.freeze(Object.defineProperty({__proto__:null,humanizeOsmTag:EN},Symbol.toStringTag,{value:"Module"}));function RN(t,e="Untitled Place"){if(!t)return e;const n=navigator.languages||[navigator.language||"en"];for(const r of n){if(!r)continue;const e=`name:${r.split("-")[0]}`;if(t[e])return t[e]}return t.name?t.name:t["name:en"]?t["name:en"]:e}const MN=["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","highway","aeroway","waterway","natural","place","border_type","admin_title"];function LN(t){if(!t)return null;for(const e of MN){const n=t[e];if(n)return EN("yes"===n?e:n)}return null}const IN=Object.freeze(Object.defineProperty({__proto__:null,getLocalizedName:RN,getPlaceType:LN},Symbol.toStringTag,{value:"Module"})),PN=[{id:"restaurants",label:"Restaurants",icon:"fork-and-knife",filter:['["amenity"~"^(restaurant|fast_food|food_court|pub|cafe)$"]["cuisine"!~"coffee"]'],types:["node","way"]},{id:"coffee",label:"Coffee",icon:"cup-and-saucer",filter:['["amenity"~"^(cafe|ice_cream)$"]','["shop"~"^(coffee|tea)$"]','["cuisine"~"coffee_shop"]'],types:["node","way"]},{id:"groceries",label:"Groceries",icon:"shopping-basket",filter:['["shop"~"^(supermarket|convenience|grocery|greengrocer|bakery|butcher|deli|farm|seafood)$"]'],types:["node","way"]},{id:"things-to-do",label:"Things to do",icon:"camera",filter:['["tourism"~"^(museum|gallery|attraction|viewpoint|zoo|theme_park|aquarium|artwork)$"]','["amenity"~"^(cinema|theatre|arts_centre|planetarium)$"]','["leisure"~"^(sports_centre|stadium|water_park)$"]','["historic"]','["shop"="flea_market"]'],types:["node","way","relation"]},{id:"accommodation",label:"Hotels",icon:"person-sleeping-in-bed",filter:['["tourism"~"^(hotel|hostel|motel|chalet)$"]'],types:["node","way","relation"]}];function AN(t){return PN.find(e=>e.id===t)}const ON=Object.freeze(Object.defineProperty({__proto__:null,POI_CATEGORIES:PN,getCategoryById:AN},Symbol.toStringTag,{value:"Module"}));class FN extends qf{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");controller=null;cachedResults=null;lastQueryKey=null;cachedPlaces=new Map;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}async getNearbyPois(t,e,n=50){const r=`${t},${e},${n}`;if(this.lastQueryKey===r&&this.cachedResults)return console.debug("Returning cached Overpass results for:",r),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,s=[`~"^(${["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","aeroway"].join("|")})$"~".*"`],o=Object.entries({public_transport:["stop_area","platform"]}).map(([t,e])=>`["${t}"!~"^(${e.join("|")})$"]`).join(""),a=`\n[out:json][timeout:25];\n(\n node(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n way(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n relation(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n);\nout center;\n `.trim(),l=`${this.settings.overpassApi}?data=${encodeURIComponent(a)}`;try{const t=await this.fetchWithRetry(l,{signal:i});if(!t.ok)throw new Error("Overpass request failed");const e=(await t.json()).elements.map(this.normalizePoi);return this.lastQueryKey=r,this.cachedResults=e,e}catch(ej){if("AbortError"===ej.name)return console.debug("Overpass request aborted"),[];throw ej}}async getCategoryPois(t,e,n,r){const i=AN(e);if(!i||!t)return[];const s=n&&r?`cat:${e}:${n}:${r}`:null;if(s&&this.lastQueryKey===s&&this.cachedResults)return console.debug("Returning cached category results for:",s),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const o=this.controller.signal,{minLat:a,minLon:l,maxLat:c,maxLon:u}=t,h=[],d=i.types||["node","way","relation"];i.filter.forEach(t=>{d.forEach(e=>{h.push(`${e}${t}[~"^name"~"."];`)})});const p=`\n[out:json][timeout:25][bbox:${a},${l},${c},${u}];\n(\n ${h.join("\n ")}\n);\nout center;\n `.trim(),f=`${this.settings.overpassApi}?data=${encodeURIComponent(p)}`;try{const t=await this.fetchWithRetry(f,{signal:o});if(!t.ok)throw new Error("Overpass request failed");const e=(await t.json()).elements.map(this.normalizePoi);return s&&(this.lastQueryKey=s,this.cachedResults=e),e}catch(ej){if("AbortError"===ej.name)return console.debug("Category search aborted"),[];throw console.error("Category search failed",ej),ej}}normalizePoi(t){const e=t.tags||{},n=LN(e)||"Point of Interest";return{title:RN(e),lat:t.lat||t.center?.lat,lon:t.lon||t.center?.lon,url:e.website,osmId:String(t.id),osmType:t.type,osmTags:e,description:e.description,source:"osm",type:n}}async fetchWithRetry(t,e={},n=3){try{const r=await fetch(t,e);return!r.ok&&n>0&&[502,503,504,429].includes(r.status)?(console.warn(`Overpass request failed with ${r.status}. Retrying... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1)):r}catch(ej){if(n>0&&"AbortError"!==ej.name)return console.debug(`Retrying Overpass request... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1);throw ej}}async getPoiById(t,e=null){let n;n="node"===e?`[out:json][timeout:25];node(${t});out center;`:"way"===e?`[out:json][timeout:25];way(${t});out center;`:`\n[out:json][timeout:25];\n(\n node(${t});\n way(${t});\n);\nout center;\n `.trim();const r=`${this.settings.overpassApi}?data=${encodeURIComponent(n)}`,i=await this.fetchWithRetry(r);if(!i.ok)throw new Error("Overpass request failed");const s=await i.json();return s.elements[0]?this.normalizePoi(s.elements[0]):null}async fetchOsmObject(t,e){if(!t||!e)return null;const n=`${e}:${t}`,r=this.cachedPlaces.get(n);if(r&&Date.now()-r.timestamp<1e4)return console.debug(`Using in-memory cached OSM object for ${n}`),r.data;let i;if("node"===e)i=`https://www.openstreetmap.org/api/0.6/node/${t}.json`;else if("way"===e)i=`https://www.openstreetmap.org/api/0.6/way/${t}/full.json`;else{if("relation"!==e)return console.error("Unknown OSM type:",e),null;i=`https://www.openstreetmap.org/api/0.6/relation/${t}/full.json`}try{const r=await this.fetchWithRetry(i);if(!r.ok){if(410===r.status)return console.warn("OSM object has been deleted"),null;throw new Error(`OSM API request failed: ${r.status}`)}const s=await r.json(),o=this.normalizeOsmApiData(s.elements,t,e);return this.cachedPlaces.set(n,{data:o,timestamp:Date.now()}),setTimeout(()=>{this.cachedPlaces.delete(n)},1e4),o}catch(ej){return console.error("Failed to fetch OSM object:",ej),null}}normalizeOsmApiData(t,e,n){if(!t||0===t.length)return null;let r=t.find(t=>String(t.id)===String(e)&&t.type===n);if(!r)return null;let i=r;if("relation"===n&&r.members){const e=r.members.find(t=>"label"===t.role&&"node"===t.type),n=r.members.find(t=>"admin_centre"===t.role&&"node"===t.type),s=e||n;if(s){const e=t.find(t=>String(t.id)===String(s.ref)&&"node"===t.type);e&&(i=e)}}let s=i.lat,o=i.lon,a=null,l=null;if("way"===n&&r.nodes){const e=new Map;t.forEach(t=>{"node"===t.type&&e.set(t.id,[t.lon,t.lat])});const n=r.nodes.map(t=>e.get(t)).filter(Boolean);if(n.length>0){if(i===r){const t=n.reduce((t,e)=>t+e[1],0),e=n.reduce((t,e)=>t+e[0],0);s=t/n.length,o=e/n.length}const t=n.map(t=>t[1]),e=n.map(t=>t[0]);if(a={minLat:Math.min(...t),maxLat:Math.max(...t),minLon:Math.min(...e),maxLon:Math.max(...e)},n.length>1){const t=n[0],e=n[n.length-1];l=t[0]===e[0]&&t[1]===e[1]?{type:"Polygon",coordinates:[n]}:{type:"LineString",coordinates:n}}}}else if("relation"===n&&r.members){const e=[],n=new Map;t.forEach(t=>{"node"===t.type&&n.set(t.id,t)});const c=[];if(r.members.forEach(r=>{if("node"===r.type){const t=n.get(r.ref);t&&e.push(t)}else if("way"===r.type){const i=t.find(t=>"way"===t.type&&t.id===r.ref);if(i&&i.nodes){const t=[];i.nodes.forEach(r=>{const i=n.get(r);i&&(e.push(i),t.push([i.lon,i.lat]))}),t.length>1&&c.push(t)}}}),e.length>0){if(i===r){const t=e.reduce((t,e)=>t+e.lat,0),n=e.reduce((t,e)=>t+e.lon,0);s=t/e.length,o=n/e.length}const t=e.map(t=>t.lat),n=e.map(t=>t.lon);a={minLat:Math.min(...t),maxLat:Math.max(...t),minLon:Math.min(...n),maxLon:Math.max(...n)}}c.length>0&&(l={type:"MultiLineString",coordinates:c})}const c=i.tags||{},u=LN(c)||"Point of Interest";return{title:RN(c),lat:s,lon:o,bbox:a,geojson:l,url:c.website,osmId:String(i.id),osmType:i.type,osmTags:c,description:c.description,source:"osm",type:u}}}const zN=Object.freeze(Object.defineProperty({__proto__:null,default:FN},Symbol.toStringTag,{value:"Module"}));class DN extends qf{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");controller=null;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}get baseUrl(){return this.settings.photonApi}async search(t,e,n,r=10){if(!t||t.length<2)return[];this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,s=new URLSearchParams({q:t,limit:String(r)});e&&n&&(s.append("lat",parseFloat(e).toFixed(4)),s.append("lon",parseFloat(n).toFixed(4)));const o=`${this.baseUrl}?${s.toString()}`;try{const t=await this.fetchWithRetry(o,{signal:i});if(!t.ok)throw new Error(`Photon request failed with status ${t.status}`);const e=await t.json();return e.features?e.features.map(t=>this.normalizeFeature(t)):[]}catch(ej){return"AbortError"===ej.name||console.error("Photon search error:",ej),[]}}normalizeFeature(t){const e=t.properties||{},n=(t.geometry||{}).coordinates||[],r=n[0],i=n[1],s=[];e.street&&s.push(e.housenumber?`${e.street} ${e.housenumber}`:e.street),e.city&&e.city!==e.name&&s.push(e.city),e.state&&e.state!==e.city&&s.push(e.state),e.country&&s.push(e.country);const o=s.join(", "),a=e.name||o||"Unknown Place",l={...e};e.osm_key&&e.osm_value&&(l[e.osm_key]=e.osm_value);const c=LN(l)||EN(e.osm_value);return{title:a,lat:i,lon:r,osmId:e.osm_id,osmType:{N:"node",W:"way",R:"relation"}[e.osm_type]||e.osm_type,osmTags:l,description:e.name?o:s.slice(1).join(", "),source:"photon",type:c}}async fetchWithRetry(t,e={},n=3){try{const r=await fetch(t,e);return!r.ok&&n>0&&[502,503,504,429].includes(r.status)?(console.warn(`Photon request failed with ${r.status}. Retrying... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1)):r}catch(ej){if(n>0&&"AbortError"!==ej.name)return console.debug(`Retrying Photon request... (${n} left)`,ej),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1);throw ej}}}const NN=Object.freeze(Object.defineProperty({__proto__:null,default:DN},Symbol.toStringTag,{value:"Module"})),jN={overpassApi:"https://overpass-api.de/api/interpreter",mapKinetic:!0,photonApi:"https://photon.komoot.io/api/",showQuickSearchButtons:!0,nostrPhotoFallbackUploads:!1,nostrReadRelays:null,nostrWriteRelays:null};class BN extends qf{static{dF(this.prototype,"overpassApi",[Is],function(){return jN.overpassApi})}#nt=void fF(this,"overpassApi");static{dF(this.prototype,"mapKinetic",[Is],function(){return jN.mapKinetic})}#rt=void fF(this,"mapKinetic");static{dF(this.prototype,"photonApi",[Is],function(){return jN.photonApi})}#it=void fF(this,"photonApi");static{dF(this.prototype,"showQuickSearchButtons",[Is],function(){return jN.showQuickSearchButtons})}#st=void fF(this,"showQuickSearchButtons");static{dF(this.prototype,"nostrPhotoFallbackUploads",[Is],function(){return jN.nostrPhotoFallbackUploads})}#ot=void fF(this,"nostrPhotoFallbackUploads");static{dF(this.prototype,"nostrReadRelays",[Is],function(){return jN.nostrReadRelays})}#at=void fF(this,"nostrReadRelays");static{dF(this.prototype,"nostrWriteRelays",[Is],function(){return jN.nostrWriteRelays})}#lt=void fF(this,"nostrWriteRelays");overpassApis=[{name:"overpass-api.de (DE)",url:"https://overpass-api.de/api/interpreter"},{name:"private.coffee (AT)",url:"https://overpass.private.coffee/api/interpreter"}];photonApis=[{name:"photon.komoot.io",url:"https://photon.komoot.io/api/"}];constructor(){super(...arguments),this.loadSettings()}loadSettings(){let t={};const e=localStorage.getItem("marco:settings");if(e)try{t=JSON.parse(e)}catch(ej){console.error("Failed to parse settings from localStorage",ej)}else{const e=localStorage.getItem("marco:overpass-api");e&&(t.overpassApi=e);const n=localStorage.getItem("marco:map-kinetic");null!==n&&(t.mapKinetic="true"===n);const r=localStorage.getItem("marco:show-quick-search");null!==r&&(t.showQuickSearchButtons="true"===r);const i=localStorage.getItem("marco:nostr-photo-fallback-uploads");null!==i&&(t.nostrPhotoFallbackUploads="true"===i);const s=localStorage.getItem("marco:photon-api");s&&(t.photonApi=s)}const n={...jN,...t};this.overpassApis.some(t=>t.url===n.overpassApi)||(n.overpassApi=jN.overpassApi),this.overpassApi=n.overpassApi,this.mapKinetic=n.mapKinetic,this.photonApi=n.photonApi,this.showQuickSearchButtons=n.showQuickSearchButtons,this.nostrPhotoFallbackUploads=n.nostrPhotoFallbackUploads,this.nostrReadRelays=n.nostrReadRelays,this.nostrWriteRelays=n.nostrWriteRelays,this.saveSettings()}saveSettings(){const t={overpassApi:this.overpassApi,mapKinetic:this.mapKinetic,photonApi:this.photonApi,showQuickSearchButtons:this.showQuickSearchButtons,nostrPhotoFallbackUploads:this.nostrPhotoFallbackUploads,nostrReadRelays:this.nostrReadRelays,nostrWriteRelays:this.nostrWriteRelays};localStorage.setItem("marco:settings",JSON.stringify(t))}update(t,e){t in jN&&(this[t]=e,this.saveSettings())}}const UN=Object.freeze(Object.defineProperty({__proto__:null,default:BN},Symbol.toStringTag,{value:"Module"}));var $N,qN={exports:{}},VN=($N||($N=1,qN.exports=function(){var t={548:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Access=void 0;class n{constructor(){this.reset()}get scopes(){return Object.keys(this.scopeModeMap).map(t=>({name:t,mode:this.scopeModeMap[t]}))}get scopeParameter(){return this.scopes.map(t=>`${this._scopeNameForParameter(t)}:${t.mode}`).join(" ")}claim(t,e){if("string"!=typeof t||-1!==t.indexOf("/")||0===t.length)throw new Error("Scope should be a non-empty string without forward slashes");if("string"!=typeof e||!e.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(t),this.scopeModeMap[t]=e}get(t){return this.scopeModeMap[t]}remove(t){const e={};for(const n in this.scopeModeMap)e[n]=this.scopeModeMap[n];this.reset(),delete e[t];for(const n in e)this.claim(n,e[n])}checkPermission(t,e){const n=this.get(t);return n&&("r"===e||"rw"===n)}checkPathPermission(t,e){if(this.checkPermission("*",e))return!0;const n=this._getModuleName(t);return!!this.checkPermission(n,e)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(t){if("/"!==t[0])throw new Error("Path should start with a slash");const e=t.replace(/^\/public/,"").match(/^\/([^/]*)\//);return e?e[1]:"*"}_adjustRootPaths(t){"*"in this.scopeModeMap||"*"===t?this.rootPaths=["/"]:t in this.scopeModeMap||(this.rootPaths.push("/"+t+"/"),this.rootPaths.push("/public/"+t+"/"))}_scopeNameForParameter(t){if("*"===t.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return t.name}setStorageType(t){this.storageType=t}static _rs_init(){}}e.Access=n,e.default=n},275:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Authorize=void 0;const s=i(n(334)),o=n(746),a=i(n(503)),l=n(368);let c;function u(t){const e=t||h.getLocation().href,n={};for(const[s,o]of new URL(e).searchParams)n[s]=o;const r=e.indexOf("#");if(-1===r)return n;const i=e.substring(r+1);return i.includes("=")?i.split("&").reduce(function(t,e){const n=e.split("=");if("state"===n[0]&&n[1].match(/rsDiscovery/)){let e=decodeURIComponent(n[1]);const r=e.substr(e.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];t.rsDiscovery=JSON.parse(atob(r)),e=e.replace(new RegExp("&?rsDiscovery="+r),""),e.length>0&&(t.state=e)}else t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]);return t},n):n}class h{static authorize(t,e){if((0,s.default)("[Authorize] authURL = ",e.authURL,"scope = ",e.scope,"redirectUri = ",e.redirectUri,"clientId = ",e.clientId,"response_type =",e.response_type),!e.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,o.localStorageAvailable)()&&"remotestorage"===t.backend){e.redirectUri+=e.redirectUri.indexOf("#")>0?"&":"#";const n={userAddress:t.remote.userAddress,href:t.remote.href,storageApi:t.remote.storageApi,properties:t.remote.properties};e.redirectUri+="rsDiscovery="+(0,o.toBase64)(JSON.stringify(n))}const n=function(t){const e=new URL(t.redirectUri);t.state||(t.state=e.hash?e.hash.substring(1):""),t.response_type||(t.response_type="token");const n=new URL(t.authURL);n.searchParams.set("redirect_uri",t.redirectUri.replace(/#.*$/,"")),n.searchParams.set("scope",t.scope),n.searchParams.set("client_id",t.clientId);for(const r of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const e=t[r];e&&n.searchParams.set(r,e)}return n.href}(e);o.globalContext.cordova?h.openWindow(n,e.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then(e=>{t.remote.configure({token:e.access_token})}):h.setLocation(n)}static refreshAccessToken(t,e,n){return r(this,void 0,void 0,function*(){var t,r,i;yield e.configure({token:null,tokenType:null});const o=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:n}),c=yield(0,l.requestWithTimeout)("POST",e.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),responseType:"json"});if(200!==(null==c?void 0:c.status))throw yield e.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(c.response));{(0,s.default)(`[Authorize] access token good for ${null===(t=null==c?void 0:c.response)||void 0===t?void 0:t.expires_in} seconds`);const n={token:null===(r=null==c?void 0:c.response)||void 0===r?void 0:r.access_token,tokenType:null===(i=null==c?void 0:c.response)||void 0===i?void 0:i.token_type};if(!n.token)throw new Error(`no access_token in "successful" refresh: ${c.response}`);yield e.configure(n)}})}static setLocation(t){if("string"==typeof t)document.location.href=t;else{if("object"!=typeof t)throw"Invalid location "+t;document.location=t}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(t){t.removeEventListener("features-loaded",c)}}e.Authorize=h,h.IMPLIED_FAKE_TOKEN=!1,h.getLocation=function(){return document.location},h.openWindow=function(t,e,n){return new Promise((r,i)=>{const s=open(t,"_blank",n);function o(){i("Authorization was canceled")}s&&!s.closed?(s.addEventListener("loadstart",function(t){if(0!==t.url.indexOf(e))return;s.removeEventListener("exit",o),s.close();const n=u(t.url);n?r(n):i("Authorization error")}),s.addEventListener("exit",o)):i("Authorization popup was blocked")})},h._rs_init=function(t){const e=u();let n;e&&(n=h.getLocation(),n.hash=""),c=function(){let i=!1;if(e){if(e.error)throw"access_denied"===e.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${e.error}`);e.rsDiscovery&&t.remote.configure(e.rsDiscovery),e.access_token&&(t.remote.configure({token:e.access_token}),i=!0),e.remotestorage&&(t.connect(e.remotestorage),i=!0),e.state&&(n=h.getLocation(),h.setLocation(n.href.split("#")[0]+"#"+e.state)),e.code&&(function(e){r(this,void 0,void 0,function*(){var r,i,o,a;const c=sessionStorage.getItem("remotestorage:codeVerifier");if(!c)return void(0,s.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");n=h.getLocation();let u=n.origin;"/"!==n.pathname&&(u+=n.pathname);const d=new URLSearchParams({code:e,grant_type:"authorization_code",client_id:t.remote.clientId,redirect_uri:u,code_verifier:c}),p=yield(0,l.requestWithTimeout)("POST",t.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:d.toString(),responseType:"json"});if(200===p.status){(0,s.default)(`[Authorize] access token good for ${null===(r=null==p?void 0:p.response)||void 0===r?void 0:r.expires_in} seconds`);const e={token:null===(i=null==p?void 0:p.response)||void 0===i?void 0:i.access_token,refreshToken:null===(o=null==p?void 0:p.response)||void 0===o?void 0:o.refresh_token,tokenType:null===(a=null==p?void 0:p.response)||void 0===a?void 0:a.token_type};e.token?t.remote.configure(e):t._emit("error",new Error(`no access_token in "successful" response: ${p.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else t._emit("error",new Error(`${p.statusText}: ${p.response}`))})}(e.code),i=!0),i||t.remote.stopWaitingForToken()}else t.remote.stopWaitingForToken()},t.on("features-loaded",c)},e.default=h},424:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.BaseClient=void 0;const s=i(n(439)),o=i(n(613)),a=i(n(491)),l=i(n(93)),c=i(n(28)),u=n(746);class h{constructor(t,e){if(this.schemas={configurable:!0,get(){return h.Types.inScope(this.moduleName)}},"/"!==e[e.length-1])throw"Not a folder: "+e;"/"===e&&(this.makePath=t=>("/"===t[0]?"":"/")+t),this.storage=t,this.base=e,this.moduleName=function(t){const e=t.split("/");return t.length>2?e[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),t.onChange(this.base,this._fireChange.bind(this))}scope(t){return new h(this.storage,this.makePath(t))}getListing(t,e){return r(this,void 0,void 0,function*(){if("string"!=typeof t)t="";else if(t.length>0&&!(0,u.isFolder)(t))return Promise.reject("Not a folder: "+t);return this.storage.get(this.makePath(t),e).then(t=>404===t.statusCode?{}:t.body)})}getAll(t,e){return r(this,void 0,void 0,function*(){if("string"!=typeof t)t="";else if(t.length>0&&!(0,u.isFolder)(t))return Promise.reject("Not a folder: "+t);return this.storage.get(this.makePath(t),e).then(n=>{if(404===n.statusCode)return{};if("object"==typeof n.body){const r=Object.keys(n.body);if(0===r.length)return{};const i=r.map(r=>this.storage.get(this.makePath(t+r),e).then(t=>{if("string"==typeof t.body)try{t.body=JSON.parse(t.body)}catch(t){}"object"==typeof t.body&&(n.body[r]=t.body)}));return Promise.all(i).then(()=>n.body)}})})}getFile(t,e){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(t),e).then(t=>({data:t.body,contentType:t.contentType,revision:t.revision}))})}storeFile(t,e,n){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'contentType' of baseClient.storeFile must be a string"):"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof n&&"object"!=typeof n?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(e),n,t).then(t=>200===t.statusCode||201===t.statusCode?t.revision:Promise.reject("Request (PUT "+this.makePath(e)+") failed with status: "+t.statusCode)))})}getObject(t,e){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(t),e).then(e=>{if("object"==typeof e.body)return e.body;if("string"==typeof e.body)try{return JSON.parse(e.body)}catch(e){throw new Error("Not valid JSON: "+this.makePath(t))}else if(void 0!==e.body&&200===e.statusCode)return Promise.reject("Not an object: "+this.makePath(t))})})}storeObject(t,e,n){return r(this,void 0,void 0,function*(){if("string"!=typeof t)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof e)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof n)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(n,t);try{const t=this.validate(n);if(!t.valid)return Promise.reject(t)}catch(t){return Promise.reject(t)}return this.storage.put(this.makePath(e),JSON.stringify(n),"application/json; charset=UTF-8").then(t=>200===t.statusCode||201===t.statusCode?t.revision:Promise.reject("Request (PUT "+this.makePath(e)+") failed with status: "+t.statusCode))})}remove(t){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(t),this.storage.connected))})}getItemURL(t){if("string"!=typeof t)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(t=(0,u.cleanPath)(this.makePath(t)),this.storage.remote.href+t):void 0}cache(t,e="ALL"){if("string"!=typeof t)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof e)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==e&&"SEEN"!==e&&"ALL"!==e)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(t),e),this}declareType(t,e,n){let r;if(n&&"string"==typeof e)r=e;else if(n||"string"==typeof e){if(!n&&"string"==typeof e)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else n=e,r=this._defaultTypeURI(t);h.Types.declare(this.moduleName,t,r,n)}validate(t){const e=h.Types.getSchema(t["@context"]);if(e)return s.default.validateResult(t,e);throw new a.default(t["@context"])}_defaultTypeURI(t){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(t)}_attachType(t,e){t["@context"]=h.Types.resolveAlias(this.moduleName+"/"+e)||this._defaultTypeURI(e)}makePath(t){return this.base+(t||"")}_fireChange(t){c.default.changeEvents[t.origin]&&(["new","old","lastCommon"].forEach(function(e){if((!t[e+"ContentType"]||/^application\/(.*)json(.*)/.exec(t[e+"ContentType"]))&&"string"==typeof t[e+"Value"])try{t[e+"Value"]=JSON.parse(t[e+"Value"])}catch(t){}}),this._emit("change",t))}static _rs_init(){}}e.BaseClient=h,h.Types=o.default,(0,u.applyMixins)(h,[l.default]),e.default=h},285:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Caching=void 0;const i=n(746),s=r(n(334));class o{constructor(t){this.pendingActivations=[],this._access=t.access,this.reset()}set(t,e){if("string"!=typeof t)throw new Error("path should be a string");if(!(0,i.isFolder)(t))throw new Error("path should be a folder");if(!this._access.checkPathPermission(t,"r"))throw new Error('No access to path "'+t+'". You must claim access to it first.');if(void 0===e||!e.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[t]=e,"ALL"===e&&(this.activateHandler?this.activateHandler(t):this.pendingActivations.push(t))}enable(t){this.set(t,"ALL")}disable(t){this.set(t,"FLUSH")}onActivate(t){(0,s.default)("[Caching] Setting activate handler",t,this.pendingActivations),this.activateHandler=t;for(let e=0;e{this.emitChange(t.data)})}get(t,e,n){return r(this,void 0,void 0,function*(){return"number"==typeof e?this.getNodes((0,c.pathsFromRoot)(t)).then(r=>{const i=u(r[t]);return h(r,e)?n(t):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}}):this.getNodes([t]).then(e=>{const n=u(e[t]);if(n){if((0,c.isFolder)(t))for(const t in n.itemsMap)n.itemsMap.hasOwnProperty(t)&&!1===n.itemsMap[t]&&delete n.itemsMap[t];return{statusCode:200,body:n.body||n.itemsMap,contentType:n.contentType}}return{statusCode:404}})})}put(t,e,n){return r(this,void 0,void 0,function*(){const r=(0,c.pathsFromRoot)(t);return this._updateNodes(r,function(t,r){try{for(let i=0,s=t.length;i0)break}else console.error("Cannot delete non-existing node "+i)}return n})})}flush(t){return this._getAllDescendentPaths(t).then(t=>this.getNodes(t)).then(t=>{for(const e in t){const n=t[e];n&&n.common&&n.local&&this.emitChange({path:n.path,origin:"local",oldValue:!1===n.local.body?void 0:n.local.body,newValue:!1===n.common.body?void 0:n.common.body}),t[e]=void 0}return this.setNodes(t)})}emitChange(t){a.default.changeEvents[t.origin]&&this._emit("change",t)}fireInitial(){a.default.changeEvents.local&&this.forAllNodes(t=>{if((0,c.isDocument)(t.path)){const e=u(t);e&&this.emitChange({path:t.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:e.body,newContentType:e.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(t){this.diffHandler=t}_updateNodes(t,e){return new Promise((n,r)=>{this._doUpdateNodes(t,e,{resolve:n,reject:r})})}_doUpdateNodes(t,e,n){return r(this,void 0,void 0,function*(){if(this._updateNodesRunning)return void this._updateNodesQueued.push({paths:t,cb:e,promise:n});this._updateNodesRunning=!0;try{let r=yield this.getNodes(t);const i=(0,c.deepClone)(r),s=[];r=e(t,r);for(const t in r){const e=r[t];(0,c.equal)(e,i[t])?delete r[t]:(0,c.isDocument)(t)&&((0,c.equal)(e.local.body,e.local.previousBody)&&e.local.contentType===e.local.previousContentType||s.push({path:t,origin:"window",oldValue:e.local.previousBody,newValue:!1===e.local.body?void 0:e.local.body,oldContentType:e.local.previousContentType,newContentType:e.local.contentType}),void 0===e.local.body?r[t]=void 0:(delete e.local.previousBody,delete e.local.previousContentType))}yield this.setNodes(r),this._emitChangeEvents(s),n.resolve({statusCode:200})}catch(t){n.reject(t)}this._updateNodesRunning=!1;const r=this._updateNodesQueued.shift();r&&(yield this._doUpdateNodes(r.paths,r.cb,r.promise))})}_emitChangeEvents(t){for(let e=0,n=t.length;e{const n=[t],r=u(e[t]),i=Object.keys(r.itemsMap).map(e=>this._getAllDescendentPaths(t+e).then(t=>{for(let e=0,r=t.length;en)}):Promise.resolve([t])}_getInternals(){return{getLatest:u,makeNode:d,isOutdated:h}}}(0,c.applyMixins)(f,[o.default]),t.exports=f},28:function(t){t.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},373:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(199)),s=r(n(28)),o=r(n(334)),a=n(746);let l;const c="remotestorage:discover";let u={};const h=function(t){return new Promise((e,n)=>{if(t in u)return e(u[t]);const r=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:s.default.discoveryTimeout});return setTimeout(()=>n(new Error("timed out")),s.default.discoveryTimeout),r.lookup(t,function(r,i){if(r)return n(r);if("object"!=typeof i.idx.links.remotestorage||"number"!=typeof i.idx.links.remotestorage.length||i.idx.links.remotestorage.length<=0)return(0,o.default)("[Discover] WebFinger record for "+t+" does not have remotestorage defined in the links section ",JSON.stringify(i.json)),n("WebFinger record for "+t+" does not have remotestorage defined in the links section.");const s=i.idx.links.remotestorage[0],a=s.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||s.properties["auth-endpoint"],h=s.properties["http://remotestorage.io/spec/version"]||s.type;return u[t]={href:s.href,storageApi:h,authURL:a,properties:s.properties},l&&localStorage.setItem(c,JSON.stringify({cache:u})),e(u[t])})})};(h.DiscoveryError=function(t){this.name="DiscoveryError",this.message=t,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),h.DiscoveryError.prototype.constructor=h.DiscoveryError,h._rs_init=function(){if(l=(0,a.localStorageAvailable)(),l){const t=JSON.parse(localStorage.getItem(c));t&&(u=t.cache)}},h._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},h._rs_cleanup=function(){l&&localStorage.removeItem(c)},t.exports=h},706:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(93)),o=i(n(424)),a=i(n(941)),l=i(n(982)),c=i(n(503)),u=n(746),h=n(368),d=n(684),p=i(n(275));let f;const g="remotestorage:dropbox",m="https://api.dropboxapi.com/2/files/list_folder",y="https://api.dropboxapi.com/2/files/list_folder/continue",v="/remotestorage";function b(t){return(v+"/"+t).replace(/\/+$/,"").replace(/\/+/g,"/")}const w=/[\u007f-\uffff]/g;function _(t){return JSON.stringify(t).replace(w,function(t){return"\\u"+("000"+t.charCodeAt(0).toString(16)).slice(-4)})}function x(t,e){return new RegExp("^"+e.join("\\/")+"(\\/|$)").test(t.error_summary)}function C(t){return t instanceof ArrayBuffer||(0,h.isArrayBufferView)(t)}class S extends d.RemoteBase{constructor(t){if(super(t),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=t.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},f=(0,u.localStorageAvailable)(),f){const t=(0,u.getJSONFromLocalStorage)(g);t&&this.configure(t),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return r(this,void 0,void 0,function*(){try{if(this.rs.setBackend("dropbox"),this.token)T(this.rs);else{const{codeVerifier:t,codeChallenge:e,state:n}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",t),sessionStorage.setItem("remotestorage:state",n),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:n,code_challenge:e,code_challenge_method:"S256",token_access_type:"offline"})}}catch(t){throw this.rs._emit("error",t),this.rs.setBackend(void 0),t}})}configure(t){return r(this,void 0,void 0,function*(){void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.token&&(this.token=t.token),void 0!==t.refreshToken&&(this.refreshToken=t.refreshToken),void 0!==t.tokenType&&(this.tokenType=t.tokenType);const e=()=>{f&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),e();else try{const t=yield this.info();this.userAddress=t.email,this._emit("connected"),e()}catch(t){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),e.apply(this)}else(()=>{this.connected=!1,f&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()})}_getFolder(t){const e=this._revCache,n=n=>{let i;if(200!==n.status&&409!==n.status)return Promise.reject("Unexpected response status: "+n.status);try{i=JSON.parse(n.responseText)}catch(t){return Promise.reject(t)}if(409===n.status)return x(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const s=i.entries.reduce((n,r)=>{try{const i="folder"===r[".tag"],s=r.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)n[s]={ETag:e.get(t+s)};else{const e=new Date(r.server_modified);n[s]={ETag:r.rev,"Content-Length":r.size,"Last-Modified":e.toUTCString()},this._revCache.set(t+s,r.rev)}}catch(e){console.error(`[Dropbox] folder “${t}” has entry ${JSON.stringify(r)}:`,e)}return n},{});return i.has_more?r(i.cursor).then(function(t){return Object.assign(s,t)}):Promise.resolve(s)},r=t=>{const e={body:{cursor:t}};return this._request("POST",y,e).then(n)};return this._request("POST",m,{body:{path:b(t)}}).then(n).then(function(n){return Promise.resolve({statusCode:200,body:n,contentType:"application/json; charset=UTF-8",revision:e.get(t)})})}get(t,e={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");const n=this._revCache.get(t);if(null===n)return Promise.resolve({statusCode:404});if(e&&e.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(t,e));if(n&&n===e.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===t.slice(-1))return this._getFolder(t);const r={headers:{"Dropbox-API-Arg":_({path:b(t)})},responseType:"arraybuffer"};return e&&e.ifNoneMatch&&(r.headers["If-None-Match"]=e.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",r).then(e=>{const n=e.status;let r,i,s,o;return 200!==n&&409!==n?Promise.resolve({statusCode:n}):(r=e.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(e.response,"UTF-8").then(a=>{i=a,409===n&&(r=i);try{r=JSON.parse(r)}catch(t){return Promise.reject(t)}if(409===n)return x(r,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+t+'"): '+r.error_summary));if(s=e.getResponseHeader("Content-Type"),o=r.rev,this._revCache.set(t,o),this._shareIfNeeded(t),(0,u.shouldBeTreatedAsBinary)(a,s))i=e.response;else try{i=JSON.parse(i),s="application/json; charset=UTF-8"}catch(t){}return{statusCode:n,body:i,contentType:s,revision:o}}))})}put(t,e,n){return r(this,arguments,void 0,function*(t,e,n,r={}){if(!this.connected)throw new Error("not connected (path: "+t+")");const i=this._revCache.get(t);if(r&&r.ifMatch&&i&&i!==r.ifMatch)return{statusCode:412,revision:i};if(r&&"*"===r.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!n.match(/charset=/)&&C(e)&&(n+="; charset=binary"),e.length>157286400)throw new Error("Cannot upload file larger than 150MB");const s={body:e,contentType:n,path:t};if(r&&(r.ifMatch||"*"===r.ifNoneMatch)){const e=yield this._getMetadata(t);if(r&&"*"===r.ifNoneMatch&&e)return{statusCode:412,revision:e.rev};if(r&&r.ifMatch&&e&&e.rev!==r.ifMatch)return{statusCode:412,revision:e.rev}}const o=yield this._uploadSimple(s);return this._shareIfNeeded(t),o})}delete(t){return r(this,arguments,void 0,function*(t,e={}){if(!this.connected)throw new Error("not connected (path: "+t+")");const n=this._revCache.get(t);if((null==e?void 0:e.ifMatch)&&n&&e.ifMatch!==n)return{statusCode:412,revision:n};if(null==e?void 0:e.ifMatch){const n=yield this._getMetadata(t);if((null==e?void 0:e.ifMatch)&&n&&n.rev!==e.ifMatch)return{statusCode:412,revision:n.rev}}return this._deleteSimple(t)})}_shareIfNeeded(t){if(t.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[t])return this.share(t)}share(t){const e={body:{path:b(t)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",e).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let n;try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?x(n,["shared_link_already_exists"])?this._getSharedLink(t):Promise.reject(new Error("API error: "+n.error_summary)):Promise.resolve(n.url)}).then(e=>(this._itemRefs[t]=e,f&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(e)),e=>(e.message='Sharing Dropbox file or folder ("'+t+'") failed: '+e.message,Promise.reject(e)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then(function(t){let e;try{const n=JSON.parse(t.responseText);e=null==n?void 0:n.email}catch(e){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+t.responseText))}return Promise.resolve({email:e})})}_request(t,e,n){return r(this,arguments,void 0,function*(t,e,n,r=1){if(this.isForbiddenRequestMethod(t,e))throw`Don't use ${t} on directories!`;if(!this.token)throw new c.default("No access token");n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,"object"!=typeof n.body||C(n.body)||(n.body=JSON.stringify(n.body),n.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:t,isFolder:(0,u.isFolder)(e)});try{const i=yield(0,h.requestWithTimeout)(t,e,n);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?r>=3?(console.error(`Abandoned after ${r} attempts: ${t} ${e}`),i):(this.rs._emit("wire-busy",{method:t,isFolder:(0,u.isFolder)(e)}),yield p.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!0}),this._request(t,e,n,r+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),r>=3?(console.warn(`Abandoned after ${r} attempts: ${t} ${e}`),i):(yield new Promise(t=>setTimeout(t,(0,h.retryAfterMs)(i))),this._request(t,e,n,r+1))):i}catch(n){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!1}),n}})}fetchDelta(...t){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const e=t=>r(this,void 0,void 0,function*(){let n,r;"string"==typeof t?(n=y,r={cursor:t}):(n=m,r={path:v,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",n,{body:r});if(401===i.status)throw new c.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let s;try{s=JSON.parse(i.responseText)}catch(t){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!x(s,["path","not_found"]))throw new Error("API returned an error: "+s.error_summary);s={cursor:null,entries:[],has_more:!1}}if(t||this._revCache.deactivatePropagation(),s.entries.forEach(t=>{const e=t.path_display.slice(14);"deleted"===t[".tag"]?(this._revCache.delete(e),this._revCache.delete(e+"/")):"file"===t[".tag"]&&this._revCache.set(e,t.rev)}),this._fetchDeltaCursor=s.cursor,s.has_more)return e(s.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(t){if("timeout"===t)return;throw t}});return this._fetchDeltaPromise=e(this._fetchDeltaCursor).catch(t=>("object"==typeof t&&"message"in t?t.message="Dropbox: fetchDelta: "+t.message:t=`Dropbox: fetchDelta: ${t}`,this.rs._emit("error",t),this._fetchDeltaPromise=null,Promise.reject(t))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(t))),this._fetchDeltaPromise}_getMetadata(t){const e={path:b(t)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:e}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?x(e,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+e.error_summary)):Promise.resolve(e)}).then(void 0,e=>(e.message='Could not load metadata for file or folder ("'+t+'"): '+e.message,Promise.reject(e)))}_uploadSimple(t){const e={path:b(t.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return t.ifMatch&&(e.mode={".tag":"update",update:t.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:t.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":_(e)}}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let n;try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid API result: "+e.responseText))}return 409===e.status?x(n,["path","conflict"])?this._getMetadata(t.path).then(function(t){return Promise.resolve({statusCode:412,revision:t.rev})}):(this.rs._emit("error",new Error(n.error_summary)),Promise.resolve({statusCode:e.status})):(this._revCache.set(t.path,n.rev),Promise.resolve({statusCode:e.status,revision:n.rev}))})}_deleteSimple(t){const e={path:b(t)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:e}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}if(409===t.status){if(x(e,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(e.error_summary))}return Promise.resolve({statusCode:t.status})}).then(e=>(200!==e.statusCode&&404!==e.statusCode||(this._revCache.delete(t),delete this._itemRefs[t]),Promise.resolve(e)),e=>(e.message='Could not delete Dropbox file or folder ("'+t+'"): '+e.message,Promise.reject(e)))}_getSharedLink(t){return r(this,void 0,void 0,function*(){const e={body:{path:b(t),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",e).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status: "+t.status));let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?Promise.reject(new Error("API error: "+(null==e?void 0:e.error_summary)||0)):e.links.length?Promise.resolve(e.links[0].url):Promise.reject(new Error("No links returned"))},e=>(e.message='Could not get link to a shared file or folder ("'+t+'"): '+e.message,Promise.reject(e)))})}static _rs_init(t){f=(0,u.localStorageAvailable)(),t.apiKeys.dropbox&&(t.dropbox=new S(t)),"dropbox"===t.backend&&T(t)}static _rs_supported(){return!0}static _rs_cleanup(t){!function(t){(function(t){t._origRemote&&(t.remote=t._origRemote,delete t._origRemote)})(t),function(t){t._dropboxOrigSync&&(t.sync.sync=t._dropboxOrigSync,delete t._dropboxOrigSync)}(t),function(t){t._origBaseClientGetItemURL&&(o.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}(t),E(t)}(t),f&&localStorage.removeItem(g),t.setBackend(void 0)}}function k(t,...e){t._dropboxOrigSync||(t._dropboxOrigSync=t.sync.sync.bind(t.sync),t.sync.sync=function(){return this.dropbox.fetchDelta(t,...e).then(t._dropboxOrigSync,function(e){t._emit("error",new l.default(e)),t._emit("sync-done")})}.bind(t))}function E(t){t._dropboxOrigSyncCycle&&(t.syncCycle=t._dropboxOrigSyncCycle,delete t._dropboxOrigSyncCycle)}function T(t){!function(t){t._origRemote||(t._origRemote=t.remote,t.remote=t.dropbox)}(t),t.sync?k(t):function(t,...e){t._dropboxOrigSyncCycle||(t._dropboxOrigSyncCycle=t.syncCycle,t.syncCycle=()=>{if(!t.sync)throw new Error("expected sync to be initialized by now");k(t),t._dropboxOrigSyncCycle(t,...e),E(t)})}(t),function(t){t._origBaseClientGetItemURL||(t._origBaseClientGetItemURL=o.default.prototype.getItemURL,o.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(t)}(0,u.applyMixins)(S,[s.default]),t.exports=S},451:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(93)),s=n(746),o=r(n(334));class a{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?((0,o.default)("[Env] Going into background mode"),this.goBackground()):((0,o.default)("[Env] Going into foreground mode"),this.goForeground())}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,s.applyMixins)(a,[i.default]),t.exports=a},93:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.EventHandling=void 0;const i=r(n(334));class s{addEvents(t){t.forEach(t=>this._addEvent(t))}addEventListener(t,e){if("string"!=typeof t)throw new Error("Argument eventName should be a string");if("function"!=typeof e)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",t),this._validateEvent(t),this._handlers[t].push(e)}on(t,e){return this.addEventListener(t,e)}removeEventListener(t,e){this._validateEvent(t);const n=this._handlers[t].length;for(let r=0;r{t(...e)})}_validateEvent(t){if(!(t in this._handlers))throw new Error("Unknown event: "+t)}_delegateEvent(t,e){e.on(t,e=>{this._emit(t,e)})}_addEvent(t){void 0===this._handlers&&(this._handlers={}),this._handlers[t]=[]}}e.EventHandling=s,e.default=s},545:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(28)),s=r(n(451)),o=r(n(334)),a=n(746),l=r(n(370)),c=r(n(548)),u=r(n(275)),h=r(n(373)),d=r(n(424)),p=r(n(801)),f=r(n(706)),g=r(n(600)),m=r(n(313)),y=r(n(285)),v=r(n(567)),b=r(n(794)),w=r(n(365)),_={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:g.default,Dropbox:f.default,GoogleDrive:p.default,Access:c.default,Discover:h.default,Authorize:u.default,BaseClient:d.default,Env:s.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:y.default,IndexedDB:v.default,LocalStorage:b.default,InMemoryStorage:w.default,Sync:m.default}),i.default.disableFeatures.forEach(t=>{this.featureModules[t]&&delete this.featureModules[t]}),this._allLoaded=!1;for(const t in this.featureModules)this.loadFeature(t)},hasFeature(t){for(let e=this.features.length-1;e>=0;e--)if(this.features[e].name===t)return this.features[e].supported;return!1},loadFeature(t){const e=this.featureModules[t],n=!e._rs_supported||e._rs_supported();(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initializing ...`),"object"==typeof n?n.then(()=>{this.featureSupported(t,!0),this.initFeature(t)},()=>{this.featureSupported(t,!1)}):"boolean"==typeof n?(this.featureSupported(t,n),n&&this.initFeature(t)):this.featureSupported(t,!1)},initFeature(t){const e=this.featureModules[t];let n;try{n=e._rs_init(this)}catch(e){return void this.featureFailed(t,e)}"object"==typeof n&&"function"==typeof n.then?n.then(()=>{this.featureInitialized(t)},e=>{this.featureFailed(t,e)}):this.featureInitialized(t)},featureFailed(t,e){(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initialization failed (${e})`),this.featureDone()},featureSupported(t,e){(0,o.default)(`[RemoteStorage] [FEATURE ${t}]${e?"":"not "} supported`),e||this.featureDone()},featureInitialized(t){(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initialized`),this.features.push({name:t,init:this.featureModules[t]._rs_init,supported:!0,cleanup:this.featureModules[t]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(t=>{if(this.features.some(e=>e.name===t))return this.features.local=this.featureModules[t],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(t){console.error("'ready' failed: ",t,t.stack),this._emit("error",t)}},featuresLoaded(){(0,o.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(l.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._emit("not-connected")}),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(t){(0,a.logError)(t),this._emit("error",t)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let t=0;t=n-this.maxAge?e.v:void 0}set(t,e){this._items[t]={v:e,t:(new Date).getTime()}}}class v extends l.RemoteBase{constructor(t,e){if(super(t),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=e,this._fileIdCache=new y(300),d=(0,o.localStorageAvailable)(),d){const t=(0,o.getJSONFromLocalStorage)(u);t&&this.configure(t)}}configure(t){void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.token&&(this.token=t.token);const e=function(){d&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},n=function(){this.connected=!1,delete this.token,d&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),e.apply(this)):this.info().then(t=>{this.userAddress=t.user.emailAddress,this._emit("connected"),e.apply(this)}).catch(()=>{n.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):n.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(t,e={}){return(0,o.isFolder)(t)?this._getFolder(m(t)):this._getFile(m(t),e)}put(t,e,n,r={}){const i=m(t);function s(t){if(t.status>=200&&t.status<300){const e=JSON.parse(t.responseText),n=this.stripQuotes(e.etag);return Promise.resolve({statusCode:200,contentType:e.mimeType,revision:n})}return 412===t.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+t.status+" ("+t.responseText+")")}return this._getFileId(i).then(t=>t?r&&"*"===r.ifNoneMatch?s({status:412}):this._updateFile(t,i,e,n,r).then(s):this._createFile(i,e,n).then(s))}delete(t,e={}){const n=m(t);return this._getFileId(n).then(t=>t?this._getMeta(t).then(n=>{let r;return"object"==typeof n&&"string"==typeof n.etag&&(r=this.stripQuotes(n.etag)),e&&e.ifMatch&&e.ifMatch!==r?{statusCode:412,revision:r}:this._request("DELETE",c+"/drive/v2/files/"+t,{}).then(t=>200===t.status||204===t.status?{statusCode:200}:Promise.reject("Delete failed: "+t.status+" ("+t.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){const t=c+"/drive/v2/about?fields=user";return this._request("GET",t,{}).then(function(t){try{const e=JSON.parse(t.responseText);return Promise.resolve(e)}catch(t){return Promise.reject(t)}})}_updateFile(t,e,n,r,i){const s={mimeType:r},o={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(o["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",c+"/upload/drive/v2/files/"+t+"?uploadType=resumable",{body:JSON.stringify(s),headers:o}).then(t=>412===t.status?t:this._request("PUT",t.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(n):n}))}_createFile(t,e,n){return this._getParentId(t).then(r=>{const i={title:p(g(t)),mimeType:n,parents:[{kind:"drive#fileLink",id:r}]};return this._request("POST",c+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(t=>this._request("POST",t.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(e):e}))})}_getFile(t,e){return this._getFileId(t).then(t=>this._getMeta(t).then(t=>{let n;if("object"==typeof t&&"string"==typeof t.etag&&(n=this.stripQuotes(t.etag)),e&&e.ifNoneMatch&&n===e.ifNoneMatch)return Promise.resolve({statusCode:304});if(!t.downloadUrl){if(!t.exportLinks||!t.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:t.mimeType,revision:n});t.mimeType+=";export=text/html",t.downloadUrl=t.exportLinks["text/html"]}return this._request("GET",t.downloadUrl,{responseType:"arraybuffer"}).then(e=>(0,o.getTextFromArrayBuffer)(e.response,"UTF-8").then(function(r){let i=r;if(t.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(t){}else(0,o.shouldBeTreatedAsBinary)(r,t.mimeType)&&(i=e.response);return{statusCode:200,body:i,contentType:t.mimeType,revision:n}}))}))}_getFolder(t){return this._getFileId(t).then(e=>{let n,r,i;if(!e)return Promise.resolve({statusCode:404});const s="'"+e+"' in parents";return this._request("GET",c+"/drive/v2/files?q="+encodeURIComponent(s)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(e=>{var s;if(200!==e.status)return Promise.reject("request failed or something: "+e.status);try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const a of n.items)(null===(s=a.labels)||void 0===s?void 0:s.trashed)||(r=this.stripQuotes(a.etag),a.mimeType===h?(this._fileIdCache.set(t+(0,o.cleanPath)(a.title)+"/",a.id),i[a.title+"/"]={ETag:r}):(this._fileIdCache.set(t+(0,o.cleanPath)(a.title),a.id),i[a.title]={ETag:r,"Content-Type":a.mimeType,"Content-Length":a.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(t){const e=f(t);return this._getFileId(e).then(t=>t?Promise.resolve(t):this._createFolder(e))}_createFolder(t){return this._getParentId(t).then(e=>this._request("POST",c+"/drive/v2/files",{body:JSON.stringify({title:p(g(t)),mimeType:h,parents:[{id:e}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(t=>{const e=JSON.parse(t.responseText);return Promise.resolve(e.id)}))}_getFileId(t){let e;return"/"===t?Promise.resolve("root"):(e=this._fileIdCache.get(t))?Promise.resolve(e):this._getFolder(f(t)).then(()=>(e=this._fileIdCache.get(t),e?Promise.resolve(e):"/"===t.substr(-1)?this._createFolder(t).then(()=>this._getFileId(t)):Promise.resolve()))}_getMeta(t){return this._request("GET",c+"/drive/v2/files/"+t,{}).then(function(e){return 200===e.status?Promise.resolve(JSON.parse(e.responseText)):Promise.reject("request (getting metadata for "+t+") failed with status: "+e.status)})}_request(t,e,n){return this.isForbiddenRequestMethod(t,e)?Promise.reject(`Don't use ${t} on directories!`):(n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:t,isFolder:(0,o.isFolder)(e)}),(0,a.requestWithTimeout)(t,e,n).then(n=>n&&401===n.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,o.isFolder)(e),success:!0}),Promise.resolve(n)),n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,o.isFolder)(e),success:!1}),Promise.reject(n))))}static _rs_init(t){const e=t.apiKeys.googledrive;var n;e&&(t.googledrive=new v(t,e.clientId),"googledrive"===t.backend&&(t._origRemote=t.remote,t.remote=t.googledrive,(n=t)._origBaseClientGetItemURL||(n._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(t){var e;t.setBackend(void 0),t._origRemote&&(t.remote=t._origRemote,delete t._origRemote),(e=t)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}}(0,o.applyMixins)(v,[s.default]),t.exports=v},567:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(93)),o=i(n(496)),a=i(n(334)),l=n(746),c="remotestorage";let u;class h extends o.default{constructor(t){super(),this.addEvents(["change","local-events-done"]),this.db=t||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(t){return r(this,void 0,void 0,function*(){const e=[],n={};for(let r=0,i=t.length;r0?this.getNodesFromDb(e).then(function(t){for(const e in n)t[e]=n[e];return t}):n})}setNodes(t){return r(this,void 0,void 0,function*(){for(const e in t)this.changesQueued[e]=t[e]||!1;this.maybeFlush()})}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=n.g.setInterval(function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(t){return new Promise((e,n)=>{const r=this.db.transaction(["nodes"],"readonly"),i=r.objectStore("nodes"),s={};this.getsRunning++,t.map(t=>{i.get(t).onsuccess=e=>{s[t]=e.target.result}}),r.oncomplete=()=>{e(s),this.getsRunning--},r.onerror=r.onabort=()=>{n("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(t){return r(this,void 0,void 0,function*(){return new Promise((e,n)=>{const r=this.db.transaction(["nodes"],"readwrite"),i=r.objectStore("nodes"),s=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting puts",t,this.putsRunning);for(const o in t){const e=t[o];if("object"==typeof e)try{i.put(e)}catch(t){throw(0,a.default)("[IndexedDB] Error while putting",e,t),t}else try{i.delete(o)}catch(t){throw(0,a.default)("[IndexedDB] Error while removing",i,e,t),t}}r.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished puts",t,this.putsRunning,(new Date).getTime()-s+"ms"),e()},r.onerror=()=>{this.putsRunning--,n("transaction error")},r.onabort=()=>{n("transaction abort"),this.putsRunning--}})})}reset(t){const e=this.db.name;this.db.close(),h.clean(e,()=>{h.open(e,(n,r)=>{n?(0,a.default)(`[IndexedDB] Error while resetting database ${e}:`,n):this.db=r,"function"==typeof t&&t(self)})})}forAllNodes(t){return r(this,void 0,void 0,function*(){return new Promise(e=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=n=>{const r=n.target.result;r?(t(r.value),r.continue()):e()}})})}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(t,e){const n=setTimeout(function(){e("timeout trying to open db")},1e4);try{const r=indexedDB.open(t,2);r.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",r),clearTimeout(n),e(r.error)},r.onupgradeneeded=function(t){const e=r.result;(0,a.default)("[IndexedDB] Upgrade: from ",t.oldVersion," to ",t.newVersion),1!==t.oldVersion&&((0,a.default)("[IndexedDB] Creating object store: nodes"),e.createObjectStore("nodes",{keyPath:"path"})),(0,a.default)("[IndexedDB] Creating object store: changes"),e.createObjectStore("changes",{keyPath:"path"})},r.onsuccess=function(){clearTimeout(n);const i=r.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),void h.clean(t,function(){h.open(t,e)});e(null,r.result)}}catch(r){(0,a.default)("[IndexedDB] Failed to open database: "+r),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(n),h.clean(t,function(){h.open(t,e)})}}static clean(t,e){const n=indexedDB.deleteDatabase(t);n.onsuccess=function(){(0,a.default)(`[IndexedDB] Deleted database "${t}"`),e()},n.onerror=n.onabort=function(e){console.error('Failed to remove database "'+t+'"',e)}}static _rs_init(t){return new Promise((e,n)=>{h.open(c,function(r,i){r?n(r):(u=i,i.onerror=()=>{t._emit("error",r)},e())})})}static _rs_supported(){return new Promise((t,e)=>{const n=(0,l.getGlobalContext)();let r=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(r=!0)),"indexedDB"in n&&!r)try{const n=indexedDB.open("rs-check");n.onerror=function(){e()},n.onsuccess=function(){n.result.close(),indexedDB.deleteDatabase("rs-check"),t()}}catch(t){e()}else e()})}static _rs_cleanup(t){return new Promise(e=>{t.local instanceof h&&t.local.closeDB(),h.clean(c,e)})}diffHandler(){}}(0,l.applyMixins)(h,[s.default]),t.exports=h},365:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(93)),s=r(n(496)),o=n(746);class a extends s.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(t){const e={};for(let n=0,r=t.length;n=2e3&&t<=36e5}var E;!function(t){t.GOOGLE="googledrive",t.DROPBOX="dropbox"}(E||(E={}));class T{constructor(t){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=w.default.loadFeatures,this.features=w.default.features,this.loadFeature=w.default.loadFeature,this.featureSupported=w.default.featureSupported,this.featureDone=w.default.featureDone,this.featuresDone=w.default.featuresDone,this.featuresLoaded=w.default.featuresLoaded,this.featureInitialized=w.default.featureInitialized,this.featureFailed=w.default.featureFailed,this.hasFeature=w.default.hasFeature,this._setCachingModule=w.default._setCachingModule,this._collectCleanupFunctions=w.default._collectCleanupFunctions,this._fireReady=w.default._fireReady,this.initFeature=w.default.initFeature,"object"==typeof t&&(0,c.extend)(a.default,t),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-started","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),C=(0,c.localStorageAvailable)(),C){this.apiKeys=(0,c.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const t=localStorage.getItem("remotestorage:backend");"dropbox"===t||"googledrive"===t?this.setBackend(t):this.setBackend("remotestorage")}const e=this.on;this.on=function(t,n){if(this._allLoaded)switch(t){case"features-loaded":setTimeout(n,0);break;case"ready":this.remote&&setTimeout(n,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(n,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(n,0)}return e.call(this,t,n)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){a.default.modules.forEach(this.addModule.bind(this))}authorize(t){if(this.access.setStorageType(this.remote.storageApi),void 0===t.scope&&(t.scope=this.access.scopeParameter),x.cordova)t.redirectUri=a.default.cordovaRedirectUri;else{const e=h.default.getLocation();let n=e.origin;"/"!==e.pathname&&(n+=e.pathname),t.redirectUri=n}void 0===t.clientId&&(t.clientId=t.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h.default.authorize(this,t)}impliedauth(t,e){t=t||this.remote.storageApi,e=e||String(document.location),(0,l.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+t+" redirectUri = "+e),this.remote.configure({token:h.default.IMPLIED_FAKE_TOKEN}),document.location.href=e}connect(t,e){if(this.setBackend("remotestorage"),t.indexOf("@")<0&&!t.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new T.DiscoveryError("Not a valid user address or URL."));else{if(t.indexOf("@")<0&&!t.match(/^https?:\/\//)&&(t=`https://${t}`),x.cordova){if("string"!=typeof a.default.cordovaRedirectUri)return void this._emit("error",new T.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!x.cordova.InAppBrowser)return void this._emit("error",new T.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:t}),this._emit("connecting"),(0,y.default)(t).then(n=>{if(this._emit("authing"),n.userAddress=t,this.remote.configure(n),!this.remote.connected)if(n.authURL)if(void 0===e)this.authorize({authURL:n.authURL});else{if("string"!=typeof e)throw new Error("Supplied bearer token must be a string");(0,l.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:e})}else this.impliedauth()},()=>{this._emit("error",new T.DiscoveryError("No storage information found for this user address."))})}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const t=this._cleanups.length;let e=0;const n=()=>{e++,e>=t&&(this._init(),(0,l.default)('Cleanups done, emitting "disconnected" event'),this._emit("disconnected"))};t>0?this._cleanups.forEach(t=>{const e=t(this);"object"==typeof e&&"function"==typeof e.then?e.then(n):n()}):n()}setBackend(t){this.backend=t,C&&(void 0!==t?localStorage.setItem("remotestorage:backend",t):localStorage.removeItem("remotestorage:backend"))}onChange(t,e){this._pathHandlers.change[t]||(this._pathHandlers.change[t]=[]),this._pathHandlers.change[t].push(e)}enableLog(){a.default.logging=!0}disableLog(){a.default.logging=!1}log(...t){l.default.apply(T,t)}setApiKeys(t){const e=[E.GOOGLE,E.DROPBOX];if("object"!=typeof t||!Object.keys(t).every(t=>e.includes(t)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(t).forEach(e=>{const n=t[e];if(n){switch(e){case E.DROPBOX:this.apiKeys[E.DROPBOX]={appKey:n},void 0!==this.dropbox&&this.dropbox.clientId===n||m.default._rs_init(this);break;case E.GOOGLE:this.apiKeys[E.GOOGLE]={clientId:n},void 0!==this.googledrive&&this.googledrive.clientId===n||g.default._rs_init(this)}return!0}delete this.apiKeys[e]}),C&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(t){if("string"!=typeof t||!t.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");a.default.cordovaRedirectUri=t}_setGPD(t,e){function n(t){return function(...n){return t.apply(e,n).then(S.bind(this))}}this.get=n(t.get),this.put=n(t.put),this.delete=n(t.delete)}_pendingGPD(t){return(...e)=>{const n=Array.prototype.slice.call(e);return new Promise((e,r)=>{this._pending.push({method:t,args:n,promise:{resolve:e,reject:r}})})}}_processPending(){this._pending.forEach(t=>{try{this[t.method](...t.args).then(t.promise.resolve,t.promise.reject)}catch(e){t.promise.reject(e)}}),this._pending=[]}_bindChange(t){t.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(t,e){Object.keys(this._pathHandlers[t]).forEach(n=>{const r=n.length;e.path.substr(0,r)===n&&this._pathHandlers[t][n].forEach(t=>{const r={};for(const n in e)r[n]=e[n];r.relativePath=e.path.replace(new RegExp("^"+n),"");try{t(r)}catch(t){console.error("'change' handler failed: ",t,t.stack),this._emit("error",t)}})})}scope(t){if("string"!=typeof t)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(t,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestorage.io/rs.js/docs/api/access/classes/Access.html#claim"),new d.default(this,t)}getSyncInterval(){return a.default.syncInterval}setSyncInterval(t){if(!k(t))throw t+" is not a valid sync interval";const e=a.default.syncInterval;a.default.syncInterval=t,this._emit("sync-interval-change",{oldValue:e,newValue:t})}getBackgroundSyncInterval(){return a.default.backgroundSyncInterval}setBackgroundSyncInterval(t){if(!k(t))throw t+" is not a valid sync interval";const e=a.default.backgroundSyncInterval;a.default.backgroundSyncInterval=t,this._emit("sync-interval-change",{oldValue:e,newValue:t})}getCurrentSyncInterval(){return a.default.isBackground?a.default.backgroundSyncInterval:a.default.syncInterval}getRequestTimeout(){return a.default.requestTimeout}setRequestTimeout(t){if("number"!=typeof t)throw t+" is not a valid request timeout";a.default.requestTimeout=t}setupSyncCycle(){this.sync&&!this.sync.stopped&&((0,l.default)("[Sync] Setting up sync cycle"),this.on("sync-done",()=>{(0,l.default)("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync&&!this.sync.stopped&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}),this.sync.sync())}startSync(){return a.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?((0,l.default)("[Sync] Stopping sync"),this.sync.stopped=!0):((0,l.default)("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)}addModule(t){const e=t.name,n=t.builder;if(Object.defineProperty(this,e,{configurable:!0,get:function(){const t=this._loadModule(e,n);return Object.defineProperty(this,e,{value:t}),t}}),-1!==e.indexOf("-")){const t=e.replace(/\-[a-z]/g,function(t){return t[1].toUpperCase()});Object.defineProperty(this,t,{get:function(){return this[e]}})}}_loadModule(t,e){if(e)return e(new d.default(this,"/"+t+"/"),new d.default(this,"/public/"+t+"/")).exports;throw"Unknown module: "+t}}e.RemoteStorage=T,T.SyncError=v.default,T.Unauthorized=b.default,T.DiscoveryError=y.default.DiscoveryError,T.util=_,Object.defineProperty(T.prototype,"access",{configurable:!0,get:function(){const t=new u.default;return Object.defineProperty(this,"access",{value:t}),t}}),Object.defineProperty(T.prototype,"caching",{configurable:!0,get:function(){const t=new p.default(this);return Object.defineProperty(this,"caching",{value:t}),t}}),(0,c.applyMixins)(T,[f.EventHandling]),e.default=T},368:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.isArrayBufferView=void 0,e.retryAfterMs=function(t){const e=1e3*parseInt(t.getResponseHeader("Retry-After"));return e>=1e3?e:Math.max(1500,Math.min(6e4,Math.round(o.default.syncInterval/(2.9+.2*Math.random()))))},e.requestWithTimeout=function(t,n,i){return r(this,void 0,void 0,function*(){return"function"==typeof fetch?function(t,e,n){return r(this,void 0,void 0,function*(){const r="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise((t,e)=>{i=setTimeout(()=>{r&&r.abort(),e("timeout")},o.default.requestTimeout)});let l;const c={},u=fetch(e,{method:t,headers:n.headers,body:n.body,signal:r?r.signal:void 0}).then(t=>{switch((0,s.default)("[requests fetch]",t),t.headers.forEach((t,e)=>{c[e.toUpperCase()]=t}),l={readyState:4,status:t.status,statusText:t.statusText,response:void 0,getResponseHeader:t=>c[t.toUpperCase()]||null,responseType:n.responseType,responseURL:e},n.responseType){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"json":return t.json();case void 0:case"":case"text":return t.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}}).then(t=>(l.response=t,n.responseType&&"text"!==n.responseType||(l.responseText=t),l)).finally(()=>{clearTimeout(i)});return Promise.race([u,a])})}(t,n,i):"function"==typeof XMLHttpRequest?function(t,n,i){return r(this,void 0,void 0,function*(){return new Promise((r,a)=>{(0,s.default)("[requests XHR]",t,n);let l=!1;const c=setTimeout(()=>{l=!0,a("timeout")},o.default.requestTimeout),u=new XMLHttpRequest;if(u.open(t,n,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const t in i.headers)u.setRequestHeader(t,i.headers[t]);u.onload=()=>{l||(clearTimeout(c),r(u))},u.onerror=t=>{l||(clearTimeout(c),a(t))};let h=i.body;"object"==typeof h&&!(0,e.isArrayBufferView)(h)&&h instanceof ArrayBuffer&&(h=new Uint8Array(h)),u.send(h)})})}(t,n,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")})};const s=i(n(334)),o=i(n(28));if("function"==typeof(n.g||window).ArrayBufferView)e.isArrayBufferView=function(t){return t&&t instanceof(n.g||window).ArrayBufferView};else{const t=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];e.isArrayBufferView=function(e){for(let n=0;n<8;n++)if(e instanceof t[n])return!0;return!1}}},941:function(t){t.exports=class{constructor(t){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=t,this.activatePropagation()}get(t){t=t.toLowerCase();let e=this._storage[t];return void 0===e&&(e=this.defaultValue,this._storage[t]=e),e}set(t,e){return t=t.toLowerCase(),this._storage[t]===e||(this._storage[t]=e,e||delete this._itemsRev[t],this._updateParentFolderItemRev(t,e),this._canPropagate&&this._propagate(t)),e}delete(t){return this.set(t,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(t){let e=0;if(0===t.length)return e;for(let n=0;n0&&(n=this._generateHash(t))}return this.set(t,n),n}}},491:function(t){class e extends Error{constructor(t){super();const e=new Error("Schema not found: "+t);return e.name="SchemaNotFound",e}}t.exports=e},982:function(t){class e extends Error{constructor(t){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof t?this.message+=t:(this.message+=t.message,this.stack=t.stack,this.originalError=t)}}t.exports=e},313:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Sync=void 0;const s=i(n(28)),o=i(n(451)),a=i(n(93)),l=i(n(334)),c=i(n(275)),u=i(n(982)),h=i(n(503)),d=n(746);let p,f;function g(t,e,n){return{action:t,path:e,promise:n}}function m(t,e){return t.common.revision!==e&&(!t.remote||t.remote.revision!==e)}function y(t){return!!t.common&&!!t.common.revision}class v{constructor(t){this.numThreads=10,this._tasks={},this._running={},this._timeStarted={},this._finishedTasks=[],this.rs=t,this.rs.local.onDiff(t=>{this.addTask(t),this.doTasks()}),this.rs.caching.onActivate(t=>{this.addTask(t),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(t){return r(this,void 0,void 0,function*(){return new Promise((e,n)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(t,function(){this.rs.local.get(t).then(t=>e(t))}.bind(this)),this.doTasks()):n("cannot fulfill maxAge requirement - remote is not online"):n("cannot fulfill maxAge requirement - remote is not connected")})})}corruptServerItemsMap(t){if("object"!=typeof t||Array.isArray(t))return!0;for(const e in t){const n=t[e];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if((0,d.isFolder)(e)){if(-1!==e.substring(0,e.length-1).indexOf("/"))return!0}else if(-1!==e.indexOf("/"))return!0}return!1}corruptItemsMap(t){if("object"!=typeof t||Array.isArray(t))return!0;for(const e in t)if("boolean"!=typeof t[e])return!0;return!1}corruptRevision(t){return"object"!=typeof t||Array.isArray(t)||t.revision&&"string"!=typeof t.revision||t.body&&"string"!=typeof t.body&&"object"!=typeof t.body||t.contentType&&"string"!=typeof t.contentType||t.contentLength&&"number"!=typeof t.contentLength||t.timestamp&&"number"!=typeof t.timestamp||t.itemsMap&&this.corruptItemsMap(t.itemsMap)}isCorrupt(t){return"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.path||this.corruptRevision(t.common)||t.local&&this.corruptRevision(t.local)||t.remote&&this.corruptRevision(t.remote)||t.push&&this.corruptRevision(t.push)}hasTasks(){return Object.keys(this._tasks).length>0}collectDiffTasks(){return r(this,void 0,void 0,function*(){let t=0;return this.rs.local.forAllNodes(e=>{t>100||(this.isCorrupt(e)?((0,l.default)("[Sync] WARNING: corrupt node in local cache",e),"object"==typeof e&&e.path&&(this.addTask(e.path),t++)):(this.needsFetch(e)&&this.rs.access.checkPathPermission(e.path,"r")||(0,d.isDocument)(e.path)&&this.needsPush(e)&&this.rs.access.checkPathPermission(e.path,"rw"))&&(this.addTask(e.path),t++))}).then(()=>t)})}inConflict(t){return!(!t.local||!t.remote||void 0===t.remote.body&&!t.remote.itemsMap)}needsRefresh(t){return!!t.common&&(!t.common.timestamp||this.now()-t.common.timestamp>s.default.syncInterval)}needsFetch(t){return!!this.inConflict(t)||!(!t.common||void 0!==t.common.itemsMap||void 0!==t.common.body)||!(!t.remote||void 0!==t.remote.itemsMap||void 0!==t.remote.body)}needsPush(t){return!this.inConflict(t)&&(!(!t.local||t.push)||void 0)}needsRemotePut(t){return t.local&&"string"==typeof t.local.body}needsRemoteDelete(t){return t.local&&!1===t.local.body}getParentPath(t){const e=t.match(/^(.*\/)([^\/]+\/?)$/);if(e)return e[1];throw new Error('Not a valid path: "'+t+'"')}deleteChildPathsFromTasks(){for(const t in this._tasks){const e=(0,d.pathsFromRoot)(t);for(let n=1;n{let e;if(this.needsRefresh(t)){try{e=this.getParentPath(t.path)}catch(t){}e&&this.rs.access.checkPathPermission(e,"r")?this.addTask(e):this.rs.access.checkPathPermission(t.path,"r")&&this.addTask(t.path)}}),this.deleteChildPathsFromTasks()})}flush(t){for(const e in t)"FLUSH"===this.rs.caching.checkPath(e)&&t[e]&&!t[e].local&&((0,l.default)("[Sync] Flushing",e),t[e]=void 0);return t}doTask(t){return r(this,void 0,void 0,function*(){return this.rs.local.getNodes([t]).then(e=>{const n=e[t];return void 0===n||function(t){return!(!t.remote||!t.remote.revision||t.remote.itemsMap||t.remote.body)}(n)?g("get",t,this.rs.remote.get(t)):this.needsRemotePut(n)?(n.push=(0,d.deepClone)(n.local),n.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(e)).then(()=>{let e;return e=y(n)?{ifMatch:n.common.revision}:{ifNoneMatch:"*"},g("put",t,this.rs.remote.put(t,n.push.body,n.push.contentType,e))})):this.needsRemoteDelete(n)?(n.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(e)).then(()=>y(n)?g("delete",t,this.rs.remote.delete(t,{ifMatch:n.common.revision})):g("get",t,this.rs.remote.get(t)))):y(n)?g("get",t,this.rs.remote.get(t,{ifNoneMatch:n.common.revision})):g("get",t,this.rs.remote.get(t))})})}autoMergeFolder(t){if(t.remote.itemsMap&&(t.common=t.remote,delete t.remote,t.common.itemsMap)){for(const e in t.common.itemsMap)t.local.itemsMap[e]||(t.local.itemsMap[e]=!1);for(const e in t.local.itemsMap)t.common.itemsMap[e]||this.addTask(t.path+e);(0,d.equal)(t.local.itemsMap,t.common.itemsMap)&&delete t.local}return t}autoMergeDocument(t){var e;return function(t){return(!t.remote||!t.remote.revision||t.remote.revision===t.common.revision)&&(void 0===t.common.body&&!1===t.remote.body||t.remote.body===t.common.body&&t.remote.contentType===t.common.contentType)}(t)?delete(t=function(t){return t.remote&&!1===t.remote.body&&t.local&&!1===t.local.body&&delete t.local,t}(t)).remote:void 0!==t.remote.body&&(!1===t.remote.body&&!1===(null===(e=t.local)||void 0===e?void 0:e.body)||((0,l.default)("[Sync] Emitting conflict event"),setTimeout(this.rs.local.emitChange.bind(this.rs.local),10,{origin:"conflict",path:t.path,oldValue:t.local.body,newValue:t.remote.body,lastCommonValue:t.common.body,oldContentType:t.local.contentType,newContentType:t.remote.contentType,lastCommonContentType:t.common.contentType})),!1===t.remote.body?t.common={}:t.common=t.remote,delete t.remote,delete t.local),t}autoMerge(t){if(t.remote){if(t.local)return(0,d.isFolder)(t.path)?this.autoMergeFolder(t):this.autoMergeDocument(t);if((0,d.isFolder)(t.path))void 0!==t.remote.itemsMap&&(t.common=t.remote,delete t.remote);else if(void 0!==t.remote.body){const e={origin:"remote",path:t.path,oldValue:!1===t.common.body?void 0:t.common.body,newValue:!1===t.remote.body?void 0:t.remote.body,oldContentType:t.common.contentType,newContentType:t.remote.contentType};if(void 0===e.oldValue&&void 0===e.newValue||this.rs.local.emitChange(e),!1===t.remote.body)return;t.common=t.remote,delete t.remote}return t}t.common.body&&this.rs.local.emitChange({origin:"remote",path:t.path,oldValue:t.common.body,newValue:void 0,oldContentType:t.common.contentType,newContentType:void 0})}updateCommonTimestamp(t,e){return r(this,void 0,void 0,function*(){return this.rs.local.getNodes([t]).then(n=>(n[t]&&n[t].common&&n[t].common.revision===e&&(n[t].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(n))))})}markChildren(t,e,n,i){return r(this,void 0,void 0,function*(){const r=[],s={},o={};for(const n in e)r.push(t+n),s[t+n]=e[n];for(const e in i)r.push(t+e);const a=yield this.rs.local.getNodes(r);let l,c;for(const e in a)if(c=a[e],s[e])c&&c.common?m(c,s[e].ETag)&&(n[e]=(0,d.deepClone)(c),n[e].remote={revision:s[e].ETag,timestamp:this.now()},n[e]=this.autoMerge(n[e])):(l=this.rs.caching.checkPath(e),"ALL"===l&&(n[e]={path:e,common:{timestamp:this.now()},remote:{revision:s[e].ETag,timestamp:this.now()}})),n[e]&&s[e]["Content-Type"]&&(n[e].remote.contentType=s[e]["Content-Type"]),n[e]&&s[e]["Content-Length"]&&(n[e].remote.contentLength=s[e]["Content-Length"]);else if(i[e.substring(t.length)]&&c&&c.common){if(c.common.itemsMap)for(const t in c.common.itemsMap)o[e+t]=!0;if(c.local&&c.local.itemsMap)for(const t in c.local.itemsMap)o[e+t]=!0;if(c.remote||(0,d.isFolder)(e))n[e]=void 0;else if(n[e]=this.autoMerge(c),void 0===n[e]){const r=this.getParentPath(e),i=n[r],s=e.substring(t.length);i&&i.local&&(delete i.local.itemsMap[s],(0,d.equal)(i.local.itemsMap,i.common.itemsMap)&&delete i.local)}}const u=yield this.markRemoteDeletions(Object.keys(o),n);u&&(yield this.rs.local.setNodes(this.flush(u)))})}markRemoteDeletions(t,e){return r(this,void 0,void 0,function*(){if(0===t.length)return e;const n=yield this.rs.local.getNodes(t),r={};function i(t,e){if(t&&t.itemsMap)for(const n in t.itemsMap)r[e+n]=!0}for(const t in n){const r=n[t];r&&((0,d.isFolder)(t)?(i(r.common,t),i(r.local,t)):r.common&&void 0!==r.common.body&&(e[t]=(0,d.deepClone)(r),e[t].remote={body:!1,timestamp:this.now()},e[t]=this.autoMerge(e[t])))}const s=yield this.markRemoteDeletions(Object.keys(r),e);s&&(yield this.rs.local.setNodes(this.flush(s)))})}completeFetch(t,e,n,i){return r(this,void 0,void 0,function*(){let r,s;const o=(0,d.pathsFromRoot)(t);(0,d.isFolder)(t)?r=[t]:(s=o[1],r=[t,s]);const a=yield this.rs.local.getNodes(r),l=a[s],c={};let u,h=a[t];function p(t){if(t&&t.itemsMap)for(u in t.itemsMap)e[u]||(c[u]=!0)}if("object"==typeof h&&h.path===t&&"object"==typeof h.common||(h={path:t,common:{}},a[t]=h),h.remote={revision:i,timestamp:this.now()},(0,d.isFolder)(t))for(u in p(h.common),p(h.remote),h.remote.itemsMap={},e)h.remote.itemsMap[u]=!0;else h.remote.body=e,h.remote.contentType=n,l&&l.local&&l.local.itemsMap&&(u=t.substring(s.length),!1!==e?l.local.itemsMap[u]=!0:l.local.itemsMap[u]&&delete l.local.itemsMap[u],(0,d.equal)(l.local.itemsMap,l.common.itemsMap)&&delete l.local);return a[t]=this.autoMerge(h),{toBeSaved:a,missingChildren:c}})}completePush(t,e,n,i){return r(this,void 0,void 0,function*(){const r=yield this.rs.local.getNodes([t]),s=r[t];if(!s.push)throw this.stopped=!0,new Error("completePush called but no push version!");n?((0,l.default)("[Sync] We have a conflict"),s.remote&&s.remote.revision===i||(s.remote={revision:i||"conflict",timestamp:this.now()},delete s.push),r[t]=this.autoMerge(s)):(s.common={revision:i,timestamp:this.now()},"put"===e?(s.common.body=s.push.body,s.common.contentType=s.push.contentType,(0,d.equal)(s.local.body,s.push.body)&&s.local.contentType===s.push.contentType&&delete s.local,delete s.push):"delete"===e&&(!1===s.local.body?r[t]=void 0:delete s.push)),yield this.rs.local.setNodes(this.flush(r))})}dealWithFailure(t){return r(this,void 0,void 0,function*(){const e=yield this.rs.local.getNodes([t]);if(e[t])return delete e[t].push,this.rs.local.setNodes(this.flush(e))})}interpretStatus(t){const e={statusCode:t,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof t&&("offline"===t||"timeout"===t))return e.successful=!1,e.networkProblems=!0,e;if("number"==typeof t){const n=Math.floor(t/100);return e.successful=2===n||304===t||412===t||404===t,e.conflict=412===t,e.unAuth=401===t&&this.rs.remote.token!==c.default.IMPLIED_FAKE_TOKEN||402===t||403===t,e.notFound=404===t,e.changed=304!==t,e}}handleGetResponse(t,e,n,i,s){return r(this,void 0,void 0,function*(){if(e.notFound&&(n=!!(0,d.isFolder)(t)&&{}),e.changed){const e=yield this.completeFetch(t,n,i,s);if((0,d.isFolder)(t)){if(this.corruptServerItemsMap(n))return(0,l.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+t),!1;yield this.markChildren(t,n,e.toBeSaved,e.missingChildren)}else yield this.rs.local.setNodes(this.flush(e.toBeSaved))}else yield this.updateCommonTimestamp(t,s);return!0})}handleResponse(t,e,n){return r(this,void 0,void 0,function*(){const r=this.interpretStatus(n.statusCode);if(r.successful){if("get"===e)return this.handleGetResponse(t,r,n.body,n.contentType,n.revision);if("put"===e||"delete"===e)return this.completePush(t,e,r.conflict,n.revision).then(function(){return!0});throw new Error(`cannot handle response for unknown action ${e}`)}{let e;return e=r.unAuth?new h.default:r.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+r.statusCode+" received."),this.dealWithFailure(t).then(()=>{throw this.rs._emit("error",e),e})}})}finishTask(t){return r(this,arguments,void 0,function*(t,e=!0){if(void 0===t.action)return void delete this._running[t.path];if(e&&((0,l.default)("[Sync] queue finished task:",t.path),this._finishedTasks.push(t),this._finishedTasks.length>1))return void(0,l.default)("[Sync] delaying finished task:",t.path);let n;(0,l.default)("[Sync] run task:",t.path);try{n=yield t.promise}catch(e){(0,l.default)("[Sync] wire client rejects its promise",t.path,t.action,e),n={statusCode:"offline"}}try{const e=yield this.handleResponse(t.path,t.action,n);this.finishSuccessfulTask(t,e)}catch(e){this.finishUnsuccessfulTask(t,e)}})}finishSuccessfulTask(t,e){return r(this,void 0,void 0,function*(){if(this._finishedTasks.shift(),delete this._timeStarted[t.path],delete this._running[t.path],e&&this._tasks[t.path]){for(let e=0;e0?yield this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then(()=>{!this.hasTasks()||this.stopped?(this.done||(this.done=!0),this.rs._emit("sync-done",{completed:!0})):setTimeout(()=>{this.doTasks()},10)})})}finishUnsuccessfulTask(t,e){return r(this,void 0,void 0,function*(){(0,l.default)("[Sync]",e.message),this._finishedTasks.shift(),delete this._timeStarted[t.path],delete this._running[t.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?yield this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))})}tasksWanted(){return this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0}doTasks(){const t=this.tasksWanted()-Object.keys(this._running).length;if(t<=0)return!0;this.hasTasks()&&!this.done&&this.rs._emit("sync-started");let e,n=0;for(e in this._tasks)if(!this._running[e]&&(this._timeStarted[e]=this.now(),this._running[e]=this.doTask(e).then(this.finishTask.bind(this)),n++,n>=t))break;return n>=t}collectTasks(){return r(this,arguments,void 0,function*(t=!0){if(!this.hasTasks()&&!this.stopped)return(yield this.collectDiffTasks())>0?void 0:t?this.collectRefreshTasks():void 0})}addTask(t,e){this._tasks[t]||(this._tasks[t]=[]),"function"==typeof e&&this._tasks[t].push(e)}sync(){return r(this,void 0,void 0,function*(){if(this.done=!1,!this.doTasks()){try{yield this.collectTasks()}catch(t){throw(0,l.default)("[Sync] Sync error",t),new Error("Local cache unavailable")}this.doTasks()}})}static _rs_init(t){p=function(){const e=new o.default;e.isBrowser()&&function(t,e){function n(t){const n=e.getCurrentSyncInterval();s.default.isBackground=!t;const r=e.getCurrentSyncInterval();e._emit("sync-interval-change",{oldValue:n,newValue:r})}t.on("background",()=>n(!1)),t.on("foreground",()=>n(!0))}(e,t),t.sync||(t.sync=new v(t),t.syncStopped&&((0,l.default)("[Sync] Initializing with sync stopped"),t.sync.stopped=!0,delete t.syncStopped)),t.setupSyncCycle()},f=function(){t.removeEventListener("connected",f),t.startSync()},t.on("ready",p),t.on("connected",f)}static _rs_cleanup(t){t.stopSync(),t.removeEventListener("ready",p),t.removeEventListener("connected",f),t.sync=void 0,delete t.sync}}e.Sync=v,(0,d.applyMixins)(v,[a.default]),e.default=v},370:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})};const i=(this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}})(n(334));function s(t){return"dropbox"===this.backend&&!!t.match(/^\/public\/.*[^\/]$/)}const o={get:function(t,e){if(this.local){if(void 0===e)e="object"==typeof(n=this).remote&&n.remote.connected&&n.remote.online?2*n.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof e&&!1!==e)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(t,e,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(t);var n},put:function(t,e,n){return s.bind(this)(t)?o._wrapBusyDone.call(this,this.remote.put(t,e,n)):this.local?this.local.put(t,e,n):o._wrapBusyDone.call(this,this.remote.put(t,e,n))},delete:function(t,e){return this.local?this.local.delete(t,e):o._wrapBusyDone.call(this,this.remote.delete(t,e))},_wrapBusyDone:function(t){return r(this,void 0,void 0,function*(){return this._emit("wire-busy"),t.then(t=>(this._emit("wire-done",{success:!0}),Promise.resolve(t)),t=>(this._emit("wire-done",{success:!1}),Promise.reject(t)))})}};t.exports=o},613:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseClientTypes=void 0;class n{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(t,e,n,r){const i=t+"/"+e;if(r.extends){const e=r.extends.split("/"),n=1===e.length?t+"/"+e.shift():e.join("/"),s=this.uris[n];if(!s)throw"Type '"+i+"' tries to extend unknown schema '"+n+"'";r.extends=this.schemas[s]}this.uris[i]=n,this.aliases[n]=i,this.schemas[n]=r}resolveAlias(t){return this.uris[t]}getSchema(t){return this.schemas[t]}inScope(t){const e=t.length,n={};for(const r in this.uris)if(r.substr(0,e+1)===t+"/"){const t=this.uris[r];n[t]=this.schemas[t]}return n}}e.BaseClientTypes=n;const r=new n;e.default=r},503:function(t){class e extends Error{constructor(t,e={}){super(),this.name="Unauthorized",this.message=void 0===t?"App authorization expired or revoked.":t,void 0!==e.code&&(this.code=e.code),this.stack=(new Error).stack}}t.exports=e},746:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})};function i(t,e){if("object"==typeof t&&!Array.isArray(t)&&null!==t)for(const n in t)if("object"==typeof t[n]&&null!==t[n])if("[object ArrayBuffer]"===t[n].toString()){e[n]=new ArrayBuffer(t[n].byteLength);const r=new Int8Array(t[n]);new Int8Array(e[n]).set(r)}else i(t[n],e[n])}Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=e.getTextFromArrayBuffer=e.shouldBeTreatedAsBinary=e.getJSONFromLocalStorage=e.localStorageAvailable=e.pathsFromRoot=e.deepClone=e.equal=e.bindAll=e.cleanPath=e.baseName=e.isDocument=e.isFolder=e.containingFolder=e.extend=e.getGlobalContext=e.globalContext=e.logError=void 0,e.generateCodeVerifier=function(){return r(this,arguments,void 0,function*(t=128){const e=new Uint8Array(t);crypto.getRandomValues(e);const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=Array.from(e).map(t=>n[t%66]),i=r.join(""),s=Uint8Array.from(r.map(t=>t.charCodeAt(0))),o=(a=yield crypto.subtle.digest("SHA-256",s),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(e),{codeVerifier:i,codeChallenge:o,state:Array.from(e).map(t=>n[t%66]).join("")}})},e.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(n=>{Object.defineProperty(t.prototype,n,Object.getOwnPropertyDescriptor(e.prototype,n))})})},e.logError=t=>{"string"==typeof t?console.error(t):console.error(t.message,t.stack)},e.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:n.g,e.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:n.g,e.extend=(...t)=>{const e=t[0];return Array.prototype.slice.call(t,1).forEach(function(t){for(const n in t)e[n]=t[n]}),e},e.containingFolder=t=>{if(""===t)return"/";if(!t)throw"Path not given!";return t.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},e.isFolder=t=>"/"===t.slice(-1),e.isDocument=t=>!(0,e.isFolder)(t),e.baseName=t=>{const n=t.split("/");return(0,e.isFolder)(t)?n[n.length-2]+"/":n[n.length-1]},e.cleanPath=t=>t.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),e.bindAll=t=>{for(const e in this)"function"==typeof t[e]&&(t[e]=t[e].bind(t))},e.equal=(t,n,r=[])=>{let i;if(typeof t!=typeof n)return!1;if("number"==typeof t||"boolean"==typeof t||"string"==typeof t)return t===n;if("function"==typeof t)return t.toString()===n.toString();if(t instanceof ArrayBuffer&&n instanceof ArrayBuffer&&(t=new Uint8Array(t),n=new Uint8Array(n)),t instanceof Array){if(t.length!==n.length)return!1;for(let i=0,s=t.length;i=0)continue;s=r.slice(),s.push(n[i])}if(!(0,e.equal)(t[i],n[i],s))return!1}}return!0},e.deepClone=t=>{if(void 0!==t){const e=JSON.parse(JSON.stringify(t));return i(t,e),e}},e.pathsFromRoot=t=>{const e=[t],n=t.replace(/\/$/,"").split("/");for(;n.length>1;)n.pop(),e.push(n.join("/")+"/");return e},e.localStorageAvailable=()=>{const t=(0,e.getGlobalContext)();if(!("localStorage"in t))return!1;try{return t.localStorage.setItem("rs-check","1"),t.localStorage.removeItem("rs-check"),!0}catch(t){return!1}},e.getJSONFromLocalStorage=t=>{const n=(0,e.getGlobalContext)();try{return JSON.parse(n.localStorage.getItem(t))}catch(t){}},e.shouldBeTreatedAsBinary=(t,e)=>!!(e&&e.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(t)),e.getTextFromArrayBuffer=(t,n)=>new Promise(r=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const e=Buffer.from(t);r(e.toString(n))}else{let i;const s=e.globalContext;if(s.BlobBuilder=s.BlobBuilder||s.WebKitBlobBuilder,void 0!==s.BlobBuilder){const e=new s.BlobBuilder;e.append(t),i=e.getBlob()}else i=new Blob([t]);const o=new FileReader;"function"==typeof o.addEventListener?o.addEventListener("loadend",function(t){r(t.target.result)}):o.onloadend=function(t){r(t.target.result)},o.readAsText(i,n)}}),e.toBase64=t=>{const n=(0,e.getGlobalContext)();return"btoa"in n?n.btoa(t):Buffer.from(t).toString("base64")}},600:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(275)),o=i(n(93)),a=i(n(503)),l=i(n(334)),c=n(746),u=n(368),h=n(684);let d;const p="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends h.RemoteBase{constructor(t){if(super(t),this._revisionCache={},d=(0,c.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),d){const t=function(){const t=(0,c.getJSONFromLocalStorage)(p)||{},{userAddress:e,href:n,storageApi:r,token:i,properties:s}=t;return{userAddress:e,href:n,storageApi:r,token:i,properties:s}}();t&&setTimeout(()=>{this.configure(t)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const t=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return t?t[1]:"2012.04"}}_request(t,e,n,i,o,h,d){return r(this,void 0,void 0,function*(){if(this.isForbiddenRequestMethod(t,e))return Promise.reject(`Don't use ${t} on directories!`);let r;return n!==s.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+n),this.rs._emit("wire-busy",{method:t,isFolder:(0,c.isFolder)(e)}),(0,u.requestWithTimeout)(t,e,{body:o,headers:i,responseType:"arraybuffer"}).then(n=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,c.isFolder)(e),success:!0}),i=n.status,[401,403,404,412].indexOf(i)>=0)return(0,l.default)("[WireClient] Error response status",n.status),r=h?this.stripQuotes(n.getResponseHeader("ETag")):void 0,401===n.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:n.status,revision:r});if(function(t){return[201,204,304].indexOf(t)>=0}(n.status)||200===n.status&&"GET"!==t)return r=this.stripQuotes(n.getResponseHeader("ETag")),(0,l.default)("[WireClient] Successful request",r),Promise.resolve({statusCode:n.status,revision:r});{const t=n.getResponseHeader("Content-Type");r=h?this.stripQuotes(n.getResponseHeader("ETag")):200===n.status?d:void 0;const e=function(t){let e,n="utf-8";return t&&(e=t.match(/charset=(.+)$/),e&&(n=e[1])),n}(t);return(0,c.shouldBeTreatedAsBinary)(n.response,t)?((0,l.default)("[WireClient] Successful request with unknown or binary mime-type",r),Promise.resolve({statusCode:n.status,body:n.response,contentType:t,revision:r})):(0,c.getTextFromArrayBuffer)(n.response,e).then(e=>((0,l.default)("[WireClient] Successful request",r),Promise.resolve({statusCode:n.status,body:e,contentType:t,revision:r})))}var i},n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,c.isFolder)(e),success:!1}),Promise.reject(n)))})}configure(t){if("object"!=typeof t)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.href&&(this.href=t.href),void 0!==t.storageApi&&(this.storageApi=t.storageApi),void 0!==t.token&&(this.token=t.token),void 0!==t.properties&&(this.properties=t.properties),"string"==typeof this.storageApi){const t=f[this.storageApi]||5;this.supportsRevs=t>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,d&&localStorage.setItem(p,JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(t,e={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");const n={};return this.supportsRevs&&e.ifNoneMatch&&(n["If-None-Match"]=this.addQuotes(e.ifNoneMatch)),this._request("GET",this.href+(0,c.cleanPath)(t),this.token,n,void 0,this.supportsRevs,this._revisionCache[t]).then(e=>{if(!(0,c.isFolder)(t))return Promise.resolve(e);let n={};if(void 0!==e.body)try{e.body=JSON.parse(e.body)}catch(e){return Promise.reject("Folder description at "+this.href+(0,c.cleanPath)(t)+" is not JSON")}if(200===e.statusCode&&"object"==typeof e.body){if(0===Object.keys(e.body).length)e.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(r=e.body)["@context"]&&"object"==typeof r.items){for(const n in e.body.items)this._revisionCache[t+n]=e.body.items[n].ETag;n=e.body.items}else Object.keys(e.body).forEach(r=>{this._revisionCache[t+r]=e.body[r],n[r]={ETag:e.body[r]}});return e.body=n,Promise.resolve(e)}return Promise.resolve(e);var r})}put(t,e,n,r={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");!n.match(/charset=/)&&(e instanceof ArrayBuffer||(0,u.isArrayBufferView)(e))&&(n+="; charset=binary");const i={"Content-Type":n};return this.supportsRevs&&(r.ifMatch&&(i["If-Match"]=this.addQuotes(r.ifMatch)),r.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(r.ifNoneMatch))),this._request("PUT",this.href+(0,c.cleanPath)(t),this.token,i,e,this.supportsRevs)}delete(t,e={}){if(!this.connected)throw new Error("not connected (path: "+t+")");e||(e={});const n={};return this.supportsRevs&&e.ifMatch&&(n["If-Match"]=this.addQuotes(e.ifMatch)),this._request("DELETE",this.href+(0,c.cleanPath)(t),this.token,n,void 0,this.supportsRevs)}static _rs_init(t){t.remote=new g(t),t.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){d&&delete localStorage[p]}}(0,c.applyMixins)(g,[o.default]),t.exports=g},439:function(t,e){var n,r;n=function(){var t,e,n,r;Object.keys||(Object.keys=(t=Object.prototype.hasOwnProperty,e=!{toString:null}.propertyIsEnumerable("toString"),r=(n=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var s=[];for(var o in i)t.call(i,o)&&s.push(o);if(e)for(var a=0;a>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&((r=Number(arguments[1]))!=r?r=0:0!==r&&r!==1/0&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);i0&&(e+=u.suffices["*"]&&n||",",u.suffices["*"]&&l&&(e+=u.name+"=")),e+=a?encodeURIComponent(h[p]).replace(/!/g,"%21"):o(h[p])}else if("object"==typeof h){l&&!u.suffices["*"]&&(e+=u.name+"=");var f=!0;for(var g in h)f||(e+=u.suffices["*"]&&n||","),f=!1,e+=a?encodeURIComponent(g).replace(/!/g,"%21"):o(g),e+=u.suffices["*"]?"=":",",e+=a?encodeURIComponent(h[g]).replace(/!/g,"%21"):o(h[g])}else l&&(e+=u.name,c&&""===h||(e+="=")),null!=u.truncate&&(h=h.substring(0,u.truncate)),e+=a?encodeURIComponent(h).replace(/!/g,"%21"):o(h)}return e};return w.varNames=u,{prefix:r,substitution:w}}function l(t){if(!(this instanceof l))return new l(t);for(var e=t.split("{"),n=[e.shift()],r=[],i=[],s=[];e.length>0;){var o=e.shift(),c=o.split("}")[0],u=o.substring(c.length+1),h=a(c);i.push(h.substitution),r.push(h.prefix),n.push(u),s=s.concat(h.substitution.varNames)}this.fill=function(t){for(var e=n[0],r=0;r0&&"/"===e.charAt(t.length-1)||"#"===n.charAt(0)||"?"===n.charAt(0))return!0}return!1}(e,t.id)&&void 0===this.schemas[t.id]&&(this.schemas[t.id]=t),t)if("enum"!==r)if("object"==typeof t[r])this.searchSchemas(t[r],e);else if("$ref"===r){var i=g(t[r]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},c.prototype.addSchema=function(t,e){if("string"!=typeof t||void 0===e){if("object"!=typeof t||"string"!=typeof t.id)return;t=(e=t).id}t===g(t)+"#"&&(t=g(t)),this.schemas[t]=e,delete this.missingMap[t],m(e,t),this.searchSchemas(e,t)},c.prototype.getSchemaMap=function(){var t={};for(var e in this.schemas)t[e]=this.schemas[e];return t},c.prototype.getSchemaUris=function(t){var e=[];for(var n in this.schemas)t&&!t.test(n)||e.push(n);return e},c.prototype.getMissingUris=function(t){var e=[];for(var n in this.missingMap)t&&!t.test(n)||e.push(n);return e},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(t,e,n,r,i){var s;if(!(e=this.resolveRefs(e)))return null;if(e instanceof x)return this.errors.push(e),e;var o,a=this.errors.length,l=null,c=null;if(this.checkRecursive&&t&&"object"==typeof t){if(s=!this.scanned.length,t[this.validatedSchemasKey]){var u=t[this.validatedSchemasKey].indexOf(e);if(-1!==u)return this.errors=this.errors.concat(t[this.validationErrorsKey][u]),null}if(Object.isFrozen(t)&&-1!==(o=this.scannedFrozen.indexOf(t))){var h=this.scannedFrozenSchemas[o].indexOf(e);if(-1!==h)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[o][h]),null}if(this.scanned.push(t),Object.isFrozen(t))-1===o&&(o=this.scannedFrozen.length,this.scannedFrozen.push(t),this.scannedFrozenSchemas.push([])),l=this.scannedFrozenSchemas[o].length,this.scannedFrozenSchemas[o][l]=e,this.scannedFrozenValidationErrors[o][l]=[];else{if(!t[this.validatedSchemasKey])try{Object.defineProperty(t,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(t,this.validationErrorsKey,{value:[],configurable:!0})}catch(e){t[this.validatedSchemasKey]=[],t[this.validationErrorsKey]=[]}c=t[this.validatedSchemasKey].length,t[this.validatedSchemasKey][c]=e,t[this.validationErrorsKey][c]=[]}}var d=this.errors.length,p=this.validateBasic(t,e,i)||this.validateNumeric(t,e,i)||this.validateString(t,e,i)||this.validateArray(t,e,i)||this.validateObject(t,e,i)||this.validateCombinations(t,e,i)||this.validateHypermedia(t,e,i)||this.validateFormat(t,e,i)||this.validateDefinedKeywords(t,e,i)||null;if(s){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(p||d!==this.errors.length)for(;n&&n.length||r&&r.length;){var f=n&&n.length?""+n.pop():null,g=r&&r.length?""+r.pop():null;p&&(p=p.prefixWith(f,g)),this.prefixErrors(d,f,g)}return null!==l?this.scannedFrozenValidationErrors[o][l]=this.errors.slice(a):null!==c&&(t[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(p)},c.prototype.validateFormat=function(t,e){if("string"!=typeof e.format||!this.formatValidators[e.format])return null;var n=this.formatValidators[e.format].call(null,t,e);return"string"==typeof n||"number"==typeof n?this.createError(v.FORMAT_CUSTOM,{message:n},"","/format",null,t,e):n&&"object"==typeof n?this.createError(v.FORMAT_CUSTOM,{message:n.message||"?"},n.dataPath||"",n.schemaPath||"/format",null,t,e):null},c.prototype.validateDefinedKeywords=function(t,e,n){for(var r in this.definedKeywords)if(void 0!==e[r])for(var i=this.definedKeywords[r],s=0;s=h&&re.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:t,maximum:e.maximum},"","/maximum",null,t,e);if(e.exclusiveMaximum&&t===e.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:t,maximum:e.maximum},"","/exclusiveMaximum",null,t,e)}return null},c.prototype.validateNaN=function(t,e){return"number"!=typeof t?null:!0===isNaN(t)||t===1/0||t===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:t},"","/type",null,t,e):null},c.prototype.validateString=function(t,e,n){return this.validateStringLength(t,e,n)||this.validateStringPattern(t,e,n)||null},c.prototype.validateStringLength=function(t,e){return"string"!=typeof t?null:void 0!==e.minLength&&t.lengthe.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:t.length,maximum:e.maxLength},"","/maxLength",null,t,e):null},c.prototype.validateStringPattern=function(t,e){if("string"!=typeof t||"string"!=typeof e.pattern&&!(e.pattern instanceof RegExp))return null;var n;if(e.pattern instanceof RegExp)n=e.pattern;else{var r,i="",s=e.pattern.match(/^\/(.+)\/([img]*)$/);s?(r=s[1],i=s[2]):r=e.pattern,n=new RegExp(r,i)}return n.test(t)?null:this.createError(v.STRING_PATTERN,{pattern:e.pattern},"","/pattern",null,t,e)},c.prototype.validateArray=function(t,e,n){return Array.isArray(t)&&(this.validateArrayLength(t,e,n)||this.validateArrayUniqueItems(t,e,n)||this.validateArrayItems(t,e,n))||null},c.prototype.validateArrayLength=function(t,e){var n;return void 0!==e.minItems&&t.lengthe.maxItems&&(n=this.createError(v.ARRAY_LENGTH_LONG,{length:t.length,maximum:e.maxItems},"","/maxItems",null,t,e),this.handleError(n))?n:null},c.prototype.validateArrayUniqueItems=function(t,e){if(e.uniqueItems)for(var n=0;ne.maxProperties&&(n=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:r.length,maximum:e.maxProperties},"","/maxProperties",null,t,e),this.handleError(n))?n:null},c.prototype.validateObjectRequiredProperties=function(t,e){if(void 0!==e.required)for(var n=0;n 10000");if(void 0!==v[t])throw new Error("Error already defined: "+t+" as "+v[t]);if(void 0!==b[e])throw new Error("Error code already used: "+b[e]+" as "+e);for(var r in v[t]=e,b[e]=t,_[t]=_[e]=n,C){var i=C[r];i[t]&&(i[e]=i[e]||i[t])}},reset:function(){r.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:m,resolveUrl:f,getDocumentUri:g,errorCodes:v};return i.language("en"),i}();return S.addLanguage("en-gb",_),S.tv4=S,S},void 0===(r=n.apply(e,[]))||(t.exports=r)},199:function(t,e,n){var r;"function"!=typeof fetch&&"function"!=typeof XMLHttpRequest&&(XMLHttpRequest=n(317)),function(){var n={"http://webfist.org/spec/rel":"webfist","http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},i={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},s=["webfinger","host-meta","host-meta.json"];function o(t){return t.toString=function(){return this.message},t}function a(t){"object"!=typeof t&&(t={}),this.config={tls_only:void 0===t.tls_only||t.tls_only,webfist_fallback:void 0!==t.webfist_fallback&&t.webfist_fallback,uri_fallback:void 0!==t.uri_fallback&&t.uri_fallback,request_timeout:void 0!==t.request_timeout?t.request_timeout:1e4}}a.prototype.__fetchJRD=function(t,e,n){if("function"==typeof fetch)return this.__fetchJRD_fetch(t,e,n);if("function"==typeof XMLHttpRequest)return this.__fetchJRD_XHR(t,e,n);throw new Error("add a polyfill for fetch or XMLHttpRequest")},a.prototype.__fetchJRD_fetch=function(t,e,n){var r,i=this;"function"==typeof AbortController&&(r=new AbortController);var s=fetch(t,{headers:{Accept:"application/jrd+json, application/json"},signal:r?r.signal:void 0}).then(function(e){if(e.ok)return e.text();throw 404===e.status?o({message:"resource not found",url:t,status:e.status}):o({message:"error during request",url:t,status:e.status})},function(e){throw o({message:"error during request",url:t,status:void 0,err:e})}).then(function(e){if(i.__isValidJSON(e))return e;throw o({message:"invalid json",url:t,status:void 0})}),a=new Promise(function(e,n){setTimeout(function(){n(o({message:"request timed out",url:t,status:void 0})),r&&r.abort()},i.config.request_timeout)});Promise.race([s,a]).then(function(t){n(t)}).catch(function(t){e(t)})},a.prototype.__fetchJRD_XHR=function(t,e,n){var r=this,i=!1,s=new XMLHttpRequest;function a(){if(!i)return i=!0,200===s.status?r.__isValidJSON(s.responseText)?n(s.responseText):e(o({message:"invalid json",url:t,status:s.status})):404===s.status?e(o({message:"resource not found",url:t,status:s.status})):s.status>=301&&s.status<=302?function(t){return"string"==typeof t&&"https"===t.split("://")[0]}(s.getResponseHeader("Location"))?l():e(o({message:"no redirect URL found",url:t,status:s.status})):e(o({message:"error during request",url:t,status:s.status}))}function l(){s.onreadystatechange=function(){4===s.readyState&&a()},s.onload=function(){a()},s.ontimeout=function(){return e(o({message:"request timed out",url:t,status:s.status}))},s.open("GET",t,!0),s.timeout=r.config.request_timeout,s.setRequestHeader("Accept","application/jrd+json, application/json"),s.send()}return l()},a.prototype.__isValidJSON=function(t){try{JSON.parse(t)}catch(t){return!1}return!0},a.prototype.__isLocalhost=function(t){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(t)},a.prototype.__processJRD=function(t,e,r,s){var a=JSON.parse(e);if("object"!=typeof a||"object"!=typeof a.links)return void 0!==a.error?r(o({message:a.error,request:t})):r(o({message:"unknown response from server",request:t}));var l=a.links;Array.isArray(l)||(l=[]);var c={object:a,json:e,idx:{}};c.idx.properties={name:void 0},c.idx.links=JSON.parse(JSON.stringify(i)),l.map(function(t){if(n.hasOwnProperty(t.rel)&&c.idx.links[n[t.rel]]){var e={};Object.keys(t).map(function(n){e[n]=t[n]}),c.idx.links[n[t.rel]].push(e)}});var u=JSON.parse(e).properties;for(var h in u)u.hasOwnProperty(h)&&"http://packetizer.com/ns/name"===h&&(c.idx.properties.name=u[h]);return s(c)},a.prototype.lookup=function(t,e){if("string"!=typeof t)throw new Error("first parameter must be a user address");if("function"!=typeof e)throw new Error("second parameter must be a callback");var n=this,r="";r=t.indexOf("://")>-1?t.replace(/ /g,"").split("/")[2]:t.replace(/ /g,"").split("@")[1];var i=0,o="https";function a(){var e="";return t.split("://")[1]||(e="acct:"),o+"://"+r+"/.well-known/"+s[i]+"?resource="+e+t}function l(t){if(n.config.uri_fallback&&"webfist.org"!==r&&i!==s.length-1)return i+=1,c();if(!n.config.tls_only&&"https"===o)return i=0,o="http",c();if(!n.config.webfist_fallback||"webfist.org"===r)return e(t);i=0,o="http",r="webfist.org";var l=a();n.__fetchJRD(l,e,function(t){n.__processJRD(l,t,e,function(t){"object"==typeof t.idx.links.webfist&&"string"==typeof t.idx.links.webfist[0].href&&n.__fetchJRD(t.idx.links.webfist[0].href,e,function(t){n.__processJRD(l,t,e,function(){return e(null,e)})})})})}function c(){var t=a();n.__fetchJRD(t,l,function(r){n.__processJRD(t,r,e,function(t){e(null,t)})})}return n.__isLocalhost(r)&&(o="http"),setTimeout(c,0)},a.prototype.lookupLink=function(t,e,n){if(!i.hasOwnProperty(e))return n("unsupported rel "+e);this.lookup(t,function(t,r){var i=r.idx.links[e];return t?n(t):0===i.length?n('no links found with rel="'+e+'"'):n(null,i[0])})},void 0===(r=function(){return a}.apply(e,[]))||(t.exports=r)}()},317:function(t){t.exports=XMLHttpRequest}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var s=e[r]={exports:{}};return t[r].call(s.exports,s,s.exports,n),s.exports}return n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n(423).default}()),qN.exports); -/*! For license information please see remotestorage.js.LICENSE.txt */const WN=BA(VN),HN="0123456789ABCDEFGHJKMNPQRSTVWXYZ",GN=0xffffffffffff;var KN;!function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"}(KN||(KN={}));class ZN extends Error{constructor(t,e){super(`${e} (${t})`),this.name="ULIDError",this.code=t}}function YN(t){const e=Math.floor(32*t())%32;return HN.charAt(e)}const XN={type:"object",properties:{id:{type:"string"},title:{type:"string"},lat:{type:"number"},lon:{type:"number"},geohash:{type:"string"},zoom:{type:"number"},url:{type:"string"},osmId:{type:"string"},osmType:{type:"string"},osmTags:{type:"object",additionalProperties:{type:"string"}},description:{type:"string"},tags:{type:"array",items:{type:"string"},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","lat","lon","geohash","createdAt"]},JN={type:"object",properties:{id:{type:"string"},title:{type:"string"},color:{type:"string"},placeRefs:{type:"array",items:{type:"object",properties:{id:{type:"string"},geohash:{type:"string"}},required:["id","geohash"]},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","placeRefs","createdAt"]},QN={name:"places",builder:function(t){function e(t,e){return`${t.substring(0,2)}/${t.substring(2,4)}/${e}`}t.declareType("place",XN),t.declareType("list",JN);const n={async getAll(){const e=await t.getAll("_lists/");return e?Object.values(e):[]},async get(e){const n=`_lists/${e}`;return t.getObject(n)},async create(e,n,r){const i=`_lists/${e}`;let s=await t.getObject(i);const o=(new Date).toISOString();return s?(s.title=n,r&&(s.color=r),s.updatedAt=o):s={id:e,title:n,color:r,placeRefs:[],createdAt:o,updatedAt:o},await t.storeObject("list",i,s),s},async delete(e){await t.remove(`_lists/${e}`)},async addPlace(e,n,r){const i=`_lists/${e}`,s=await t.getObject(i);if(!s)throw new Error(`List not found: ${e}`);return-1===s.placeRefs.findIndex(t=>t.id===n)&&(s.placeRefs.push({id:n,geohash:r}),s.updatedAt=(new Date).toISOString(),await t.storeObject("list",i,s)),s},async removePlace(e,n){const r=`_lists/${e}`,i=await t.getObject(r);if(!i)throw new Error(`List not found: ${e}`);const s=i.placeRefs.findIndex(t=>t.id===n);return-1!==s&&(i.placeRefs.splice(s,1),i.updatedAt=(new Date).toISOString(),await t.storeObject("list",r,i)),i},async initDefaults(){const t=[{id:"to-go",title:"Want to go",color:"#2e9e4f"},{id:"to-do",title:"To do",color:"#2a7fff"}];for(const e of t)await this.get(e.id)||await this.create(e.id,e.title,e.color)}},r={lists:n,store:async function(n){const r=function(t){const e=(new Date).toISOString(),n=t.id||function(){const t=function(){const t="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:null,e=t&&(t.crypto||t.msCrypto)||null;if("function"==typeof e?.getRandomValues)return()=>{const t=new Uint8Array(1);return e.getRandomValues(t),t[0]/256};if("function"==typeof e?.randomBytes)return()=>e.randomBytes(1).readUInt8()/256;throw new ZN(KN.PRNGDetectFailure,"Failed to find a reliable PRNG")}();return function(t,e=10){if(isNaN(t))throw new ZN(KN.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>GN)throw new ZN(KN.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${GN}: ${t}`);if(t<0)throw new ZN(KN.EncodeTimeNegative,`Time must be positive: ${t}`);if(!1===Number.isInteger(t))throw new ZN(KN.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let i=e;i>0;i--)n=t%32,r=HN.charAt(n)+r,t=(t-n)/32;return r}(Date.now(),10)+function(t,e){let n="";for(;t>0;t--)n=YN(e)+n;return n}(16,t)}(),r="number"==typeof t.lat?t.lat:0,i="number"==typeof t.lon?t.lon:0,s=t.title||"Untitled Place",o=t.geohash||DD.encode(r,i,10),a={...t,id:n,lat:r,lon:i,geohash:o,title:s,tags:t.tags||[],createdAt:t.createdAt||e,updatedAt:t.id?e:void 0};return Object.keys(a).forEach(t=>{void 0===a[t]&&delete a[t]}),a}(n),i=e(r.geohash,r.id);return await t.storeObject("place",i,r),r},remove:async function(r,i){if(!r||!i)throw new Error("Both id and geohash are required to remove a place");const s=await n.getAll();await Promise.all(s.map(async e=>{const n=e.placeRefs.findIndex(t=>t.id===r);-1!==n&&(e.placeRefs.splice(n,1),e.updatedAt=(new Date).toISOString(),await t.storeObject("list",`_lists/${e.id}`,e))}));const o=e(i,r);return t.remove(o)},get:async function(n,r){if(!n||!r)throw new Error("Both id and geohash are required to get a place");const i=e(r,n);return t.getObject(i)},listByPrefix:async function(e){let n="";return e.length>=2&&(n+=e.substring(0,2)+"/"),e.length>=4&&(n+=e.substring(2,4)+"/"),t.getAll(n)},getPlaces:async function(e){const n=[],r=async e=>{const r=await t.getAll(e,!1);r&&Object.values(r).forEach(t=>{t&&"object"==typeof t&&!t.toString().endsWith("/")&&n.push(t)})};if(e&&e.length>0){const t=e.map(async t=>{if(t.length<4)return;const e=t.substring(0,2),n=t.substring(2,4);await r(`${e}/${n}/`)});await Promise.all(t)}else{const e=t=>{if(!t||"object"!=typeof t)return[];let e=t;return t.items&&"object"==typeof t.items&&(e=t.items),Object.keys(e).filter(t=>t.endsWith("/")&&!t.startsWith("@"))},n=await t.getListing("",!1),i=e(n);await Promise.all(i.map(async n=>{const i=await t.getListing(n,!1),s=e(i);await Promise.all(s.map(async t=>{await r(n+t)}))}))}return n}};return{exports:r}}};var tj,ej,nj={exports:{}},rj=tj?nj.exports:(tj=1,self,ej=()=>(()=>{var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function r(t){var e=function(t){if("object"!=n(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=n(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==n(e)?e:e+""}t.d(e,{default:()=>i});const i=function(){return t=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.rs=e,this.leaveOpen=!!n.leaveOpen&&n.leaveOpen,this.autoCloseAfter=n.autoCloseAfter?n.autoCloseAfter:1500,this.skipInitial=!!n.skipInitial&&n.skipInitial,this.logging=!!n.logging&&n.logging,this.parentContainerEl=null,n.hasOwnProperty("modalBackdrop")){if("boolean"!=typeof n.modalBackdrop&&"onlySmallScreens"!==n.modalBackdrop)throw'options.modalBackdrop has to be true/false or "onlySmallScreens"';this.modalBackdrop=n.modalBackdrop}else this.modalBackdrop="onlySmallScreens";this.active=!1,this.online=!1,this.closed=!1,this.lastSynced=null,this.lastSyncedUpdateLoop=null},e=[{key:"log",value:function(){if(this.logging){for(var t,e=arguments.length,n=new Array(e),r=0;r

Connect your storage

To sync data with your account
';var e=document.createElement("style");return e.innerHTML='#remotestorage-widget {\n z-index: 21000000;\n}\n\n.rs-widget {\n box-sizing: border-box;\n overflow: hidden;\n max-width: 350px;\n padding: 10px;\n margin: 10px;\n border-radius: 3px;\n background-color: #fff;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n font-family: arial, sans-serif;\n font-size: 16px;\n color: #333;\n will-change: max-height, height, width, opacity, max-width, background, box-shadow;\n transition-property: width, height, opacity, max-width, max-height, background, box-shadow;\n transition-duration: 300ms;\n}\n\n.rs-widget * {\n box-sizing: border-box;\n}\n\n.rs-widget .rs-hidden {\n display: none;\n}\n\n.rs-box {\n overflow: hidden;\n will-change: height;\n transition-property: height, width, max-height;\n transition-duration: 300ms;\n transition-timing-function: ease-in;\n opacity: 0;\n max-height: 0px;\n}\n\n.rs-box.rs-selected:not([aria-hidden=true]) {\n opacity: 1;\n max-height: 420px;\n}\n\n/* Main logo */\n.rs-main-logo {\n float: left;\n height: 36px;\n width: 36px;\n margin-top: 1px;\n margin-right: 0.625em;\n transition: margin-left 300ms ease-out, transform 300ms ease-out;\n cursor: pointer;\n}\n.rs-widget .rs-backend-remotestorage svg#rs-main-logo-remotestorage {\n display: block;\n}\n.rs-widget[class*="rs-backend-"]:not(.rs-backend-remotestorage) svg#rs-main-logo-remotestorage {\n display: none;\n}\n.rs-widget.rs-backend-dropbox svg#rs-main-logo-dropbox {\n display: block;\n}\n.rs-widget:not(.rs-backend-dropbox) svg#rs-main-logo-dropbox {\n display: none;\n}\n.rs-widget.rs-backend-googledrive svg#rs-main-logo-googledrive {\n display: block;\n}\n.rs-widget:not(.rs-backend-googledrive) svg#rs-main-logo-googledrive {\n display: none;\n}\n\npolygon.rs-logo-shape {\n fill: #FF4B03;\n}\n\npolygon.rs-logo-shape,\n#rs-main-logo-dropbox path,\n#rs-main-logo-googledrive path {\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n.rs-offline polygon.rs-logo-shape,\n.rs-offline #rs-main-logo-dropbox path,\n.rs-offline #rs-main-logo-googledrive path {\n fill: #888;\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n/* Hide everything except logo when connected and clicked outside of box */\n.rs-closed {\n max-width: 56px;\n background-color: transparent;\n box-shadow: none;\n opacity: 0.5;\n\n transition: max-height 100ms ease-out 0ms, max-width 300ms ease-out 300ms, background 300ms ease-in 200ms, opacity 300ms ease 200ms;\n}\n\n.rs-closed:hover {\n cursor: pointer;\n opacity: 1;\n}\n\n.rs-box-initial {\n transition-duration: 0ms;\n}\n\n.rs-box-initial:hover {\n cursor: pointer;\n}\n\n.rs-widget a {\n color: #0093cc;\n}\n\n/* HEADLINE */\n.rs-small-headline {\n font-size: 1em;\n font-weight: bold;\n margin: 0;\n margin-bottom: 2px;\n height: 1.2em;\n word-break: break-all;\n overflow: hidden;\n line-height: 1em;\n}\n\n.rs-sub-headline {\n word-break: break-all;\n overflow: hidden;\n color: #666;\n font-size: 0.92em;\n height: 1.2em;\n}\n.rs-big-headline {\n font-size: 1.625em;\n font-weight: normal;\n text-align: center;\n margin-top: 20px;\n margin-bottom: 20px;\n}\n\n/* BUTTONS */\n.rs-button {\n font: inherit;\n color: inherit;\n background-color: transparent;\n border: 1px solid #dcdcdc;\n border-radius: 3px;\n cursor: pointer;\n}\n.rs-button-small {\n padding: 0.6em 0.7em;\n margin-left: 0.2em;\n transition: border-color 300ms ease-out;\n}\n.rs-button-small svg {\n vertical-align: top;\n}\n.rs-button-wrap {\n margin-top: 10px;\n}\n\n.rs-button-wrap img,\n.rs-button-wrap svg {\n float: left;\n margin-right: 0.6em;\n width: 40px;\n height: 40px;\n}\n\n.rs-button-big {\n padding: 15px 10px;\n margin-bottom: 10px;\n display: block;\n width: 100%;\n text-align: left;\n transition: box-shadow 200ms;\n}\n.rs-button-big > div {\n font-size: 1.125em;\n padding: 10px 0;\n}\n.rs-button-big:hover {\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:active {\n background-color: #eee;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:last-child {\n margin-bottom: 0;\n}\n\n.rs-content {\n padding: 0 10px 10px 10px;\n}\n\n\n.rs-state-choose .rs-main-logo,\n.rs-state-sign-in .rs-main-logo {\n margin-left: 45%;\n float: none;\n}\n\n.rs-sign-in-form input[type=text] {\n padding: 15px 10px;\n display: block;\n width: 100%;\n font: inherit;\n height: 52px;\n border: 1px solid #aaa;\n border-radius: 0;\n box-shadow: none;\n}\n.rs-sign-in-form button.rs-connect {\n padding: 15px 10px;\n margin-top: 20px;\n margin-bottom: 15px;\n display: block;\n width: 100%;\n border: none;\n border-radius: 3px;\n background-color: #3fb34f;\n font: inherit;\n color: #fff;\n transition: box-shadow 200ms, background-color 200ms;\n}\n\n.rs-sign-in-form button.rs-connect:hover {\n cursor: pointer;\n background-color: #4BCB5D;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n\n.rs-sign-in-form button.rs-connect:active {\n background-color: #3fb34f;\n}\n\n.rs-sign-in-form button.rs-connect:disabled,\n.rs-sign-in-form button.rs-connect:disabled:hover {\n background-color: #aaa;\n}\n\n.rs-sign-in-form button.rs-connecting svg {\n height: 1em;\n width: auto;\n vertical-align: middle;\n margin-left: 0.5em;\n animation: rs-spin 1s linear infinite;\n}\n\n.rs-sign-in-error.rs-hidden,\n.rs-box-error.rs-hidden {\n height: 0;\n}\n\n.rs-sign-in-error.rs-visible,\n.rs-box-error.rs-visible {\n height: auto;\n border-radius: 3px;\n padding: 0.5em 0.5em;\n margin-top: 0.5em;\n text-align: center;\n background-color: rgba(255,0,0,0.1);\n color: darkred;\n}\n\n.rs-box-error {\n display: flex;\n flex-direction: row;\n}\n\n.rs-box-error .rs-error-message {\n flex: auto;\n}\n\n /*Choose provider box */\n.rs-box-choose {\n text-align: center;\n overflow: hidden;\n}\n\n.rs-box-choose p {\n margin-top: 0;\n margin-bottom: 20px;\n line-height: 1.4em;\n}\n\n/*Connected box */\n.rs-box-connected {\n display: flex;\n flex-direction: row;\n height: 40px;\n transition: height 0s;\n}\n.rs-connected-text {\n flex: auto;\n min-width: 0;\n}\n.rs-box-connected .rs-user {\n font-weight: bold;\n text-overflow: ellipsis;\n overflow: hidden;\n word-break: keep-all;\n}\n.rs-connected-buttons, .rs-error-buttons {\n flex: none;\n}\n.rs-disconnect:hover {\n border-color: #FF2D2D;\n}\n.rs-disconnect:hover .rs-icon{\n fill: #FF2D2D;\n}\n.rs-sync:hover {\n border-color: #FFBB0C;\n}\n.rs-sync:hover .rs-icon {\n fill: #FFBB0C;\n}\n.rs-sync.rs-rotate {\n border-color: #FFBB0C;\n}\n.rs-sync.rs-rotate .rs-icon {\n fill: #FFBB0C;\n animation: rs-spin 1s linear infinite;\n}\n\n/* Floating widget styles (top right corner) */\n.rs-floating {\n position: fixed;\n top: 0;\n right: 0;\n}\n\n@keyframes rs-spin {\n 100% {\n transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n/* Small/mobile screens */\n@media screen and (max-width: 420px) {\n .rs-widget {\n font-size: 100%;\n transition: all 300ms ease-out;\n max-width: 400px;\n }\n .rs-floating {\n position: relative;\n top: auto;\n right: auto\n }\n .rs-closed {\n max-width: 56px;\n }\n .rs-state-choose,\n .rs-state-sign-in {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n max-width: 100%;\n }\n}\n\n/* remove dotted outline border on Firefox */\n.rs-widget a:focus,\n.rs-widget a:active,\n.rs-widget button:focus,\n.rs-widget input:focus {\n outline:none;\n}\n.rs-widget button::-moz-focus-inner,\n.rs-widget input[type="button"]::-moz-focus-inner {\n border:0;\n}\n\n/* prevent rounded buttons on mobile Safari */\n.rs-widget button,\n.rs-widget input[type="button"] {\n -webkit-appearance: none;\n}\n\n.remotestorage-widget-modal-backdrop {\n display: none;\n position: fixed;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-color: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: opacity 0.3s linear;\n}\n\n.remotestorage-widget-modal-backdrop.visible {\n opacity: 1;\n transition: opacity 0.3s linear;\n}\n',t.appendChild(e),t}},{key:"setModalClass",value:function(){if(this.modalBackdrop){if("onlySmallScreens"===this.modalBackdrop&&!this.isSmallScreen())return;this.rsWidget.classList.add("rs-modal")}}},{key:"setupElements",value:function(){if(!this.parentContainerEl)throw new Error("Parent container element not found");this.rsWidget=this.parentContainerEl.querySelector(".rs-widget"),this.rsBackdrop=this.parentContainerEl.querySelector(".remotestorage-widget-modal-backdrop"),this.rsInitial=this.parentContainerEl.querySelector(".rs-box-initial"),this.rsChoose=this.parentContainerEl.querySelector(".rs-box-choose"),this.rsConnected=this.parentContainerEl.querySelector(".rs-box-connected"),this.rsSignIn=this.parentContainerEl.querySelector(".rs-box-sign-in"),this.rsConnectedLabel=this.parentContainerEl.querySelector(".rs-box-connected .rs-sub-headline"),this.rsChooseRemoteStorageButton=this.parentContainerEl.querySelector("button.rs-choose-rs"),this.rsChooseDropboxButton=this.parentContainerEl.querySelector("button.rs-choose-dropbox"),this.rsChooseGoogleDriveButton=this.parentContainerEl.querySelector("button.rs-choose-googledrive"),this.rsErrorBox=this.parentContainerEl.querySelector(".rs-box-error .rs-error-message"),this.rs.apiKeys.hasOwnProperty("googledrive")||this.rsChooseGoogleDriveButton.parentNode.removeChild(this.rsChooseGoogleDriveButton),this.rs.apiKeys.hasOwnProperty("dropbox")||this.rsChooseDropboxButton.parentNode.removeChild(this.rsChooseDropboxButton),this.rsSignInForm=this.parentContainerEl.querySelector(".rs-sign-in-form"),this.rsAddressInput=this.rsSignInForm.querySelector("input[name=rs-user-address]"),this.rsConnectButton=this.parentContainerEl.querySelector(".rs-connect"),this.rsDisconnectButton=this.parentContainerEl.querySelector(".rs-disconnect"),this.rsSyncButton=this.parentContainerEl.querySelector(".rs-sync"),this.rsLogo=this.parentContainerEl.querySelector(".rs-widget-icon"),this.rsErrorReconnectLink=this.parentContainerEl.querySelector(".rs-box-error a.rs-reconnect"),this.rsErrorDisconnectButton=this.parentContainerEl.querySelector(".rs-box-error button.rs-disconnect"),this.rsConnectedUser=this.parentContainerEl.querySelector(".rs-connected-text h1.rs-user")}},{key:"setupHandlers",value:function(){var t=this;this.rs.on("connected",function(){return t.eventHandler("connected")}),this.rs.on("ready",function(){return t.eventHandler("ready")}),this.rs.on("disconnected",function(){return t.eventHandler("disconnected")}),this.rs.on("network-online",function(){return t.eventHandler("network-online")}),this.rs.on("network-offline",function(){return t.eventHandler("network-offline")}),this.rs.on("error",function(e){return t.eventHandler("error",e)}),this.setEventListeners(),this.setClickHandlers()}},{key:"attach",value:function(t){var e=this.createHtmlTemplate(t);if(this.parentContainerEl,t instanceof HTMLElement)this.parentContainerEl=t;else if("string"==typeof t){if(this.parentContainerEl=document.getElementById(t),!this.parentContainerEl)throw new Error('Failed to find target DOM element with id="'+t+'"')}else{if(t)throw new Error("Unknown element type. Expected instance of HTMLElement or type of string.");this.parentContainerEl=document.body}this.parentContainerEl.appendChild(e),this.setupElements(),this.setupHandlers(),this.setInitialState(),this.setModalClass()}},{key:"setEventListeners",value:function(){var t=this;this.rsSignInForm.addEventListener("submit",function(e){e.preventDefault();var n=t.parentContainerEl.querySelector("input[name=rs-user-address]").value.trim();t.disableConnectButton(),t.rs.connect(n)})}},{key:"showChooseOrSignIn",value:function(){this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.style.display="block",this.rsBackdrop.classList.add("visible")),this.rs.apiKeys&&Object.keys(this.rs.apiKeys).length>0?this.setState("choose"):this.setState("sign-in")}},{key:"setClickHandlers",value:function(){var t=this;this.rsInitial.addEventListener("click",function(){return t.showChooseOrSignIn()}),this.rsChooseRemoteStorageButton.addEventListener("click",function(){t.setState("sign-in"),t.rsAddressInput.focus()}),this.rsChooseDropboxButton.addEventListener("click",function(){return t.rs.dropbox.connect()}),this.rsChooseGoogleDriveButton.addEventListener("click",function(){return t.rs.googledrive.connect()}),this.rsDisconnectButton.addEventListener("click",function(){return t.rs.disconnect()}),this.rsErrorReconnectLink.addEventListener("click",function(){return t.rs.reconnect()}),this.rsErrorDisconnectButton.addEventListener("click",function(){return t.rs.disconnect()}),this.rs.hasFeature("Sync")&&this.rsSyncButton.addEventListener("click",function(){t.rsSyncButton.classList.contains("rs-rotate")?(t.rs.stopSync(),t.rsSyncButton.classList.remove("rs-rotate")):(t.rsConnectedLabel.textContent="Synchronizing",t.rs.startSync(),t.rsSyncButton.classList.add("rs-rotate"))}),document.addEventListener("click",function(){return t.close()}),this.rsWidget.addEventListener("click",function(t){return t.stopPropagation()}),this.rsLogo.addEventListener("click",function(){return t.toggle()})}},{key:"toggle",value:function(){this.closed?this.open():"initial"===this.state?this.showChooseOrSignIn():this.close()}},{key:"open",value:function(){this.closed=!1,this.rsWidget.classList.remove("rs-closed"),this.shouldCloseWhenSyncDone=!1;var t=this.parentContainerEl.querySelector(".rs-box.rs-selected");t&&t.setAttribute("aria-hidden","false")}},{key:"close",value:function(){var t=this;if("error"!==this.state){if(!this.leaveOpen&&this.active){this.closed=!0,this.rsWidget.classList.add("rs-closed");var e=this.parentContainerEl.querySelector(".rs-box.rs-selected");e&&e.setAttribute("aria-hidden","true")}else this.active?this.setState("connected"):this.setInitialState();this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.classList.remove("visible"),setTimeout(function(){t.rsBackdrop.style.display="none"},300))}}},{key:"disableConnectButton",value:function(){this.rsConnectButton.disabled=!0,this.rsConnectButton.classList.add("rs-connecting"),this.rsConnectButton.innerHTML="Connecting ".concat('\n \n \n \n \n \n \n\n')}},{key:"enableConnectButton",value:function(){this.rsConnectButton.disabled=!1,this.rsConnectButton.textContent="Connect",this.rsConnectButton.classList.remove("rs-connecting")}},{key:"setOffline",value:function(){this.online&&(this.rsWidget.classList.add("rs-offline"),this.rsConnectedLabel.textContent="Offline",this.online=!1)}},{key:"setOnline",value:function(){this.online||(this.rsWidget.classList.remove("rs-offline"),this.active&&(this.rsConnectedLabel.textContent="Connected")),this.online=!0}},{key:"setBackendClass",value:function(t){this.rsWidget.classList.remove("rs-backend-remotestorage"),this.rsWidget.classList.remove("rs-backend-dropbox"),this.rsWidget.classList.remove("rs-backend-googledrive"),t&&this.rsWidget.classList.add("rs-backend-".concat(t))}},{key:"showErrorBox",value:function(t){this.rsErrorBox.innerHTML=t,this.setState("error")}},{key:"hideErrorBox",value:function(){this.rsErrorBox.innerHTML="",this.close()}},{key:"handleSyncStarted",value:function(){var t=this;this.syncInProgress=!0,this.rsSyncButton.classList.add("rs-rotate"),setTimeout(function(){t.syncInProgress&&(t.rsConnectedLabel.textContent="Synchronizing")},1e3)}},{key:"handleDiscoveryError",value:function(t){var e=this.parentContainerEl.querySelector(".rs-sign-in-error");e.innerHTML=t.message,e.classList.remove("rs-hidden"),e.classList.add("rs-visible"),this.enableConnectButton()}},{key:"handleSyncError",value:function(){this.setOffline()}},{key:"handleUnauthorized",value:function(t){t.code&&"access_denied"===t.code?this.rs.disconnect():(this.open(),this.showErrorBox(t.message+" "),this.rsErrorBox.appendChild(this.rsErrorReconnectLink),this.rsErrorReconnectLink.classList.remove("rs-hidden"))}},{key:"updateLastSyncedStatus",value:function(){var t=new Date;this.online?(this.lastSynced=t,this.rsConnectedLabel.textContent="Synced"):this.rsWidget.classList.contains("rs-state-unauthorized")||(this.rsConnectedLabel.textContent="Offline")}},{key:"isSmallScreen",value:function(){return window.innerWidth<421}}],e&&function(t,e){for(var n=0;n{n?this.updated.push(this.wrapRecord(t)):(this.added.push(this.wrapRecord(t)),n=!0)}),this.recordCaches.set(t,e)}return e}constructor(t,e,n,r,i,s){this.wrapRecord=i,this.release=s,this.recordArrayCache=$e(()=>{let s=new Set;De(on(t,"[]")),fj(t,t=>{qe(this.getCacheForItem(t)),s.add(t)}),He(()=>{this.recordCaches.forEach((t,e)=>{s.has(e)||(this.removed.push(i(e)),this.recordCaches.delete(e))})}),this.added.length>0&&(e(this.added),this.added=[]),this.updated.length>0&&(n(this.updated),this.updated=[]),this.removed.length>0&&(r(this.removed),this.removed=[])})}revalidate(){qe(this.recordArrayCache)}}class mj{constructor(t,e,n){this.release=n;let r=!1;this.cache=$e(()=>{fj(t,()=>{}),De(on(t,"[]")),!0===r?Sa(e):r=!0}),this.release=n}revalidate(){qe(this.cache)}}class yj extends Mu{releaseMethods=sd();recordsWatchers=new Map;typeWatchers=new Map;flushWatchers=null;constructor(t){super(t),this.containerDebugAdapter=ui(this).lookup("container-debug-adapter:main")}attributeLimit=3;acceptsModelName=!0;getFilters(){return sd()}watchModelTypes(t,e){let n,r=this.getModelTypes(),i=sd();n=r.map(t=>{let n=t.klass,r=this.wrapModelType(n,t.name);return i.push(this.observeModelType(t.name,e)),r}),t(n);let s=()=>{i.forEach(t=>t()),this.releaseMethods.removeObject(s)};return this.releaseMethods.pushObject(s),s}_nameToClass(t){if("string"==typeof t){let e=ui(this).factoryFor(`model:${t}`);t=e&&e.class}return t}watchRecords(t,e,n,r){let i=this._nameToClass(t),s=this.getRecords(i,t),{recordsWatchers:o}=this,a=o.get(s);return a||(a=new gj(s,e,n,r,t=>this.wrapRecord(t),()=>{o.delete(s),this.updateFlushWatchers()}),o.set(s,a),this.updateFlushWatchers(),a.revalidate()),a.release}updateFlushWatchers(){null===this.flushWatchers?(this.typeWatchers.size>0||this.recordsWatchers.size>0)&&(this.flushWatchers=()=>{this.typeWatchers.forEach(t=>t.revalidate()),this.recordsWatchers.forEach(t=>t.revalidate())},ma.on("end",this.flushWatchers)):0===this.typeWatchers.size&&0===this.recordsWatchers.size&&(ma.off("end",this.flushWatchers),this.flushWatchers=null)}willDestroy(){this._super(...arguments),this.typeWatchers.forEach(t=>t.release()),this.recordsWatchers.forEach(t=>t.release()),this.releaseMethods.forEach(t=>t()),this.flushWatchers&&ma.off("end",this.flushWatchers)}detect(t){return!1}columnsForType(t){return sd()}observeModelType(t,e){let n=this._nameToClass(t),r=this.getRecords(n,t),{typeWatchers:i}=this,s=i.get(r);return s||(s=new mj(r,()=>{e([this.wrapModelType(n,t)])},()=>{i.delete(r),this.updateFlushWatchers()}),i.set(r,s),this.updateFlushWatchers(),s.revalidate()),s.release}wrapModelType(t,e){return{name:e,count:Cs(this.getRecords(t,e),"length"),columns:this.columnsForType(t),object:t}}getModelTypes(){let t=this.containerDebugAdapter,e=(t.canCatalogEntriesByType("model")?t.catalogEntriesByType("model"):this._getObjectsOnNamespaces()).map(t=>({klass:this._nameToClass(t),name:t}));return e.filter(t=>this.detect(t.klass))}_getObjectsOnNamespaces(){let t=Z_.NAMESPACES,e=[];return t.forEach(t=>{for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!this.detect(t[n]))continue;let r=Ff(n);e.push(r)}}),e}getRecords(t,e){return sd()}wrapRecord(t){return{object:t,columnValues:this.getRecordColumnValues(t),searchKeywords:this.getRecordKeywords(t),filterValues:this.getRecordFilterValues(t),color:this.getRecordColor(t)}}getRecordColumnValues(t){return{}}getRecordKeywords(t){return sd()}getRecordFilterValues(t){return{}}getRecordColor(t){return null}}const vj={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function bj(t,e){return"[]"===e?(t._revalidate(),t._arrTag):"length"===e?(t._revalidate(),t._lengthTag):on(t,e)}class wj extends Mu{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(t){super.init(t),lr(this,bj)}[rs](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(t){return di(Cs(this,"arrangedContent"),t)}replace(t,e,n){this.replaceContent(t,e,n)}replaceContent(t,e,n){Hs(Cs(this,"content"),t,e,n)}objectAt(t){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&t>=this._objectsDirtyIndex){let t=Cs(this,"arrangedContent");if(t){let e=this._objects.length=Cs(t,"length");for(let t=this._objectsDirtyIndex;ti)&&(this._objectsDirtyIndex=i),this._lengthDirty=!0,Vs(this,e,n,r,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!de(this._arrangedContentTag,this._arrangedContentRevision))){let t=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(t):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(t),this._arrangedContentIsUpdating=!1);let e=this._arrangedContentTag=on(this,"arrangedContent");this._arrangedContentRevision=he(this._arrangedContentTag),G(t)?(this._lengthTag=ke([e,fi(t,"length")]),this._arrTag=ke([e,fi(t,"[]")])):this._lengthTag=this._arrTag=e}}}wj.reopen(nd,{arrangedContent:Ns("content")});const _j=Object.freeze(Object.defineProperty({__proto__:null,default:wj},Symbol.toStringTag,{value:"Module"}));class xj extends ih{}xj.PrototypeMixin.reopen(tc);const Cj=Object.freeze(Object.defineProperty({__proto__:null,default:xj},Symbol.toStringTag,{value:"Module"})),Sj=ql.create({reason:null,isPending:ps("isSettled",function(){return!Cs(this,"isSettled")}).readOnly(),isSettled:ps("isRejected","isFulfilled",function(){return Cs(this,"isRejected")||Cs(this,"isFulfilled")}).readOnly(),isRejected:!1,isFulfilled:!1,promise:ps({get(){throw new Error("PromiseProxy's promise must be set")},set(t,e){return function(t,e){return Qs(t,{isFulfilled:!1,isRejected:!1}),e.then(e=>(t.isDestroyed||t.isDestroying||Qs(t,{content:e,isFulfilled:!0}),e),e=>{throw t.isDestroyed||t.isDestroying||Qs(t,{reason:e,isRejected:!0}),e},"Ember: PromiseProxy")}(this,e)}}),then:kj("then"),catch:kj("catch"),finally:kj("finally")});function kj(t){return function(...e){return Cs(this,"promise")[t](...e)}}const Ej=Object.freeze(Object.defineProperty({__proto__:null,default:Sj},Symbol.toStringTag,{value:"Module"}));function Tj(t,e,n){return t.lookup(`controller:${e}`,n)}let Rj;!function(t){function e(){}t.isNamespace=!0,t.toString=function(){return"Ember"},t.Container=gl,t.Registry=El,t._setComponentManager=pj,t._componentManagerCapabilities=jr,t._modifierManagerCapabilities=Vr,t.meta=ae,t._createCache=$e,t._cacheGetValue=qe,t._cacheIsConst=Ve,t._descriptor=Ci,t._getPath=ks,t._setClassicDecorator=Ai,t._tracked=Is,t.beginPropertyChanges=os,t.changeProperties=ls,t.endPropertyChanges=as,t.hasListeners=Ui,t.libraries=Rs,t._ContainerProxyMixin=Zl,t._ProxyMixin=tc,t._RegistryProxyMixin=Gl,t.ActionHandler=Xl,t.Comparable=Yl,t.ComponentLookup=ex,t.EventDispatcher=eh,t._Cache=si,t.GUID_KEY=Q,t.canInvoke=K_,t.generateGuid=tt,t.guidFor=et,t.uuid=Z,t.wrap=mt,t.getOwner=cx,t.onLoad=pl,t.runLoadHooks=fl,t.setOwner=ux,t.Application=hx,t.ApplicationInstance=H_,t.Namespace=Z_,t.A=sd,t.Array=ed,t.NativeArray=rd,t.isArray=Jh,t.makeArray=mu,t.MutableArray=nd,t.ArrayProxy=wj,t.FEATURES={isEnabled:oj,...sj},t._Input=qb,t.Component=Ew,t.Helper=Mw,t.Controller=cd,t.ControllerMixin=ld,t._captureRenderTree=A,t.assert=y,t.warn=z,t.debug=D,t.deprecate=V,t.deprecateFunc=q,t.runInDebug=B,t.inspect=L,t.Debug={registerDeprecationHandler:v,registerWarnHandler:x,isComputed:gs},t.ContainerDebugAdapter=tx,t.DataAdapter=yj,t._assertDestroyablesDestroyed=Nt,t._associateDestroyableChild=Wt,t._enableDestroyableTracking=Dt,t._isDestroying=Zt,t._isDestroyed=Yt,t._registerDestructor=_x,t._unregisterDestructor=xx,t.destroy=Gt,t.Engine=ox,t.EngineInstance=fd,t.Enumerable=ec,t.MutableEnumerable=nc,t.instrument=lh,t.subscribe=dh,t.Instrumentation={instrument:lh,subscribe:dh,unsubscribe:ph,reset:fh},t.Object=Mu,t._action=Pu,t.computed=ps,t.defineProperty=ms,t.get=Cs,t.getProperties=Js,t.notifyPropertyChange=ss,t.observer=Au,t.set=Fs,t.trySet=Ds,t.setProperties=Qs,t.cacheFor=Os,t._dependentKeyCompat=md,t.ComputedProperty=us,t.expandProperties=Fi,t.CoreObject=Su,t.Evented=nh,t.on=$i,t.addListener=Ni,t.removeListener=ji,t.sendEvent=Bi,t.Mixin=ql,t.mixin=Ul,t.Observable=Tu,t.addObserver=Hi,t.removeObserver=Gi,t.PromiseProxyMixin=Sj,t.ObjectProxy=xj,t.RouterDSL=Fp,t.controllerFor=Tj,t.generateController=fp,t.generateControllerFactory=pp,t.HashLocation=bf,t.HistoryLocation=xf,t.NoneLocation=Cf,t.Route=kp,t.Router=af,t.run=ya,t.Service=qf,t.compare=jh,t.isBlank=aj,t.isEmpty=kf,t.isEqual=cj,t.isNone=Sf,t.isPresent=lj,t.typeOf=zh,t.VERSION=oi,t.ViewUtils={getChildViews:Ku,getElementView:Uu,getRootViews:Du,getViewBounds:Yu,getViewBoundingClientRect:Qu,getViewClientRects:Ju,getViewElement:$u,isSimpleClick:Fu,isSerializationFirstNode:hb},t._getComponentTemplate=Jr,t._helperManagerCapabilities=vr,t._setComponentTemplate=Xr,t._setHelperManager=Kr,t._setModifierManager=Gr,t._templateOnlyComponent=Ny,t._invokeHelper=gv,t._hash=dv,t._array=av,t._concat=cv,t._get=hv,t._on=wv,t._fn=uv,t._Backburner=ha,t.inject=e,e.controller=ud,e.service=$f,t.__loader={get require(){return globalThis.require},get define(){return globalThis.define},get registry(){let t=globalThis;return t.requirejs?.entries??t.require.entries}}}(Rj||(Rj={})),Reflect.set(Rj,"RSVP",pu),Object.defineProperty(Rj,"ENV",{get:m,enumerable:!1}),Object.defineProperty(Rj,"lookup",{get:p,set:f,enumerable:!1}),Object.defineProperty(Rj,"onerror",{get:ko,set:function(t){Co=t},enumerable:!1}),Object.defineProperty(Rj,"testing",{get:w,set:_,enumerable:!1}),Object.defineProperty(Rj,"BOOTED",{configurable:!1,enumerable:!1,get:mo,set:yo}),Object.defineProperty(Rj,"TEMPLATES",{get:dj,set:hj,configurable:!1,enumerable:!1}),Object.defineProperty(Rj,"TEMPLATES",{get:dj,set:hj,configurable:!1,enumerable:!1}),Object.defineProperty(Rj,"testing",{get:w,set:_,enumerable:!1}),fl("Ember.Application",hx);let Mj={template:em,Utils:{}},Lj={template:em};function Ij(t){Object.defineProperty(Rj,t,{configurable:!0,enumerable:!0,get:()=>"Handlebars"===t?Mj:Lj})}function Pj(t){Object.defineProperty(Rj,t,{configurable:!0,enumerable:!0,get(){}})}Ij("HTMLBars"),Ij("Handlebars"),Pj("Test"),Pj("setupForTesting"),fl("Ember"),new Proxy(Rj,{get:(t,e,n)=>("string"==typeof e&&Uf(`importing ${e} from the 'ember' barrel file is deprecated.`,Bf.DEPRECATE_IMPORT_EMBER(e)),Reflect.get(t,e,n)),getOwnPropertyDescriptor:(t,e)=>("string"==typeof e&&Uf(`importing ${e} from the 'ember' barrel file is deprecated.`,Bf.DEPRECATE_IMPORT_EMBER(e)),Object.getOwnPropertyDescriptor(t,e))});const Aj=new WeakMap;function Oj(t,e,...n){if(t[e],t.isDestroying)return;"boolean"==typeof n[n.length-1]&&n[n.length-2];let r=Aj.get(t);var i;let s;r||(r=new Map,Aj.set(t,r),_x(t,(i=r,function(){0!==i.size&&i.forEach(t=>ka(t.cancelId))}))),s=r.has(e)?r.get(e).debouncedTask:(...n)=>{r.delete(e),t[e](...n)};let o=Ea(t,s,...n);r.set(e,{debouncedTask:s,cancelId:o})}class Fj extends qf{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");rs;widget;static{dF(this.prototype,"placesInView",[Is],function(){return[]})}#ut=void fF(this,"placesInView");static{dF(this.prototype,"savedPlaces",[Is],function(){return[]})}#ht=void fF(this,"savedPlaces");static{dF(this.prototype,"loadedPrefixes",[Is],function(){return[]})}#dt=void fF(this,"loadedPrefixes");static{dF(this.prototype,"currentBbox",[Is],function(){return null})}#pt=void fF(this,"currentBbox");static{dF(this.prototype,"lists",[Is],function(){return[]})}#ft=void fF(this,"lists");static{dF(this.prototype,"version",[Is],function(){return 0})}#gt=void fF(this,"version");static{dF(this.prototype,"initialSyncDone",[Is],function(){return!1})}#mt=void fF(this,"initialSyncDone");static{dF(this.prototype,"connected",[Is],function(){return!1})}#yt=void fF(this,"connected");static{dF(this.prototype,"userAddress",[Is],function(){return null})}#vt=void fF(this,"userAddress");static{dF(this.prototype,"isWidgetOpen",[Is],function(){return!1})}#bt=void fF(this,"isWidgetOpen");constructor(){super(...arguments),this.rs=new WN({modules:[QN]}),this.rs.access.claim("places","rw"),this.rs.caching.enable("/places/"),window.remoteStorage=this.rs,this.widget=new ij(this.rs,{leaveOpen:!0,skipInitial:!0}),this.rs.on("ready",()=>{}),this.rs.on("error",t=>{t&&(console.info("[rs] Error —",`${t.name}: ${t.message}`),"Unauthorized"===t.name&&this.showConnectWidget())}),this.rs.on("connected",()=>{this.connected=!0,this.userAddress=this.rs.remote.userAddress,this.loadLists()}),this.rs.on("not-connected",()=>{this.loadLists()}),this.rs.on("disconnected",()=>{this.connected=!1,this.userAddress=null,this.placesInView=[],this.savedPlaces=[],this.loadedPrefixes=[],this.lists=[],this.initialSyncDone=!1}),this.rs.on("sync-done",()=>{this.initialSyncDone||(this.initialSyncDone=!0,this.loadLists())}),this.rs.scope("/places/").on("change",t=>{t.relativePath.startsWith("_lists/")?this.loadLists():(this.handlePlaceChange(t),Oj(this,"reloadCurrentView",200))})}handlePlaceChange(t){const{newValue:e,relativePath:n}=t,r=n.split("/"),i=r[r.length-1];if(e){const t={...e,id:i},n=this.savedPlaces.findIndex(t=>t.id===i);if(-1!==n){const e=[...this.savedPlaces];e[n]=t,this.savedPlaces=e}else this.savedPlaces=[...this.savedPlaces,t]}else this.savedPlaces=this.savedPlaces.filter(t=>t.id!==i)}get places(){return this.rs.places}notifyChange(){this.version++,Oj(this,"reloadCurrentView",200)}reloadCurrentView(){if(!this.currentBbox)return;const t=ND(this.currentBbox);console.debug("Reloading view due to changes, prefixes:",t),this.loadAllPlaces(t)}async loadLists(){try{if(!this.places.lists)return;await this.places.lists.initDefaults();const t=await this.places.lists.getAll();this.lists=t||[],this.lists.forEach(t=>{"to-go"===t.id?t.icon="bookmark":"to-do"===t.id&&(t.icon="check-square")}),this.refreshPlaceListAssociations()}catch(ej){console.error("Failed to load lists:",ej)}}refreshPlaceListAssociations(){const t=new Map;this.lists.forEach(e=>{e.placeRefs&&Array.isArray(e.placeRefs)&&e.placeRefs.forEach(n=>{n.id&&(t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(e.id))})});const e=e=>{const n=t.get(e.id)||[];return e._listIds=n,e};this.savedPlaces=this.savedPlaces.map(t=>e({...t})),this.placesInView=this.placesInView.map(t=>e({...t}))}async togglePlaceList(t,e,n){if(!t)return;let r=t;if(!t.id||!t.geohash){if(!n)return;r=await this.storePlace(t)}try{return n?await this.places.lists.addPlace(e,r.id,r.geohash):await this.places.lists.removePlace(e,r.id),await this.loadLists(),this.findPlaceById(r.id)}catch(ej){throw console.error("Failed to toggle place in list:",ej),ej}}async loadPlacesInBounds(t){const e=ND(t).filter(t=>!this.loadedPrefixes.includes(t));0!==e.length&&(console.debug("Loading new prefixes:",e),await this.loadAllPlaces(e),this.loadedPrefixes=[...this.loadedPrefixes,...e],this.currentBbox=t)}async loadAllPlaces(t=null){try{const e=await this.places.getPlaces(t);if(e&&Array.isArray(e)){if(t){const n=new Set(t),r=this.placesInView.filter(t=>{if(!t.lat||!t.lon)return!1;try{const e=DD.encode(t.lat,t.lon,4);return!n.has(e)}catch{return!0}});this.placesInView=[...r,...e]}else this.placesInView=e;this.refreshPlaceListAssociations()}else t||(this.placesInView=[]);console.debug("Loaded saved places:",this.placesInView.length)}catch(ej){console.error("Failed to load places:",ej)}}findPlaceById(t){if(!t)return;const e=String(t);let n=this.savedPlaces.find(t=>t.id&&String(t.id)===e);return n||(n=this.placesInView.find(t=>t.id&&String(t.id)===e),n||(n=this.savedPlaces.find(t=>t.osmId&&String(t.osmId)===e),n||(n=this.placesInView.find(t=>t.osmId&&String(t.osmId)===e),n)))}isPlaceSaved(t){return!!this.findPlaceById(t)}async storePlace(t){const e=await this.places.store(t);return this.savedPlaces.some(t=>t.id===e.id)?this.savedPlaces=this.savedPlaces.map(t=>t.id===e.id?e:t):this.savedPlaces=[...this.savedPlaces,e],this.placesInView.some(t=>t.id===e.id)?this.placesInView=this.placesInView.map(t=>t.id===e.id?e:t):this.placesInView=[...this.placesInView,e],e}async updatePlace(t){const e=await this.places.store(t),n=this.savedPlaces.findIndex(t=>t.id===e.id);if(-1!==n){const t=[...this.savedPlaces];t[n]=e,this.savedPlaces=t}return this.placesInView=this.placesInView.map(t=>t.id===e.id?e:t),e}async removePlace(t){await this.places.remove(t.id,t.geohash),this.savedPlaces=this.savedPlaces.filter(e=>e.id!==t.id),this.placesInView.length>0&&(this.placesInView=this.placesInView.filter(e=>e.id!==t.id))}async refreshPlace(t){if(!(t&&t.id&&t.osmId&&t.osmType))return null;try{console.debug(`Checking for updates for ${t.title} (${t.osmId})`);const e=await this.osm.fetchOsmObject(t.osmId,t.osmType);if(!e)return console.warn("Could not fetch fresh data for",t.osmId),null;let n=!1;const r={},i=Math.abs(t.lat-e.lat),s=Math.abs(t.lon-e.lon);(i>1e-5||s>1e-5)&&(n=!0,r.lat=e.lat,r.lon=e.lon);const o=t.osmTags||{},a=e.osmTags||{},l=new Set([...Object.keys(o),...Object.keys(a)]);for(const t of l)if(o[t]!==a[t]){n=!0,r.osmTags=a;break}if(!n)return console.debug("No changes detected for",t.title),null;console.debug("Changes detected:",r);const c={...t,...r},u=RN(o),h=RN(a);return t.title===u&&u!==h&&(c.title=h),await this.updatePlace(c)}catch(ej){return console.error("Failed to refresh place:",ej),null}}showConnectWidget(){this.isWidgetOpen=!0,document.querySelector(".rs-widget")||this.widget.attach("rs-widget-container")}static{pF(this.prototype,"showConnectWidget",[Pu])}closeWidget(){this.isWidgetOpen=!1}static{pF(this.prototype,"closeWidget",[Pu])}disconnect(){this.rs.disconnect(),this.isWidgetOpen=!1}static{pF(this.prototype,"disconnect",[Pu])}}const zj=Object.freeze(Object.defineProperty({__proto__:null,default:Fj},Symbol.toStringTag,{value:"Module"}));class Dj extends qf{static{dF(this.prototype,"message",[Is],function(){return null})}#wt=void fF(this,"message");static{dF(this.prototype,"isVisible",[Is],function(){return!1})}#_t=void fF(this,"isVisible");timeoutId=null;show(t,e=3e3){this.message=t,this.isVisible=!0,this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isVisible=!1},e)}}const Nj=Object.freeze(Object.defineProperty({__proto__:null,default:Dj},Symbol.toStringTag,{value:"Module"}));function jj(t,e,n,r){const i=t*Math.PI/180,s=n*Math.PI/180,o=(n-t)*Math.PI/180,a=(r-e)*Math.PI/180,l=Math.sin(o/2)*Math.sin(o/2)+Math.cos(i)*Math.cos(s)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3}const Bj=Object.freeze(Object.defineProperty({__proto__:null,getDistance:jj},Symbol.toStringTag,{value:"Module"})),Uj={activity:'',angelfish:'\n \n',"arrow-left":'',barbell:'\n \n',banknote:'\n \n',"badge-shield-with-fire":'\n \n',"beach-umbrella-in-ground":'\n \n',"beer-mug-with-foam":'\n \n',bookmark:'',"boxing-glove-up":'\n \n',"burger-and-drink-cup-with-straw":'\n \n',bus:'\n \n',camera:'',"check-square":'',"chevron-left":'',"chevron-right":'',"cigarette-with-smoke-curl":'\n \n',climbing_wall:'\n \n',check:'',"alert-circle":'',"classical-building":'\n \n',"classical-building-with-dome-and-flag":'\n \n',"classical-building-with-flag":'\n \n',"commercial-building":'\n \n',"clothes-hanger":'\n \n',cleaver:'\n \n',cloth:'\n \n',cocktail:'\n \n',clock:'',"coffee-bean":'\n \n',"comedy-mask-and-tragedy-mask":'\n \n',croissant:'\n \n',"cup-and-saucer":'\n \n',donut:'\n \n',edit:'',eyeglasses:'\n \n',facebook:'',"fancy-mirror-with-reflection-and-stars":'\n \n',"family-restroom-symbol":'\n \n',film:'\n \n',"fingernail-polished":'\n \n',fish:'\n \n',"flag-checkered":'\n \n',"flower-bouquet":'\n \n',"fork-and-knife":'\n \n',fort:'\n \n',gift:'',globe:'',gravestone:'\n \n',"grecian-vase":'\n \n',"greek-cross":'\n \n',heart:'',home:'',"ice-cream-on-cone":'\n \n',info:'',instagram:'',jewel:'\n \n',"log-in":'',"log-out":'',"lowrise-building":'\n \n',mail:'',map:'',"map-pin":'',"market-stall":'\n \n',"memorial-stone-with-inscription":'\n \n',menu:'',"mobile-phone-with-keypad-and-antenna":'\n \n',"molar-tooth":'\n \n',navigation:'',"needle-and-spool-of-thread":'\n \n',nostrich:'\n \n\n',"open-book":'\n \n',palace:'\n \n',"person-cricket-batting-at-cricket-ball":'\n \n',"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track":'\n \n',"person-jockeying-racehorse":'\n \n',"person-playing-tennis":'\n \n',"person-running":'\n \n',"person-sleeping-in-bed":'\n \n',"person-swimming-in-water":'\n \n',"person-swinging-golf-club":'\n \n',phone:'',"plane-top-right":'\n \n',"plant-in-raised-planter":'\n \n',"place-of-worship-building":'\n \n',"play-structure-with-slide":'\n \n',"police-officer-with-stop-arm":'\n \n',plus:'',"round-structure-with-flag":'\n \n',remotestorage:'\n\x3c!-- Creator: CorelDRAW X7 --\x3e\n\n \n',"sailing-ship-in-water":'\n \n',"scissors-open":'\n \n',"shipwreck-in-water":'\n \n',"shopping-bag":'\n \n',search:'',server:'',settings:'',"shopping-basket":'\n \n',"shopping-cart":'\n \n',"table-tennis-paddle":'\n \n',"tattoo-machine":'\n \n',toolbox:'\n \n',target:'',"trash-2":'',"upload-cloud":'',"tree-and-bench-with-backrest":'\n \n',user:'',"village-buildings":'\n \n',"wall-hanging-with-mountains-and-sun":'\n \n',"womens-and-mens-restroom-symbol":'\n \n',whatsapp:'\n\n \n\n',wikipedia:'\n\n\n',parking_p:'\n \n',car:'\n \n',x:'',zap:'',"loading-ring":''},$j=["fork-and-knife","wikipedia","whatsapp","cup-and-saucer","coffee-bean","shopping-basket","person-sleeping-in-bed","loading-ring","nostrich"];function qj(t){return Uj[t]}function Vj(t){return $j.includes(t)}const Wj=Object.freeze(Object.defineProperty({__proto__:null,getIcon:qj,isIconFilled:Vj},Symbol.toStringTag,{value:"Module"})),Hj=[{tags:{cuisine:"donut"},icon:"donut"},{tags:{cuisine:"doughnut"},icon:"donut"},{tags:{cuisine:"coffee_shop"},icon:"coffee-bean"},{tags:{cuisine:"coffee"},icon:"coffee-bean"},{tags:{amenity:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{cuisine:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{shop:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{amenity:"cafe"},icon:"cup-and-saucer"},{tags:{amenity:"restaurant"},icon:"fork-and-knife"},{tags:{amenity:"fast_food"},icon:"burger-and-drink-cup-with-straw"},{tags:{amenity:"pub"},icon:"beer-mug-with-foam"},{tags:{amenity:"bar"},icon:"cocktail"},{tags:{amenity:"food_court"},icon:"fork-and-knife"},{tags:{amenity:"childcare"},icon:"family-restroom-symbol"},{tags:{amenity:"community_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_facility"},icon:"family-restroom-symbol"},{tags:{amenity:"bank"},icon:"banknote"},{tags:{amenity:"place_of_worship"},icon:"place-of-worship-building"},{tags:{amenity:"fire_station"},icon:"badge-shield-with-fire"},{tags:{amenity:"police"},icon:"police-officer-with-stop-arm"},{tags:{amenity:"toilets"},icon:"womens-and-mens-restroom-symbol"},{tags:{amenity:"school"},icon:"open-book"},{tags:{amenity:"driving_school"},icon:"car"},{tags:{shop:"coffee"},icon:"coffee-bean"},{tags:{shop:"tea"},icon:"coffee-bean"},{tags:{shop:"pastry"},icon:"donut"},{tags:{shop:"supermarket"},icon:"shopping-cart"},{tags:{shop:"convenience"},icon:"shopping-basket"},{tags:{shop:"grocery"},icon:"shopping-basket"},{tags:{shop:"greengrocer"},icon:"shopping-basket"},{tags:{shop:"bakery"},icon:"croissant"},{tags:{shop:"butcher"},icon:"cleaver"},{tags:{shop:"seafood"},icon:"fish"},{tags:{shop:"deli"},icon:"shopping-basket"},{tags:{shop:"clothes"},icon:"clothes-hanger"},{tags:{shop:"clothing"},icon:"clothes-hanger"},{tags:{shop:"hairdresser"},icon:"scissors-open"},{tags:{shop:"optician"},icon:"eyeglasses"},{tags:{shop:"fabric"},icon:"cloth"},{tags:{shop:"flea_market"},icon:"market-stall"},{tags:{shop:"kiosk"},icon:"shopping-basket"},{tags:{shop:"leather"},icon:"shopping-bag"},{tags:{shop:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{shop:"jewelry"},icon:"jewel"},{tags:{shop:"jewellery"},icon:"jewel"},{tags:{shop:"tobacco"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"cannabis"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"florist"},icon:"flower-bouquet"},{tags:{shop:"garden_centre"},icon:"plant-in-raised-planter"},{tags:{shop:"estate_agent"},icon:"village-buildings"},{tags:{shop:"mobile_phone"},icon:"mobile-phone-with-keypad-and-antenna"},{tags:{beauty:"nails"},icon:"fingernail-polished"},{tags:{shop:"tattoo"},icon:"tattoo-machine"},{tags:{shop:"beauty"},icon:"fancy-mirror-with-reflection-and-stars"},{tags:{craft:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{office:"estate_agent"},icon:"village-buildings"},{tags:{office:!0},icon:"commercial-building"},{tags:{craft:!0},icon:"toolbox"},{tags:{shop:!0},icon:"shopping-bag"},{tags:{natural:"beach"},icon:"beach-umbrella-in-ground"},{tags:{leisure:"park"},icon:"tree-and-bench-with-backrest"},{tags:{leisure:"playground"},icon:"play-structure-with-slide"},{tags:{aeroway:"aerodrome"},icon:"plane-top-right"},{tags:{aeroway:"heliport"},icon:"plane-top-right"},{tags:{aeroway:"helipad"},icon:"plane-top-right"},{tags:{highway:"bus_stop"},icon:"bus"},{tags:{bus:!0},icon:"bus"},{tags:{railway:"tram_stop"},icon:"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track"},{tags:{tourism:"museum"},icon:"classical-building"},{tags:{tourism:"gallery"},icon:"wall-hanging-with-mountains-and-sun"},{tags:{tourism:"aquarium"},icon:"angelfish"},{tags:{tourism:"theme_park"},icon:"camera"},{tags:{tourism:"attraction"},icon:"camera"},{tags:{tourism:"viewpoint"},icon:"camera"},{tags:{tourism:"zoo"},icon:"camera"},{tags:{tourism:"artwork"},icon:"camera"},{tags:{amenity:"cinema"},icon:"film"},{tags:{amenity:"theatre"},icon:"camera"},{tags:{amenity:"arts_centre"},icon:"comedy-mask-and-tragedy-mask"},{tags:{amenity:"arts_center"},icon:"comedy-mask-and-tragedy-mask"},{tags:{historic:"fort"},icon:"fort"},{tags:{historic:"castle"},icon:"palace"},{tags:{historic:"building"},icon:"classical-building-with-flag"},{tags:{historic:"archaeological_site"},icon:"grecian-vase"},{tags:{historic:"memorial"},icon:"memorial-stone-with-inscription"},{tags:{historic:"tomb"},icon:"gravestone"},{tags:{historic:"monument"},icon:"classical-building-with-dome-and-flag"},{tags:{historic:"ship"},icon:"sailing-ship-in-water"},{tags:{historic:"wreck"},icon:"shipwreck-in-water"},{tags:{historic:"ruins"},icon:"camera"},{tags:{historic:"ruin"},icon:"camera"},{tags:{historic:"yes"},icon:"camera"},{tags:{tourism:"hotel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"hostel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"motel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"guest_house"},icon:"person-sleeping-in-bed"},{tags:{sport:"motor"},icon:"flag-checkered"},{tags:{sport:"karting"},icon:"flag-checkered"},{tags:{sport:"motocross"},icon:"flag-checkered"},{tags:{sport:"cricket"},icon:"person-cricket-batting-at-cricket-ball"},{tags:{sport:"boxing"},icon:"boxing-glove-up"},{tags:{sport:"martial_arts"},icon:"boxing-glove-up"},{tags:{sport:"tennis"},icon:"person-playing-tennis"},{tags:{sport:"squash"},icon:"person-playing-tennis"},{tags:{sport:"padel"},icon:"person-playing-tennis"},{tags:{sport:"table_tennis"},icon:"table-tennis-paddle"},{tags:{sport:"climbing"},icon:"climbing_wall"},{tags:{leisure:"water_park"},icon:"person-swimming-in-water"},{tags:{sport:"swimming"},icon:"person-swimming-in-water"},{tags:{sport:"golf"},icon:"person-swinging-golf-club"},{tags:{leisure:"golf_course"},icon:"person-swinging-golf-club"},{tags:{sport:"horse_racing"},icon:"person-jockeying-racehorse"},{tags:{sport:"fitness"},icon:"barbell"},{tags:{sport:"fitness_centre"},icon:"barbell"},{tags:{leisure:"fitness_centre"},icon:"barbell"},{tags:{sport:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"sports_centre"},icon:"person-running"},{tags:{leisure:"pitch"},icon:"person-running"},{tags:{sport:!0},icon:"person-running"},{tags:{amenity:"dentist"},icon:"molar-tooth"},{tags:{healthcare:"dentist"},icon:"molar-tooth"},{tags:{healthcare:!0},icon:"greek-cross"},{tags:{amenity:"parking"},icon:"parking_p"},{tags:{building:"commercial"},icon:"commercial-building"},{tags:{building:"apartments"},icon:"lowrise-building"}];function Gj(t){if(!t)return null;for(const e of Hj){let n=!0;for(const[r,i]of Object.entries(e.tags)){const e=t[r];if(!e){n=!1;break}const s=e.split(";").map(t=>t.trim());if(!0!==i&&!s.includes(i)){n=!1;break}}if(n)return e.icon}return null}const Kj=Object.freeze(Object.defineProperty({__proto__:null,POI_ICON_RULES:Hj,getIconNameForTags:Gj,getIconSvgForTags:function(t){const e=Gj(t);return e?qj(e):null}},Symbol.toStringTag,{value:"Module"}));function Zj(t){return{title:t.title||RN(t.osmTags,"Untitled Place"),lat:t.lat,lon:t.lon,tags:[],url:t.osmTags?.website,osmId:String(t.osmId||t.id),osmType:t.osmType,osmTags:t.osmTags||{},description:t.description}}const Yj=Object.freeze(Object.defineProperty({__proto__:null,mapToStorageSchema:Zj},Symbol.toStringTag,{value:"Module"}));function Xj(t,e){if(!t)return null;const n=`${e}.com`,r=((t,...e)=>{for(const n of e)if(t[n])return t[n];return null})(t,`contact:${e}`,e);if(!r)return null;if(r.startsWith("http"))try{const t=new URL(r);return"facebook"===e&&"/profile.php"===t.pathname&&t.searchParams.has("id")?{url:r,username:t.searchParams.get("id")}:{url:r,username:t.pathname.replace(/^\/|\/$/g,"")||r}}catch{return{url:r,username:r}}const i=r.replace(/^@/,"");return{url:`https://${n}/${i}`,username:i}}const Jj=Object.freeze(Object.defineProperty({__proto__:null,getSocialInfo:Xj},Symbol.toStringTag,{value:"Module"}));var Qj=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","$","%","*","+",",","-",".",":",";","=","?","@","[","]","^","_","{","|","}","~"],tB=t=>{let e=0;for(let n=0;n{var n="";for(let r=1;r<=e;r++){let i=Math.floor(t)/Math.pow(83,e-r)%83;n+=Qj[Math.floor(i)]}return n},nB=t=>{let e=t/255;return e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)},rB=t=>{let e=Math.max(0,Math.min(1,t));return e<=.0031308?Math.trunc(12.92*e*255+.5):Math.trunc(255*(1.055*Math.pow(e,.4166666666666667)-.055)+.5)},iB=(t,e)=>(t=>t<0?-1:1)(t)*Math.pow(Math.abs(t),e),sB=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t}},oB=t=>{let e=t>>8&255,n=255&t;return[nB(t>>16),nB(e),nB(n)]},aB=(t,e)=>{let n=Math.floor(t/361),r=Math.floor(t/19)%19,i=t%19;return[iB((n-9)/9,2)*e,iB((r-9)/9,2)*e,iB((i-9)/9,2)*e]},lB=(t,e,n,r)=>{let i=0,s=0,o=0,a=4*e;for(let c=0;c{if("PROCESS_IMAGE"!==t.data?.type)return;const{id:e,file:n,targetWidth:r,targetHeight:i,quality:s,computeBlurhash:o}=t.data;try{let t,c;try{const e=await createImageBitmap(n,{resizeWidth:r,resizeHeight:i,resizeQuality:"high"});if(t=new OffscreenCanvas(r,i),c=t.getContext("2d"),!c)throw new Error("Failed to get 2d context from OffscreenCanvas");c.drawImage(e,0,0,r,i),e.close()}catch(a){console.warn("Hardware resize failed, falling back to stepped software scaling:",a);const e=await n.arrayBuffer(),s=new Blob([e],{type:n.type}),o=await createImageBitmap(s);let l=o.width,u=o.height,h=new OffscreenCanvas(l,u),d=h.getContext("2d");for(d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(o,0,0);.5*h.width>r&&.5*h.height>i;){const t=new OffscreenCanvas(Math.floor(.5*h.width),Math.floor(.5*h.height)),e=t.getContext("2d");e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.drawImage(h,0,0,t.width,t.height),h=t}t=new OffscreenCanvas(r,i),c=t.getContext("2d"),c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(h,0,0,r,i),o.close()}let u=null;if(o)try{u=((t,e,n)=>{if(e*n*4!==t.length)throw new sB("Width and height must match the pixels array");let r=[];for(let l=0;l<3;l++)for(let i=0;i<4;i++){let s=0==i&&0==l?1:2,o=lB(t,e,n,(t,r)=>s*Math.cos(Math.PI*i*t/e)*Math.cos(Math.PI*l*r/n));r.push(o)}let i,s=r[0],o=r.slice(1),a="";if(a+=eB(21,1),o.length>0){let t=Math.max(...o.map(t=>Math.max(...t))),e=Math.floor(Math.max(0,Math.min(82,Math.floor(166*t-.5))));i=(e+1)/166,a+=eB(e,1)}else i=1,a+=eB(0,1);return a+=eB((t=>(rB(t[0])<<16)+(rB(t[1])<<8)+rB(t[2]))(s),4),o.forEach(t=>{a+=eB(((t,e)=>19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[0]/e,.5)+9.5))))*19+19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[1]/e,.5)+9.5))))+Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[2]/e,.5)+9.5)))))(t,i),2)}),a})(c.getImageData(0,0,r,i).data,r,i)}catch(l){console.warn("Could not generate blurhash (possible canvas fingerprinting protection):",l)}const h=await t.convertToBlob({type:"image/jpeg",quality:s}),d=`${r}x${i}`;self.postMessage({id:e,success:!0,blob:h,dim:d,blurhash:u})}catch(v5){self.postMessage({id:e,success:!1,error:v5.message})}};const cB=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function uB(t,e,n){return(e=function(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function hB(t,e,n,r){n&&Object.defineProperty(t,e,{enumerable:n.enumerable,configurable:n.configurable,writable:n.writable,value:n.initializer?n.initializer.call(r):void 0})}function dB(t,e,n,r){var i={};return Object.keys(r).forEach(function(t){i[t]=r[t]}),i.enumerable=!!i.enumerable,i.configurable=!!i.configurable,("value"in i||i.initializer)&&(i.writable=!0),void 0===(i=n.slice().reverse().reduce(function(n,r){return r(t,e,n)||n},i)).initializer&&(Object.defineProperty(t,e,i),i=null),i}var pB,fB,gB,mB,yB;const vB="undefined"!=typeof FastBoot,bB="routeDidChange",wB=["separator","prepend","replace"];let _B=(pB=$f("router"),fB=$f("-document"),gB=class extends qf{constructor(t){if(super(t),hB(this,"router",mB,this),hB(this,"document",yB,this),uB(this,"tokens",[]),uB(this,"_defaultConfig",{separator:" | ",prepend:!0,replace:null}),uB(this,"scheduleTitleUpdate",()=>{Ca("afterRender",this,this._updateTitle)}),this._validateExistingTitleElement(),function(t){return"resolveRegistration"in t}(t)){const n=t.resolveRegistration("config:environment");"object"==typeof(e=n)&&null!==e&&"pageTitle"in e&&wB.forEach(t=>{if(!kf(n.pageTitle[t])){const e=n.pageTitle[t];this._defaultConfig[t]=e}})}var e;this.router.on(bB,this.scheduleTitleUpdate)}applyTokenDefaults(t){const e=this._defaultConfig.separator,n=this._defaultConfig.prepend,r=this._defaultConfig.replace;t.previous??=null,t.next??=null,null==t.separator&&(t.separator=e),null==t.prepend&&null!=n&&(t.prepend=n),null==t.replace&&null!=r&&(t.replace=r)}inheritFromPrevious(t){const e=t.previous;e&&(null==t.separator&&(t.separator=e.separator),null==t.prepend&&(t.prepend=e.prepend))}push(t){const e=this._findTokenById(t.id);if(e){const n=this.tokens.indexOf(e),r=[...this.tokens],i=e.previous;return t.previous=i,t.next=e.next,this.inheritFromPrevious(t),this.applyTokenDefaults(t),r.splice(n,1,t),void(this.tokens=r)}const n=this.tokens.slice(-1)[0];n&&(t.previous=n??null,n.next=t,this.inheritFromPrevious(t)),this.applyTokenDefaults(t),this.tokens=[...this.tokens,t]}remove(t){const e=this._findTokenById(t);if(!e)return;const{next:n,previous:r}=e;n&&(n.previous=r),r&&(r.next=n),e.previous=e.next=null;const i=[...this.tokens];i.splice(i.indexOf(e),1),this.tokens=i}get visibleTokens(){const t=this.tokens;let e=t?t.length:0;const n=[];for(;e--;){const r=t[e];if(r){if(r.replace){n.unshift(r);break}n.unshift(r)}}return n}get sortedTokens(){const t=this.visibleTokens;if(!t)return[];let e=!0,n=[];const r=[n],i=[];return t.forEach(t=>{t.front?i.unshift(t):t.prepend?(e&&(e=!1,n=[],r.push(n)),n.unshift(t)):(e||(e=!0,n=[],r.push(n)),n.push(t))}),i.concat(r.reduce((t,e)=>t.concat(e),[]))}toString(){const t=this.sortedTokens,e=[];for(let n=0,r=t.length;ne.id===t)}updateFastbootTitle(t){if(!vB)return;const e=this.document.head,n=e.childNodes;for(let s=0;snew MB(t),LB);const IB=Object.freeze(Object.defineProperty({__proto__:null,default:LB},Symbol.toStringTag,{value:"Module"})),PB=Gr,AB=uv;function OB(t){return"object"==typeof t&&t&&"isTruthy"in t&&"boolean"==typeof t.isTruthy?t.isTruthy:Jh(t)?0!==t.length:!!t}class FB extends Mw{compute(t){for(let e=0,n=t.length;e[zw],isStrictMode:!0}),this)}}class NB extends LB{static{dF(this.prototype,"title",[Is],function(){return""})}#xt=void fF(this,"title");static{dF(this.prototype,"description",[Is],function(){return""})}#Ct=void fF(this,"description");constructor(){super(...arguments),this.title=this.args.place?.title||"",this.description=this.args.place?.description||""}get shouldAutofocus(){return"undefined"!=typeof window&&window.innerWidth>768}handleSubmit(t){t.preventDefault(),this.args.onSave&&this.args.onSave({title:this.title,description:this.description})}static{pF(this.prototype,"handleSubmit",[Pu])}updateTitle(t){this.title=t.target.value}static{pF(this.prototype,"updateTitle",[Pu])}updateDescription(t){this.description=t.target.value}static{pF(this.prototype,"updateDescription",[Pu])}static{Xr(em({id:null,block:'[[[11,"form"],[24,0,"edit-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-title"],[12],[1,"Title"],[13],[1,"\\n"],[1," "],[11,"input"],[24,1,"edit-title"],[16,2,[30,0,["title"]]],[24,0,"form-control"],[24,"placeholder","Name of the place"],[16,"autofocus",[30,0,["shouldAutofocus"]]],[24,4,"text"],[4,[32,0],["input",[30,0,["updateTitle"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-desc"],[12],[1,"Description"],[13],[1,"\\n "],[11,"textarea"],[24,1,"edit-desc"],[16,2,[30,0,["description"]]],[24,0,"form-control"],[24,"rows","3"],[24,"placeholder","Add some details..."],[4,[32,0],["input",[30,0,["updateDescription"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"edit-actions"],[12],[1,"\\n "],[10,"button"],[14,0,"btn btn-blue"],[14,4,"submit"],[12],[1,"Save"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"Cancel"],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onCancel"],[]]',moduleName:"/home/basti/src/marco/app/components/place-edit-form.gjs",scope:()=>[Sb],isStrictMode:!0}),this)}}class jB{capabilities=Vr();constructor(t){this.owner=t}createModifier(t,e){return{instance:new t(this.owner,e),element:null}}installModifier(t,e,n){const r=function(t,e){const n=t;return n.element=e,n}(t,e);r.instance.modify(e,n.positional,n.named)}updateModifier(t,e){t.instance.modify(t.element,e.positional,e.named)}destroyModifier({instance:t}){Gt(t)}}PB(t=>new jB(t),class{constructor(t,e){ux(this,t)}modify(t,e,n){}});const BB=new class{capabilities=Vr();createModifier(t){return{element:null,instance:t}}installModifier(t,e,n){const r=function(t,e){const n=t;return n.element=e,n}(t,e),{positional:i,named:s}=n,o=t.instance(e,i,s);"function"==typeof o&&(r.teardown=o)}updateModifier(t,e){"function"==typeof t.teardown&&t.teardown();const n=t.instance(t.element,e.positional,e.named);"function"==typeof n&&(t.teardown=n)}destroyModifier(t){"function"==typeof t.teardown&&t.teardown()}getDebugName(t){return t.instance.toString()}getDebugInstance(t){return t}};function UB(t){return t.toString=()=>t.name,PB(()=>BB,t)}const $B=UB((t,[e])=>{const n=n=>{t&&!t.contains(n.target)&&e(n)},r=setTimeout(()=>{document.addEventListener("click",n)},0);return()=>{clearTimeout(r),document.removeEventListener("click",n)}});class qB extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"_forceClear",[Is],function(){return!1})}#Et=void fF(this,"_forceClear");get isSaved(){return this.args.isSaved}get placeListIds(){return this._forceClear?[]:this.args.place._listIds||[]}styleFor(t){return zw(`background-color: ${t}`)}isInList(t){return!!this.placeListIds&&this.placeListIds.includes(t.id)}static{pF(this.prototype,"isInList",[Pu])}async toggleSaved(){if(this.isSaved){const{osmId:t,osmType:e}=this.args.place;if(await this.storage.removePlace(this.args.place),this.args.place&&(this.args.place.id=null,this.args.place.createdAt=null,this.args.place._listIds=[],this._forceClear=!0),t&&e){const t={...this.args.place};delete t.id,delete t.createdAt,delete t._listIds,this.router.transitionTo("place",t)}else this.router.transitionTo("index");this.args.onClose&&this.args.onClose()}else await this.storage.storePlace(this.args.place)}static{pF(this.prototype,"toggleSaved",[Pu])}async toggleList(t){const e=!this.placeListIds.includes(t.id);e&&!this.isSaved&&await this.storage.storePlace(this.args.place);try{await this.storage.togglePlaceList(this.args.place,t.id,e)}catch(ej){console.error(ej),alert("Failed to update list: "+ej.message)}}static{pF(this.prototype,"toggleList",[Pu])}static{Xr(em({id:null,block:'[[[11,0],[24,0,"place-lists-manager"],[4,[32,0],[[30,1]],null],[12],[1,"\\n "],[10,0],[14,0,"list-item master-toggle"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[30,0,["isSaved"]]],[24,4,"checkbox"],[4,[32,1],["change",[30,0,["toggleSaved"]]],null],[12],[13],[1,"\\n "],[10,1],[14,0,"list-color"],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,"Saved places"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"divider"],[12],[13],[1,"\\n\\n "],[10,0],[14,0,"lists-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["storage","lists"]]],null]],null],null,[[[1," "],[10,0],[14,0,"list-item"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[28,[30,0,["isInList"]],[[30,2]],null]],[16,"disabled",[52,[51,[30,0,["isSaved"]]],true]],[24,4,"checkbox"],[4,[32,1],["change",[28,[32,2],[[30,0,["toggleList"]],[30,2]],null]],null],[12],[13],[1,"\\n"],[1," "],[10,1],[14,0,"list-color"],[15,5,[28,[30,0,["styleFor"]],[[30,2,["color"]]],null]],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,[30,2,["title"]]],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n"],[13]],["@onClose","list"],["each","-track-array","unless"]]',moduleName:"/home/basti/src/marco/app/components/place-lists-manager.gjs",scope:()=>[$B,Sb,AB],isStrictMode:!0}),this)}}class VB{assert(){}async(t){Promise.resolve().then(t)}reportUncaughtRejection(){this.async(t=>{throw t})}defer(){let t={promise:null,resolve:null,reject:null},e=new Promise((e,n)=>{t.resolve=e,t.reject=n});return t.promise=e,t}globalDebuggingEnabled(){return!1}}const WB=new VB;class HB{constructor(t){this.maxConcurrency=t||1}}const GB="CANCELLED",KB="STARTED",ZB="QUEUED",YB={type:KB},XB={type:ZB},JB=t=>({type:GB,reason:t}),QB=JB("it belongs to a 'drop' Task that was already running");class tU{constructor(t){this.remainingSlots=t}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):QB}}class eU extends HB{makeReducer(){return new tU(this.maxConcurrency)}}class nU{constructor(t){this.remainingSlots=t}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):XB}}class rU extends HB{makeReducer(){return new nU(this.maxConcurrency)}}const iU=JB("it belongs to a 'keepLatest' Task that was already running");class sU{constructor(t,e){this.remainingSlots=t,this.numToCancel=e}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):this.numToCancel>0?(this.numToCancel--,iU):XB}}class oU extends HB{makeReducer(t,e){let n=t+e;return new sU(this.maxConcurrency,n-this.maxConcurrency-1)}}const aU=JB("it belongs to a 'restartable' Task that was .perform()ed again");class lU{constructor(t){this.numToCancel=t}step(){return this.numToCancel>0?(this.numToCancel--,aU):YB}}class cU extends HB{makeReducer(t,e){return new lU(t+e-this.maxConcurrency)}}const uU=new class{step(){return YB}};class hU{makeReducer(){return uU}}const dU=new Map;class pU{constructor(t,e,n){this.stateTracker=e,this.schedulerPolicy=t,this.initialTaskInstances=n,this.startingInstances=[]}process(){let[t,e,n]=this.filterFinishedTaskInstances(),r=this.schedulerPolicy.makeReducer(e,n),i=t.filter(t=>this.setTaskInstanceExecutionState(t,r.step()));return this.stateTracker.computeFinalStates(t=>this.applyState(t)),this.startingInstances.forEach(t=>t.start()),i}filterFinishedTaskInstances(){let t=0,e=0;return[this.initialTaskInstances.filter(n=>{let r=this.stateTracker.stateFor(n.task),i=n.executor.state;return i.isFinished?(r.onCompletion(n),!1):(i.hasStarted?t+=1:e+=1,!0)}),t,e]}setTaskInstanceExecutionState(t,e){let n=this.stateTracker.stateFor(t.task);switch(t.executor.counted||(t.executor.counted=!0,n.onPerformed(t)),e.type){case GB:return t.cancel(e.reason),!1;case KB:return t.executor.state.hasStarted||(this.startingInstances.push(t),n.onStart(t)),n.onRunning(t),!0;case ZB:return n.onQueued(t),!0}}applyState(t){let{taskable:e}=t;if(!e.onState)return;const{guid:n}=e;if(dU.has(n)&&t.tagt(e))}forEachState(t){this.states.forEach(e=>t(e))}}const yU=new class{onCompletion(){}onPerformed(){}onStart(){}onRunning(){}onQueued(){}};class vU{stateFor(){return yU}computeFinalStates(){}}class bU{constructor(t,e){this.schedulerPolicy=t,this.stateTrackingEnabled=e,this.taskInstances=[]}cancelAll(t,e){let n=this.taskInstances.map(n=>{n.task.guids[t]&&n.executor.cancel(e)}).filter(t=>!!t);return Promise.all(n)}perform(t){t.onFinalize(()=>this.scheduleRefresh()),this.taskInstances.push(t),this.refresh()}scheduleRefresh(){Promise.resolve().then(()=>this.refresh())}refresh(){let t=this.stateTrackingEnabled?new mU:new vU,e=new pU(this.schedulerPolicy,t,this.taskInstances);this.taskInstances=e.process()}}class wU{constructor(t,e,n){this.value=t,this.done=e,this.errored=n}}class _U{constructor(t){this.done=!1,this.generatorFactory=t,this.iterator=null}step(t,e){try{let n=this.getIterator(),{value:r,done:i}=n[e](t);return i?this.finalize(r,!1):new wU(r,!1,!1)}catch(ej){return this.finalize(ej,!0)}}getIterator(){return this.iterator||this.done||(this.iterator=this.generatorFactory()),this.iterator}finalize(t,e){return this.done=!0,this.iterator=null,new wU(t,!0,e)}}const xU="__ec_cancel__",CU="__ec_yieldable__",SU="next",kU="throw",EU="return",TU="cancel";class RU{constructor(t,e){this._taskInstance=t,this._resumeIndex=e}getTaskInstance(){return this._taskInstance}cancel(){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,TU)}next(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,SU,t)}return(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,EU,t)}throw(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,kU,t)}}class MU{constructor(){this[CU]=this[CU].bind(this)}onYield(){}_deferable(){let t={resolve:void 0,reject:void 0};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}_toPromise(){let t=this._deferable(),e={proceed(e,n,r){n==SU||n==EU?t.resolve(r):t.reject(r)}},n=this[CU](e,0);return t.promise[xU]=n,t.promise}then(...t){return this._toPromise().then(...t)}catch(...t){return this._toPromise().catch(...t)}finally(...t){return this._toPromise().finally(...t)}[CU](t,e){let n=new RU(t,e);return this.onYield(n)}}new class extends MU{onYield(){}};const LU={completionState:0,value:null,error:null,isSuccessful:!1,isError:!1,isCanceled:!1,hasStarted:!1,isFinished:!1},IU="TaskCancelation",PU="explicit",AU="lifespan_end";class OU{constructor(t,e){this.kind=t,this.reason=e,this.promise=new Promise(t=>{this.finalize=t})}}const FU="PERFORM_TYPE_DEFAULT",zU="PERFORM_TYPE_UNLINKED",DU="PERFORM_TYPE_LINKED",NU={};let jU=[];class BU{constructor({generatorFactory:t,env:e,debug:n}){this.generatorState=new _U(t),this.state=Object.assign({},LU),this.index=1,this.disposers=[],this.finalizeCallbacks=[],this.env=e,this.debug=n,this.cancelRequest=null}start(){this.state.hasStarted||this.cancelRequest||(this.setState({hasStarted:!0}),this.proceedSync(SU,void 0))}cancel(t){return this.requestCancel(t)?(this.state.hasStarted?this.proceedWithCancelAsync():this.finalizeWithCancel(),this.cancelRequest.promise):(t.finalize(),t.promise)}setState(t){Object.assign(this.state,t),this.taskInstance.setState(this.state)}proceedChecked(t,e,n){this.state.isFinished||this.advanceIndex(t)&&(e===TU?(this.requestCancel(new OU("yielded"),n),this.proceedWithCancelAsync()):this.proceedAsync(e,n))}proceedWithCancelAsync(){this.proceedAsync(EU,NU)}proceedAsync(t,e){this.advanceIndex(this.index),this.env.async(()=>this.proceedSync(t,e))}proceedSync(t,e){this.state.isFinished||(this.dispose(),this.generatorState.done?this.handleResolvedReturnedValue(t,e):this.handleResolvedContinueValue(t,e))}handleResolvedContinueValue(t,e){let n=this.index,r=this.generatorStep(e,t);this.advanceIndex(n)&&(r.errored?this.finalize(r.value,2):this.handleYieldedValue(r))}handleResolvedReturnedValue(t,e){switch(t){case SU:case EU:this.finalize(e,1);break;case kU:this.finalize(e,2)}}handleYieldedUnknownThenable(t){let e=this.index;t.then(t=>{this.proceedChecked(e,SU,t)},t=>{this.proceedChecked(e,kU,t)})}advanceIndex(t){if(this.index===t)return++this.index}handleYieldedValue(t){let e=t.value;e?(this.addDisposer(e[xU]),e[CU]?this.invokeYieldable(e):"function"==typeof e.then?this.handleYieldedUnknownThenable(e):this.proceedWithSimpleValue(e)):this.proceedWithSimpleValue(e)}proceedWithSimpleValue(t){this.proceedAsync(SU,t)}addDisposer(t){"function"==typeof t&&this.disposers.push(t)}dispose(){let t=this.disposers;0!==t.length&&(this.disposers=[],t.forEach(t=>t()))}generatorStep(t,e){jU.push(this);let n=this.generatorState.step(t,e);if(jU.pop(),this._expectsLinkedYield){let t=n.value;t&&t.performType===DU||console.warn("You performed a .linked() task without immediately yielding/returning it. This is currently unsupported (but might be supported in future version of ember-concurrency)."),this._expectsLinkedYield=!1}return n}maybeResolveDefer(){this.defer&&this.state.isFinished&&(1===this.state.completionState?this.defer.resolve(this.state.value):this.defer.reject(this.state.error))}onFinalize(t){this.finalizeCallbacks.push(t),this.state.isFinished&&this.runFinalizeCallbacks()}runFinalizeCallbacks(){this.finalizeCallbacks.forEach(t=>t()),this.finalizeCallbacks=[],this.maybeResolveDefer(),this.maybeThrowUnhandledTaskErrorLater()}promise(){return this.defer||(this.defer=this.env.defer(),this.asyncErrorsHandled=!0,this.maybeResolveDefer()),this.defer.promise}maybeThrowUnhandledTaskErrorLater(){this.asyncErrorsHandled||2!==this.state.completionState||function(t){return t&&t.name===IU}(this.state.error)||this.env.async(()=>{this.asyncErrorsHandled||this.env.reportUncaughtRejection(this.state.error)})}requestCancel(t){return!this.cancelRequest&&!this.state.isFinished&&(this.cancelRequest=t,!0)}finalize(t,e){if(this.cancelRequest)return this.finalizeWithCancel();let n={completionState:e};1===e?(n.isSuccessful=!0,n.value=t):2===e?(n.isError=!0,n.error=t):3===e&&(n.error=t),this.finalizeShared(n)}finalizeWithCancel(){let t=this.taskInstance.formatCancelReason(this.cancelRequest.reason),e=new Error(t);this.debugEnabled()&&console.log(t),e.name=IU,this.finalizeShared({isCanceled:!0,completionState:3,error:e,cancelReason:t}),this.cancelRequest.finalize()}debugEnabled(){return this.debug||this.env.globalDebuggingEnabled()}finalizeShared(t){this.index++,t.isFinished=!0,this.setState(t),this.runFinalizeCallbacks()}invokeYieldable(t){try{let e=t[CU](this.taskInstance,this.index);this.addDisposer(e)}catch(ej){this.env.reportUncaughtRejection(ej)}}onYielded(t,e){this.asyncErrorsHandled=!0,this.onFinalize(()=>{let n=this.state.completionState;1===n?t.proceed(e,SU,this.state.value):2===n?t.proceed(e,kU,this.state.error):3===n&&t.proceed(e,TU,null)});let n=this.getPerformType();if(n!==zU)return()=>{this.detectSelfCancelLoop(n,t),this.cancel(new OU("parent_cancel"))}}getPerformType(){return this.taskInstance.performType||FU}detectSelfCancelLoop(t,e){if(t!==FU)return;let n=e.executor&&e.executor.cancelRequest;!n||n.kind!==AU||this.cancelRequest||this.state.isFinished||this.taskInstance.selfCancelLoopWarning(e)}}const UU={last:null,lastRunning:null,lastPerformed:null,lastSuccessful:null,lastComplete:null,lastErrored:null,lastCanceled:null,lastIncomplete:null,performCount:0};Object.freeze(UU);let $U=0;class qU{constructor(t){this.context=t.context,this.debug=t.debug||!1,this.enabledModifiers=t.enabledModifiers,this.env=t.env,this.group=t.group,this.hasEnabledEvents=t.hasEnabledEvents,this.modifierOptions=t.modifierOptions,this.name=t.name,this.onStateCallback=t.onStateCallback,this.scheduler=t.scheduler,this.guid="ec_"+$U++,this.guids={},this.guids[this.guid]=!0,this.group&&Object.assign(this.guids,this.group.guids)}cancelAll(t){let{reason:e,cancelRequestKind:n,resetState:r}=t||{};e=e||".cancelAll() was explicitly called on the Task";let i=new OU(n||PU,e);return this.scheduler.cancelAll(this.guid,i).then(()=>{r&&this._resetState()})}get _isAlive(){return!0}_resetState(){this.setState(UU)}setState(){}}Object.assign(qU.prototype,UU),Object.assign(qU.prototype,{numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"});class VU{constructor(t,e,n){this.task=t,this.performType=e,this.linkedObject=n}perform(...t){return this.task._performShared(t,this.performType,this.linkedObject)}}let WU=class t extends qU{constructor(t){super(t),this.generatorFactory=t.generatorFactory,this.perform=this._perform.bind(this)}linked(){let t=jU[jU.length-1];if(!t)throw new Error("You can only call .linked() from within a task.");return new VU(this,DU,t)}unlinked(){return new VU(this,zU,null)}toString(){return``}_clone(){return new t({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}_curry(...t){let e=this._clone();return e._curryArgs=[...this._curryArgs||[],...t],e}_perform(...t){return this._performShared(t,FU,null)}_performShared(t,e,n){let r=this._curryArgs?[...this._curryArgs,...t]:t,i=this._taskInstanceFactory(r,e,n);return e===DU&&(n._expectsLinkedYield=!0),this._isAlive||i.cancel(),this.scheduler.perform(i),i}_taskInstanceOptions(t,e,n){return{args:t,executor:new BU({generatorFactory:()=>this.generatorFactory(t),env:this.env,debug:this.debug}),performType:e,hasEnabledEvents:this.hasEnabledEvents}}};const HU={enqueue:(t,e)=>e&&t.setBufferPolicy(rU),debug:(t,e)=>e&&t.setDebug(e),drop:(t,e)=>e&&t.setBufferPolicy(eU),keepLatest:(t,e)=>e&&t.setBufferPolicy(oU),maxConcurrency:(t,e)=>t.setMaxConcurrency(e),onState:(t,e)=>t.setOnState(e),restartable:(t,e)=>e&&t.setBufferPolicy(cU)};let GU=class{env=WB;_debug=null;_enabledModifiers=[];_hasSetConcurrencyConstraint=!1;_hasSetBufferPolicy=!1;_hasEnabledEvents=!1;_maxConcurrency=null;_onStateCallback=(t,e)=>e.setState(t);_schedulerPolicyClass=hU;constructor(t="",e=null,n={}){this.name=t,this.taskDefinition=e,this.options=n,this._processModifierOptions(n)}createTask(t){let e=this.getTaskOptions(t);return new WU(Object.assign({generatorFactory:e=>this.taskDefinition.apply(t,e)},e))}getModifier(t){if(function(t){return t in HU}(t))return HU[t].bind(null,this)}getOptions(){return this.options}getScheduler(t,e){return new bU(t,e)}getTaskOptions(t){let e,n=this._onStateCallback,r=new this._schedulerPolicyClass(this._maxConcurrency);return e=this.getScheduler(r,n&&"function"==typeof n),{context:t,debug:this._debug,env:this.env,name:this.name,group:void 0,scheduler:e,hasEnabledEvents:this._hasEnabledEvents,onStateCallback:n,enabledModifiers:this._enabledModifiers,modifierOptions:this.getOptions()}}setBufferPolicy(t){return function(t){if(t._hasSetBufferPolicy)throw new Error(`Cannot set multiple buffer policies on a task. ${t._schedulerPolicyClass} has already been set for task '${t.name}'`)}(this),this._hasSetBufferPolicy=!0,this._hasSetConcurrencyConstraint=!0,this._schedulerPolicyClass=t,this}setDebug(t){return this._debug=t,this}setEvented(t){return this._hasEnabledEvents=t,this}setMaxConcurrency(t){return this._hasSetConcurrencyConstraint=!0,this._maxConcurrency=t,this}setName(t){return this.name=t,this}setOnState(t){return this._onStateCallback=t,this}setTaskDefinition(t){return this.taskDefinition=t,this}_processModifierOptions(t){if(t)for(let e of Object.keys(t)){let n=t[e],r=this.getModifier(e);"function"==typeof r&&r(n)&&this._enabledModifiers.push(e)}}};const KU=new class extends VB{assert(...t){}async(t){va(()=>wa("actions",t))}reportUncaughtRejection(t){Sa(null,function(){const e=ko();if(!e)throw t;e(t)})}defer(){return $c()}globalDebuggingEnabled(){return!1}};class ZU extends bU{scheduleRefresh(){xa(this,this.refresh)}}class YU{constructor({task:t,args:e,executor:n,performType:r,hasEnabledEvents:i}){this.task=t,this.args=e,this.performType=r,this.executor=n,this.executor.taskInstance=this,this.hasEnabledEvents=i}setState(){}formatCancelReason(){}selfCancelLoopWarning(){}onFinalize(t){this.executor.onFinalize(t)}proceed(t,e,n){this.executor.proceedChecked(t,e,n)}[CU](t,e){return this.executor.onYielded(t,e)}cancel(t=".cancel() was explicitly called"){this.executor.cancel(new OU(PU,t))}then(...t){return this.executor.promise().then(...t)}catch(...t){return this.executor.promise().catch(...t)}finally(...t){return this.executor.promise().finally(...t)}toString(){return`${this.task} TaskInstance`}start(){return this.executor.start(),this}}function XU(t,e){return Object.keys(t).reduce((e,n)=>function(t,e,n){const r=Object.getOwnPropertyDescriptor(t,n);r.initializer=r.initializer||(()=>t[n]),delete r.value;const i=Is(e,n,r);return e[n]=i,e}(t,e,n),e)}let JU,QU;Object.assign(YU.prototype,LU),Object.assign(YU.prototype,{state:"waiting",isDropped:!1,isRunning:!0}),JU=XU(UU,{}),JU=XU({numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"},JU),QU=XU(LU,{}),QU=XU({state:"waiting",isDropped:!1,isRunning:!1},QU),Object.freeze(JU),Object.freeze(QU);class t$ extends YU{setState(t){let e=this._recomputeState(t);Object.assign(this,{...t,isRunning:!t.isFinished,isDropped:"dropped"===e,state:e})}_recomputeState(t){return t.isDropped?"dropped":t.isCanceled?t.hasStarted?"canceled":"dropped":t.isFinished?"finished":t.hasStarted?"running":"waiting"}formatCancelReason(t){return`TaskInstance '${this.getName()}' was canceled because ${t}. For more information, see: http://ember-concurrency.com/docs/task-cancelation-help`}getName(){return this.name||(this.name=this.task&&this.task.name||""),this.name}selfCancelLoopWarning(t){let e=`\`${t.getName()}\``,n=`\`${this.getName()}\``;console.warn(`ember-concurrency detected a potentially hazardous "self-cancel loop" between parent task ${e} and child task ${n}. If you want child task ${n} to be canceled when parent task ${e} is canceled, please change \`.perform()\` to \`.linked().perform()\`. If you want child task ${n} to keep running after parent task ${e} is canceled, change it to \`.unlinked().perform()\``)}triggerEvent(...t){if(!this.hasEnabledEvents)return;let e=this.task,n=e.context,r=e&&e.name;if(n&&n.trigger&&r){let[e,...i]=t;n.trigger(`${r}:${e}`,...i)}}}QU&&Object.defineProperties(t$.prototype,QU);const e$={_performCount:0,setState(t){this._performCount=this._performCount+(t.numPerformedInc||0);let e=t.numRunning>0,n=t.numQueued>0,r=Object.assign({},t,{performCount:this._performCount,isRunning:e,isQueued:n,isIdle:!e&&!n,state:e?"running":"idle"});Object.assign(this,r)},onState(t,e){e.onStateCallback&&e.onStateCallback(t,e)}};class n$ extends WU{constructor(t){super(t),Zt(this.context)||_x(this.context,()=>{this.cancelAll({reason:"the object it lives on was destroyed or unrendered",cancelRequestKind:AU})})}get _isAlive(){return!Zt(this.context)}_taskInstanceFactory(t,e,n){let r=this._taskInstanceOptions(t,e,n);return r.task=this,new t$(r)}_clone(){return new n$({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}}JU&&Object.defineProperties(n$.prototype,JU),Object.assign(n$.prototype,e$);class r$ extends GU{env=KU;createTask(t){this.taskDefinition;let e=this.getTaskOptions(t);return new n$(Object.assign({generatorFactory:e=>this.taskDefinition.apply(t,e)},e))}getModifier(t){return super.getModifier(t)}getScheduler(t,e){return new ZU(t,e)}get taskFn(){return this.taskDefinition}set taskFn(t){this.setTaskDefinition(t)}}function i$(t,e,n){let r=e;const i=t();return new r$(n||"",i.generator,r).createTask(i.context)}class s$ extends LB{renderBlurhash=UB((t,[e,n,r])=>{if(!e||!t)return;const i=n||32,s=r||18;t.width=i,t.height=s;const o=t.getContext("2d");if(o)try{const t=((t,e,n)=>{(t=>{if(!t||t.length<6)throw new sB("The blurhash string must be at least 6 characters");let e=tB(t[0]),n=Math.floor(e/9)+1,r=e%9+1;if(t.length!==4+2*r*n)throw new sB(`blurhash length mismatch: length is ${t.length} but it should be ${4+2*r*n}`)})(t);let r=tB(t[0]),i=Math.floor(r/9)+1,s=r%9+1,o=(tB(t[1])+1)/166,a=new Array(s*i);for(let u=0;u({context:this,generator:function*(t){this.error="";try{const e=yield this.imageProcessor.process(t,1920,.94,!0);this.blurhash=e.blurhash;const n=yield this.imageProcessor.process(t,350,.9,!1);let r,i;if(bz())r=yield this.blossom.upload(e.blob,{sequential:!0}),i=yield this.blossom.upload(n.blob,{sequential:!0});else{const t=this.blossom.upload(e.blob),s=this.blossom.upload(n.blob);[r,i]=yield Promise.all([t,s])}this.args.onSuccess&&this.args.onSuccess({file:t,url:r.url,fallbackUrls:r.fallbackUrls,thumbUrl:i.url,blurhash:e.blurhash,type:"image/jpeg",dim:e.dim,hash:r.hash,thumbHash:i.hash})}catch(ej){this.error=ej.message}}}),null,"uploadTask");static{Xr(em({id:null,block:'[[[10,0],[15,0,[29,["photo-upload-item\\n ",[52,[30,0,["uploadTask","isRunning"]],"is-uploading"],"\\n ",[52,[30,0,["error"]],"has-error"]]]],[12],[1,"\\n"],[41,[30,0,["blurhash"]],[[[1," "],[8,[32,0],[[24,0,"place-header-photo-blur"]],[["@hash"],[[30,0,["blurhash"]]]],null],[1,"\\n"]],[]],null],[1," "],[10,"img"],[15,"src",[30,0,["thumbnailUrl"]]],[14,"alt","thumbnail"],[12],[13],[1,"\\n\\n"],[41,[30,0,["uploadTask","isRunning"]],[[[1," "],[10,0],[14,0,"overlay"],[12],[1,"\\n "],[8,[32,1],[[24,0,"spin-animation"]],[["@name","@size","@color"],["loading-ring",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["error"]],[[[1," "],[11,"button"],[24,0,"overlay error-overlay"],[16,"title",[30,0,["error"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["showErrorToast"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["alert-circle",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[11,"button"],[24,0,"btn-remove-photo"],[24,"title","Remove photo"],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,1],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",16,"white"]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onRemove","@file"],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload-item.gjs",scope:()=>[s$,DB,Sb,AB],isStrictMode:!0}),this)}}class a$ extends Mw{compute(t){for(let e=0,n=t.length;e!OB(t))}class c$ extends LB{static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"blossom",[$f])}#Tt=void fF(this,"blossom");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");static{dF(this.prototype,"file",[Is],function(){return null})}#At=void fF(this,"file");static{dF(this.prototype,"uploadedPhoto",[Is],function(){return null})}#Ot=void fF(this,"uploadedPhoto");static{dF(this.prototype,"status",[Is],function(){return""})}#Ft=void fF(this,"status");static{dF(this.prototype,"error",[Is],function(){return""})}#Pt=void fF(this,"error");static{dF(this.prototype,"isPublishing",[Is],function(){return!1})}#zt=void fF(this,"isPublishing");static{dF(this.prototype,"isDragging",[Is],function(){return!1})}#Dt=void fF(this,"isDragging");get place(){return this.args.place||{}}get title(){return this.place.title||"this place"}get allUploaded(){return this.file&&this.uploadedPhoto&&this.file===this.uploadedPhoto.file}handleFileSelect(t){this.addFile(t.target.files[0]),t.target.value=""}static{pF(this.prototype,"handleFileSelect",[Pu])}handleDragOver(t){t.preventDefault(),this.isDragging=!0}static{pF(this.prototype,"handleDragOver",[Pu])}handleDragLeave(t){t.preventDefault(),this.isDragging=!1}static{pF(this.prototype,"handleDragLeave",[Pu])}handleDrop(t){t.preventDefault(),this.isDragging=!1,t.dataTransfer.files.length>0&&this.addFile(t.dataTransfer.files[0])}static{pF(this.prototype,"handleDrop",[Pu])}addFile(t){t&&t.type.startsWith("image/")?(this.error="",this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=t,this.uploadedPhoto=null):this.error="Please select a valid image file."}handleUploadSuccess(t){this.uploadedPhoto=t}static{pF(this.prototype,"handleUploadSuccess",[Pu])}removeFile(){this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=null,this.uploadedPhoto=null}static{pF(this.prototype,"removeFile",[Pu])}deletePhotoTask=i$(()=>({context:this,generator:function*(t){try{t.hash&&(yield this.blossom.delete(t.hash)),t.thumbHash&&(yield this.blossom.delete(t.thumbHash))}catch(ej){this.toast.show(`Failed to delete photo from server: ${ej.message}`,5e3)}}}),null,"deletePhotoTask");async publish(){if(!this.nostrAuth.isConnected)return void(this.error="You must connect Nostr first.");if(!this.allUploaded)return void(this.error="Please wait for all photos to finish uploading.");const{osmId:t,lat:e,lon:n}=this.place,r=this.place.osmType||"node";if(t){this.status="Publishing event...",this.error="",this.isPublishing=!0;try{const i=new kO({signer:this.nostrAuth.signer}),s=[["i",`osm:${r}:${t}`]];e&&n&&(s.push(["g",DD.encode(e,n,4)]),s.push(["g",DD.encode(e,n,6)]),s.push(["g",DD.encode(e,n,7)]),s.push(["g",DD.encode(e,n,9)]));const o=this.uploadedPhoto,a=["imeta",`url ${o.url}`];if(a.push(`m ${o.type}`),o.dim&&a.push(`dim ${o.dim}`),a.push("alt A photo of a place"),o.fallbackUrls&&o.fallbackUrls.length>0)for(const t of o.fallbackUrls)a.push(`fallback ${t}`);o.thumbUrl&&a.push(`thumb ${o.thumbUrl}`),o.blurhash&&a.push(`blurhash ${o.blurhash}`),s.push(a);const l={kind:360,content:"",tags:s};l.created_at||(l.created_at=Math.floor(Date.now()/1e3));const c=await i.sign(l);await this.nostrRelay.publish(this.nostrData.activeWriteRelays,c),this.nostrData.store.add(c),this.toast.show("Photo published successfully"),this.status="",this.file=null,this.uploadedPhoto=null,this.args.onClose&&this.args.onClose(c.id)}catch(ej){this.error="Failed to publish: "+ej.message,this.status=""}finally{this.isPublishing=!1}}else this.error="This place does not have a valid OSM ID."}static{pF(this.prototype,"publish",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"place-photo-upload"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Add Photo for "],[1,[30,0,["title"]]],[13],[1,"\\n\\n"],[41,[30,0,["error"]],[[[1," "],[10,0],[14,0,"alert alert-error"],[12],[1,"\\n "],[1,[30,0,["error"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["status"]],[[[1," "],[10,0],[14,0,"alert alert-info"],[12],[1,"\\n "],[1,[30,0,["status"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["file"]],[[[1," "],[10,0],[14,0,"photo-grid"],[12],[1,"\\n "],[8,[32,0],null,[["@file","@onSuccess","@onRemove"],[[30,0,["file"]],[30,0,["handleUploadSuccess"]],[30,0,["removeFile"]]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"button"],[24,0,"btn btn-primary btn-publish"],[16,"disabled",[28,[32,1],[[28,[32,2],[[30,0,["allUploaded"]]],null],[30,0,["isPublishing"]]],null]],[24,4,"button"],[4,[32,3],["click",[30,0,["publish"]]],null],[12],[1,"\\n"],[41,[30,0,["isPublishing"]],[[[1," Publishing...\\n"]],[]],[[[1," Publish Photo\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],[[[1," "],[11,0],[16,0,[29,["dropzone ",[52,[30,0,["isDragging"]],"is-dragging"]]]],[4,[32,3],["dragover",[30,0,["handleDragOver"]]],null],[4,[32,3],["dragleave",[30,0,["handleDragLeave"]]],null],[4,[32,3],["drop",[30,0,["handleDrop"]]],null],[12],[1,"\\n "],[10,"label"],[14,"for","photo-upload-input"],[14,0,"dropzone-label"],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size","@color"],["upload-cloud",48,"#ccc"]],null],[1,"\\n "],[10,2],[12],[1,"Drag and drop a photo here, or click to browse"],[13],[1,"\\n "],[13],[1,"\\n "],[11,"input"],[24,1,"photo-upload-input"],[24,"accept","image/*"],[24,0,"file-input-hidden"],[16,"disabled",[30,0,["isPublishing"]]],[24,4,"file"],[4,[32,3],["change",[30,0,["handleFileSelect"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload.gjs",scope:()=>[o$,FB,l$,Sb,DB],isStrictMode:!0}),this)}}var u$,h$,d$={};function p$(){return h$?u$:(h$=1,u$=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then})}var f$,g$={},m$={};function y$(){if(f$)return m$;let t;f$=1;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return m$.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17},m$.getSymbolTotalCodewords=function(t){return e[t]},m$.getBCHDigit=function(t){let e=0;for(;0!==t;)e++,t>>>=1;return e},m$.setToSJISFunction=function(e){if("function"!=typeof e)throw new Error('"toSJISFunc" is not a valid function.');t=e},m$.isKanjiModeEnabled=function(){return void 0!==t},m$.toSJIS=function(e){return t(e)},m$}var v$,b$,w$,_$,x$,C$={};function S$(){return v$||(v$=1,(t=C$).L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2},t.isValid=function(t){return t&&void 0!==t.bit&&t.bit>=0&&t.bit<4},t.from=function(e,n){if(t.isValid(e))return e;try{return function(e){if("string"!=typeof e)throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+e)}}(e)}catch(ej){return n}}),C$;var t}var k$,E$,T$,R$,M$={},L$={},I$={},P$={};function A$(){if(R$)return P$;R$=1;const t=S$(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return P$.getBlocksCount=function(n,r){switch(r){case t.L:return e[4*(n-1)+0];case t.M:return e[4*(n-1)+1];case t.Q:return e[4*(n-1)+2];case t.H:return e[4*(n-1)+3];default:return}},P$.getTotalCodewordsCount=function(e,r){switch(r){case t.L:return n[4*(e-1)+0];case t.M:return n[4*(e-1)+1];case t.Q:return n[4*(e-1)+2];case t.H:return n[4*(e-1)+3];default:return}},P$}var O$,F$,z$,D$,N$,j$={},B$={},U$={},$$={},q$={};function V$(){return N$||(N$=1,q$.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),q$}var W$,H$,G$,K$={};function Z$(){if(W$)return K$;W$=1;const t="[0-9]+";let e="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";e=e.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+e+")(?:.|[\r\n]))+";K$.KANJI=new RegExp(e,"g"),K$.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),K$.BYTE=new RegExp(n,"g"),K$.NUMERIC=new RegExp(t,"g"),K$.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const r=new RegExp("^"+e+"$"),i=new RegExp("^"+t+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return K$.testKanji=function(t){return r.test(t)},K$.testNumeric=function(t){return i.test(t)},K$.testAlphanumeric=function(t){return s.test(t)},K$}function Y$(){return H$||(H$=1,function(t){const e=V$(),n=Z$();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(t,n){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!e.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?t.ccBits[0]:n<27?t.ccBits[1]:t.ccBits[2]},t.getBestModeForData=function(e){return n.testNumeric(e)?t.NUMERIC:n.testAlphanumeric(e)?t.ALPHANUMERIC:n.testKanji(e)?t.KANJI:t.BYTE},t.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")},t.isValid=function(t){return t&&t.bit&&t.ccBits},t.from=function(e,n){if(t.isValid(e))return e;try{return function(e){if("string"!=typeof e)throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+e)}}(e)}catch(ej){return n}}}($$)),$$}var X$,J$,Q$,tq,eq,nq,rq,iq,sq,oq,aq,lq,cq={},uq={},hq={exports:{}};function dq(){return oq||(oq=1,function(t){var e={single_source_shortest_paths:function(t,n,r){var i={},s={};s[n]=0;var o,a,l,c,u,h,d,p=e.PriorityQueue.make();for(p.push(n,0);!p.empty();)for(l in a=(o=p.pop()).value,c=o.cost,u=t[a]||{})u.hasOwnProperty(l)&&(h=c+u[l],d=s[l],(void 0===s[l]||d>h)&&(s[l]=h,p.push(l,h),i[l]=a));if(void 0!==r&&void 0===s[r]){var f=["Could not find a path from ",n," to ",r,"."].join("");throw new Error(f)}return i},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e;r;)n.push(r),t[r],r=t[r];return n.reverse(),n},find_path:function(t,n,r){var i=e.single_source_shortest_paths(t,n,r);return e.extract_shortest_path_from_predecessor_list(i,r)},PriorityQueue:{make:function(t){var n,r=e.PriorityQueue,i={};for(n in t=t||{},r)r.hasOwnProperty(n)&&(i[n]=r[n]);return i.queue=[],i.sorter=t.sorter||r.default_sorter,i},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};t.exports=e}(hq)),hq.exports}function pq(){if(lq)return g$;lq=1;const t=y$(),e=S$(),n=function(){if(w$)return b$;function t(){this.buffer=[],this.length=0}return w$=1,t.prototype={get:function(t){const e=Math.floor(t/8);return 1==(this.buffer[e]>>>7-t%8&1)},put:function(t,e){for(let n=0;n>>e-n-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}},b$=t}(),r=function(){if(x$)return _$;function t(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return x$=1,t.prototype.set=function(t,e,n,r){const i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)},t.prototype.get=function(t,e){return this.data[t*this.size+e]},t.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n},t.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]},_$=t}(),i=(k$||(k$=1,function(t){const e=y$().getSymbolSize;t.getRowColCoords=function(t){if(1===t)return[];const n=Math.floor(t/7)+2,r=e(t),i=145===r?26:2*Math.ceil((r-13)/(2*n-2)),s=[r-7];for(let e=1;e=0&&t<=7},t.from=function(e){return t.isValid(e)?parseInt(e,10):void 0},t.getPenaltyN1=function(t){const e=t.size;let n=0,r=0,i=0,s=null,o=null;for(let a=0;a=5&&(n+=r-5+3),s=e,r=1),e=t.get(l,a),e===o?i++:(i>=5&&(n+=i-5+3),o=e,i=1)}r>=5&&(n+=r-5+3),i>=5&&(n+=i-5+3)}return n},t.getPenaltyN2=function(t){const e=t.size;let n=0;for(let r=0;r=10&&(1488===r||93===r)&&n++,i=i<<1&2047|t.get(o,s),o>=10&&(1488===i||93===i)&&n++}return 40*n},t.getPenaltyN4=function(t){let e=0;const n=t.data.length;for(let r=0;r=0;){const t=r[0];for(let s=0;s0){const t=new Uint8Array(this.degree);return t.set(r,i),t}return r},z$=e}(),c=(G$||(G$=1,function(t){const e=y$(),n=A$(),r=S$(),i=Y$(),s=V$(),o=e.getBCHDigit(7973);function a(t,e){return i.getCharCountIndicator(t,e)+4}function l(t,e){let n=0;return t.forEach(function(t){const r=a(t.mode,e);n+=r+t.getBitsLength()}),n}t.from=function(t,e){return s.isValid(t)?parseInt(t,10):e},t.getCapacity=function(t,r,o){if(!s.isValid(t))throw new Error("Invalid QR Code version");void 0===o&&(o=i.BYTE);const l=8*(e.getSymbolTotalCodewords(t)-n.getTotalCodewordsCount(t,r));if(o===i.MIXED)return l;const c=l-a(o,t);switch(o){case i.NUMERIC:return Math.floor(c/10*3);case i.ALPHANUMERIC:return Math.floor(c/11*2);case i.KANJI:return Math.floor(c/13);case i.BYTE:default:return Math.floor(c/8)}},t.getBestVersionForData=function(e,n){let s;const o=r.from(n,r.M);if(Array.isArray(e)){if(e.length>1)return function(e,n){for(let r=1;r<=40;r++)if(l(e,r)<=t.getCapacity(r,n,i.MIXED))return r}(e,o);if(0===e.length)return 1;s=e[0]}else s=e;return function(e,n,r){for(let i=1;i<=40;i++)if(n<=t.getCapacity(i,r,e))return i}(s.mode,s.getLength(),o)},t.getEncodedBits=function(t){if(!s.isValid(t)||t<7)throw new Error("Invalid QR Code version");let n=t<<12;for(;e.getBCHDigit(n)-o>=0;)n^=7973<=0;)s^=1335<0&&(n=this.data.substr(e),r=parseInt(n,10),t.put(r,3*i+1))},J$=e}(),r=function(){if(eq)return tq;eq=1;const t=Y$(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(e){this.mode=t.ALPHANUMERIC,this.data=e}return n.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=45*e.indexOf(this.data[n]);r+=e.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(e.indexOf(this.data[n]),6)},tq=n}(),i=function(){if(rq)return nq;rq=1;const t=Y$();function e(e){this.mode=t.BYTE,this.data="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e)}return e.getBitsLength=function(t){return 8*t},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(t){for(let e=0,n=this.data.length;e=33088&&r<=40956)r-=33088;else{if(!(r>=57408&&r<=60351))throw new Error("Invalid SJIS character: "+this.data[n]+"\nMake sure your charset is UTF-8");r-=49472}r=192*(r>>>8&255)+(255&r),t.put(r,13)}},iq=n}(),o=Z$(),a=y$(),l=dq();function c(t){return unescape(encodeURIComponent(t)).length}function u(t,e,n){const r=[];let i;for(;null!==(i=t.exec(n));)r.push({data:i[0],index:i.index,mode:e,length:i[0].length});return r}function h(t){const n=u(o.NUMERIC,e.NUMERIC,t),r=u(o.ALPHANUMERIC,e.ALPHANUMERIC,t);let i,s;return a.isKanjiModeEnabled()?(i=u(o.BYTE,e.BYTE,t),s=u(o.KANJI,e.KANJI,t)):(i=u(o.BYTE_KANJI,e.BYTE,t),s=[]),n.concat(r,i,s).sort(function(t,e){return t.index-e.index}).map(function(t){return{data:t.data,mode:t.mode,length:t.length}})}function d(t,o){switch(o){case e.NUMERIC:return n.getBitsLength(t);case e.ALPHANUMERIC:return r.getBitsLength(t);case e.KANJI:return s.getBitsLength(t);case e.BYTE:return i.getBitsLength(t)}}function p(t,o){let l;const c=e.getBestModeForData(t);if(l=e.from(o,c),l!==e.BYTE&&l.bit=0?t[t.length-1]:null;return n&&n.mode===e.mode?(t[t.length-1].data+=e.data,t):(t.push(e),t)},[]))},t.rawSplit=function(e){return t.fromArray(h(e,a.isKanjiModeEnabled()))}}(uq)),uq);function p(t,e,n){const r=t.size,i=u.getEncodedBits(e,n);let s,o;for(s=0;s<15;s++)o=1==(i>>s&1),s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(r-15+s,8,o,!0),s<8?t.set(8,r-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(r-8,8,1,!0)}return g$.create=function(u,f){if(void 0===u||""===u)throw new Error("No input text");let g,m,y=e.M;return void 0!==f&&(y=e.from(f.errorCorrectionLevel,e.M),g=c.from(f.version),m=o.from(f.maskPattern),f.toSJISFunc&&t.setToSJISFunction(f.toSJISFunc)),function(e,u,f,g){let m;if(Array.isArray(e))m=d.fromArray(e);else{if("string"!=typeof e)throw new Error("Invalid data");{let t=u;if(!t){const n=d.rawSplit(e);t=c.getBestVersionForData(n,f)}m=d.fromString(e,t||40)}}const y=c.getBestVersionForData(m,f);if(!y)throw new Error("The amount of data is too big to be stored in a QR Code");if(u){if(u=0&&r<=6&&(0===i||6===i)||i>=0&&i<=6&&(0===r||6===r)||r>=2&&r<=4&&i>=2&&i<=4?t.set(e+r,s+i,!0,!0):t.set(e+r,s+i,!1,!0))}}(w,u),function(t){const e=t.size;for(let n=8;n=7&&function(t,e){const n=t.size,r=c.getEncodedBits(e);let i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+n-8-3,o=1==(r>>a&1),t.set(i,s,o,!0),t.set(s,i,o,!0)}(w,u),function(t,e){const n=t.size;let r=-1,i=n-1,s=7,o=0;for(let a=n-1;a>0;a-=2)for(6===a&&a--;;){for(let n=0;n<2;n++)if(!t.isReserved(i,a-n)){let r=!1;o>>s&1)),t.set(i,a-n,r),s--,-1===s&&(o++,s=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}(w,v),isNaN(g)&&(g=o.getBestMask(w,p.bind(null,w,f))),o.applyMask(g,w),p(w,f,g),{modules:w,version:u,errorCorrectionLevel:f,maskPattern:g,segments:m}}(u,g,y,m)},g$}var fq,gq,mq={},yq={};function vq(){return fq||(fq=1,function(t){function e(t){if("number"==typeof t&&(t=t.toString()),"string"!=typeof t)throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||5===e.length||e.length>8)throw new Error("Invalid hex color: "+t);3!==e.length&&4!==e.length||(e=Array.prototype.concat.apply([],e.map(function(t){return[t,t]}))),6===e.length&&e.push("F","F");const n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:255&n,hex:"#"+e.slice(0,6).join("")}}t.getOptions=function(t){t||(t={}),t.color||(t.color={});const n=void 0===t.margin||null===t.margin||t.margin<0?4:t.margin,r=t.width&&t.width>=21?t.width:void 0,i=t.scale||4;return{width:r,scale:r?4:i,margin:n,color:{dark:e(t.color.dark||"#000000ff"),light:e(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}},t.getScale=function(t,e){return e.width&&e.width>=t+2*e.margin?e.width/(t+2*e.margin):e.scale},t.getImageWidth=function(e,n){const r=t.getScale(e,n);return Math.floor((e+2*n.margin)*r)},t.qrToImageData=function(e,n,r){const i=n.modules.size,s=n.modules.data,o=t.getScale(i,r),a=Math.floor((i+2*r.margin)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let t=0;t=l&&n>=l&&t':"",h="0&&c>0&&t[l-1]||(i+=o?n("M",c+r,.5+u+r):n("m",s,0),s=0,o=!1),c+1',d='viewBox="0 0 '+c+" "+c+'"',p=''+u+h+"\n";return"function"==typeof s&&s(null,p),p},_q}();function i(n,r,i,s,o){const a=[].slice.call(arguments,1),l=a.length,c="function"==typeof a[l-1];if(!c&&!t())throw new Error("Callback required as last argument");if(!c){if(l<1)throw new Error("Too few arguments provided");return 1===l?(i=r,r=s=void 0):2!==l||r.getContext||(s=i,i=r,r=void 0),new Promise(function(t,o){try{const o=e.create(i,s);t(n(o,r,s))}catch(ej){o(ej)}})}if(l<2)throw new Error("Too few arguments provided");2===l?(o=i,i=r,r=s=void 0):3===l&&(r.getContext&&void 0===o?(o=s,s=void 0):(o=s,s=i,i=r,r=void 0));try{const t=e.create(i,s);o(null,n(t,r,s))}catch(ej){o(ej)}}return d$.create=e.create,d$.toCanvas=i.bind(null,n.render),d$.toDataURL=i.bind(null,n.renderToDataURL),d$.toString=i.bind(null,function(t,e,n){return r.render(t,n)}),d$}();const Cq=BA(xq),Sq=UB((t,[e])=>{e&&Cq.toCanvas(t,e,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).catch(t=>{console.error("Failed to generate QR code",t)})});class kq extends LB{static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");get hasExtension(){return"undefined"!=typeof window&&void 0!==window.nostr}async connectExtension(){try{await this.nostrAuth.connectWithExtension(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(ej){console.error(ej),alert(ej.message)}}static{pF(this.prototype,"connectExtension",[Pu])}async connectApp(){try{await this.nostrAuth.connectWithApp(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(ej){console.error(ej),alert(ej.message)}}static{pF(this.prototype,"connectApp",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"nostr-connect-modal"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Connect with Nostr"],[13],[1,"\\n\\n "],[10,0],[14,0,"nostr-connect-options"],[12],[1,"\\n"],[41,[30,0,["hasExtension"]],[[[1," "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectExtension"]]],null],[12],[1,"\\n Browser Extension (nos2x, Alby)\\n "],[13],[1,"\\n"]],[]],[[[1," "],[10,"button"],[14,0,"btn btn-outline"],[14,"disabled",""],[14,"title","No Nostr extension found in your browser."],[14,4,"button"],[12],[1,"\\n Browser Extension (Not Found)\\n "],[13],[1,"\\n"]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectApp"]]],null],[12],[1,"\\n Mobile Signer App (Amber, etc.)\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[28,[32,1],[[30,0,["nostrAuth","connectStatus"]],"waiting"],null],[[[1," "],[10,0],[14,0,"nostr-connect-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isMobile"]],[[[1," "],[10,2],[12],[1,"Waiting for you to approve the connection in your mobile signer\\n app..."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[12],[1,"Scan this QR code with a compatible Nostr signer app (like\\n Amber):"],[13],[1,"\\n "],[10,0],[14,0,"qr-code-container"],[12],[1,"\\n "],[11,"canvas"],[4,[32,2],[[30,0,["nostrAuth","connectUri"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],null],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/nostr-connect.gjs",scope:()=>[Sb,zB,Sq],isStrictMode:!0}),this)}}class Eq extends LB{stopProp(t){t.stopPropagation()}static{pF(this.prototype,"stopProp",[Pu])}close(){this.args.onClose&&this.args.onClose()}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[11,0],[24,0,"modal-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[11,0],[24,0,"modal-content"],[24,"role","document"],[24,"tabindex","0"],[4,[32,0],["click",[30,0,["stopProp"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"close-modal-btn btn-text"],[24,4,"button"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["x",24]],null],[1,"\\n "],[13],[1,"\\n "],[18,1,null],[1,"\\n "],[13],[1,"\\n"],[13]],["&default"],["yield"]]',moduleName:"/home/basti/src/marco/app/components/modal.gjs",scope:()=>[Sb,DB],isStrictMode:!0}),this)}}const Tq=UB((t,[e])=>{if(!e)return;let n;t.classList.remove("loaded"),t.classList.remove("loaded-instant");const r=()=>{t.classList.contains("loaded-instant")||t.classList.add("loaded")};return t.addEventListener("load",r),n=new IntersectionObserver((n,r)=>{n.forEach(n=>{if(n.isIntersecting){r.unobserve(t);const n=new Image;n.src=e,n.complete&&t.classList.add("loaded-instant");const i=t.parentElement;i&&"PICTURE"===i.tagName&&i.querySelectorAll("source").forEach(t=>{t.dataset.srcset&&(t.srcset=t.dataset.srcset)}),t.dataset.src?t.src=t.dataset.src:t.src=e}})},{root:null,rootMargin:"100px 100%",threshold:0}),n.observe(t),()=>{t.removeEventListener("load",r),n&&n.disconnect()}});class Rq extends LB{static{dF(this.prototype,"canScrollLeft",[Is],function(){return!1})}#Nt=void fF(this,"canScrollLeft");static{dF(this.prototype,"canScrollRight",[Is],function(){return!1})}#jt=void fF(this,"canScrollRight");carouselElement=null;get photos(){return this.args.photos||[]}get showChevrons(){return this.photos.length>1}get cannotScrollLeft(){return!this.canScrollLeft}get cannotScrollRight(){return!this.canScrollRight}lastResetKey=null;resetScrollPosition=UB((t,[e])=>{void 0!==e&&e!==this.lastResetKey&&(this.lastResetKey=e,t.scrollLeft=0,setTimeout(()=>this.updateScrollState(),50))});scrollToNewPhoto=UB((t,[e])=>{e&&e!==this.lastEventId&&(this.lastEventId=e,setTimeout(()=>{const n=t.querySelector(`[data-event-id="${e}"]`);n&&(t.scrollLeft=n.offsetLeft)},100))});setupCarousel=UB(t=>{let e;return this.carouselElement=t,setTimeout(()=>{this.updateScrollState()},50),window.ResizeObserver&&(e=new ResizeObserver(()=>this.updateScrollState()),e.observe(t)),()=>{e&&e.unobserve(t)}});updateScrollState(){if(!this.carouselElement)return;const{scrollLeft:t,scrollWidth:e,clientWidth:n}=this.carouselElement;this.canScrollLeft=t>1,this.canScrollRight=t+n[Sb,s$,Tq,DB],isStrictMode:!0}),this)}}class Mq extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isEditing",[Is],function(){return!1})}#Bt=void fF(this,"isEditing");static{dF(this.prototype,"showLists",[Is],function(){return!1})}#Ut=void fF(this,"showLists");static{dF(this.prototype,"isPhotoUploadModalOpen",[Is],function(){return!1})}#$t=void fF(this,"isPhotoUploadModalOpen");static{dF(this.prototype,"isNostrConnectModalOpen",[Is],function(){return!1})}#qt=void fF(this,"isNostrConnectModalOpen");static{dF(this.prototype,"newlyUploadedPhotoId",[Is],function(){return null})}#Vt=void fF(this,"newlyUploadedPhotoId");openPhotoUploadModal(t){t&&t.preventDefault(),this.nostrAuth.isConnected?this.isPhotoUploadModalOpen=!0:this.isNostrConnectModalOpen=!0}static{pF(this.prototype,"openPhotoUploadModal",[Pu])}closePhotoUploadModal(t){this.isPhotoUploadModalOpen=!1,"string"==typeof t&&(this.newlyUploadedPhotoId=t,setTimeout(()=>{const t=document.querySelector(".sidebar-content");t&&(t.scrollTop=0)},50))}static{pF(this.prototype,"closePhotoUploadModal",[Pu])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{pF(this.prototype,"closeNostrConnectModal",[Pu])}onNostrConnected(){this.isNostrConnectModalOpen=!1,this.isPhotoUploadModalOpen=!0}static{pF(this.prototype,"onNostrConnected",[Pu])}get isSaved(){return this.storage.isPlaceSaved(this.place.id||this.place.osmId)}get place(){return this.args.place||{}}get saveablePlace(){return this.place.createdAt?this.place:Zj(this.place)}get tags(){return this.place.osmTags||{}}get name(){return this.place.title||RN(this.tags)||"Unnamed Place"}get photos(){return OD(this.nostrData.placePhotos).map(t=>({...t,style:zw(`--slide-ratio: ${t.aspectRatio};`)}))}startEditing(){this.isSaved&&(this.isEditing=!0)}static{pF(this.prototype,"startEditing",[Pu])}cancelEditing(){this.isEditing=!1}static{pF(this.prototype,"cancelEditing",[Pu])}toggleLists(t){t&&t.stopPropagation(),this.showLists=!this.showLists}static{pF(this.prototype,"toggleLists",[Pu])}closeLists(){this.showLists=!1}static{pF(this.prototype,"closeLists",[Pu])}async saveChanges(t){this.args.onSave&&await this.args.onSave({...this.place,...t}),this.isEditing=!1}static{pF(this.prototype,"saveChanges",[Pu])}get type(){return LN(this.tags)}get address(){const t=this.tags,e=[],n=(...e)=>{for(const n of e)if(t[n])return t[n];return null};let r=n("addr:street","street");const i=n("addr:housenumber","housenumber");r&&(i&&(r=`${r} ${i}`),e.push(r));let s=n("addr:city","city");const o=n("addr:postcode","postcode");s&&(o&&(s=`${o} ${s}`),e.push(s));const a=n("addr:state","state"),l=n("addr:country","country");return a&&a!==s&&e.push(a),l&&e.push(l),0===e.length?null:e.join(", ")}formatMultiLine(t,e){if(!t)return null;const n=[...new Set(t.split(";").map(t=>t.trim()).filter(Boolean))];return 0===n.length?null:zw("phone"===e?n.map(t=>`${t}`).join("
"):"email"===e?n.map(t=>`${t}`).join("
"):"whatsapp"===e?n.map(t=>`${t}`).join("
"):"url"===e?n.map(t=>`${this.getDomain(t)}`).join("
"):n.join("
"))}get phone(){const t=[this.tags.phone,this.tags["contact:phone"],this.tags.mobile,this.tags["contact:mobile"]].filter(Boolean);return 0===t.length?null:this.formatMultiLine(t.join(";"),"phone")}get whatsapp(){const t=[this.tags.whatsapp,this.tags["contact:whatsapp"]].filter(Boolean);return 0===t.length?null:this.formatMultiLine(t.join(";"),"whatsapp")}get email(){const t=this.tags.email||this.tags["contact:email"];return this.formatMultiLine(t,"email")}get website(){const t=this.place.url||this.tags.website||this.tags["contact:website"];return this.formatMultiLine(t,"url")}getDomain(t){try{return new URL(t).hostname}catch{return t}}get openingHours(){const t=this.tags.opening_hours;return this.formatMultiLine(t)}get cuisine(){return this.tags.cuisine?this.tags.cuisine.split(";").map(t=>EN(t)).join(", "):null}get facebook(){return Xj(this.tags,"facebook")}get instagram(){return Xj(this.tags,"instagram")}get wikipedia(){const t=this.tags.wikipedia;return t?t.split(";").map(t=>t.trim()).filter(Boolean)[0]:null}get geoLink(){const t=this.place.lat,e=this.place.lon;return t&&e?`geo:${t},${e}?q=${t},${e}(${encodeURIComponent(this.name)})`:"#"}get visibleGeoLink(){const t=this.place.lat,e=this.place.lon;return t&&e?`${Number(t).toFixed(6)}, ${Number(e).toFixed(6)}`:""}get osmUrl(){const t=this.place.osmId;return t?`https://www.openstreetmap.org/${this.place.osmType||"node"}/${t}`:null}get gmapsUrl(){return this.place.gmapsId||this.place.osmId?`https://www.google.com/maps/search/?api=1&query=${this.name}&query=${this.place.lat},${this.place.lon}`:null}get showDescription(){return"photon"!==this.place.source&&!!this.place.description}static{Xr(em({id:null,block:'[[[10,0],[14,0,"place-details"],[12],[1,"\\n"],[41,[30,0,["isEditing"]],[[[1," "],[8,[32,0],null,[["@place","@onSave","@onCancel"],[[30,0,["place"]],[30,0,["saveChanges"]],[30,0,["cancelEditing"]]]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@photos","@name","@resetKey","@scrollToEventId"],[[30,0,["photos"]],[30,0,["name"]],[30,0,["place","osmId"]],[30,0,["newlyUploadedPhotoId"]]]],null],[1,"\\n "],[10,"h3"],[12],[1,[30,0,["name"]]],[13],[1,"\\n "],[10,2],[14,0,"place-type"],[12],[1,"\\n "],[1,[30,0,["type"]]],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["showDescription"]],[[[1," "],[10,2],[14,0,"place-description"],[12],[1,"\\n "],[1,[30,0,["place","description"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[]]],[1,"\\n "],[10,0],[14,0,"actions"],[12],[1,"\\n "],[10,0],[14,0,"save-button-wrapper"],[12],[1,"\\n "],[11,"button"],[16,0,[52,[30,0,["isSaved"]],"btn btn-secondary","btn btn-outline"]],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleLists"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["bookmark",[52,[30,0,["isSaved"]],"currentColor","var(--link-color)"]]],null],[1,"\\n "],[1,[52,[30,0,["isSaved"]],"Saved","Save"]],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["showLists"]],[[[1," "],[8,[32,4],null,[["@place","@onClose","@isSaved"],[[30,0,["saveablePlace"]],[30,0,["closeLists"]],[30,0,["isSaved"]]]],null],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isSaved"]],[[[1," "],[11,"button"],[24,0,"btn btn-outline"],[24,"title","Edit"],[16,"disabled",[30,0,["isEditing"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["startEditing"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["edit","var(--link-color)"]],null],[1,"\\n Edit\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["cuisine"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["fork-and-knife","Cuisine"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["cuisine"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["openingHours"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["clock","Opening hours"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["openingHours"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["phone"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["phone","Phone"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["phone"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["whatsapp"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["whatsapp","WhatsApp"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["whatsapp"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["website"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["globe","Website"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["website"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["email"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["mail","Email"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["email"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["facebook"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["facebook","Facebook"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["facebook","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["facebook","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["instagram"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["instagram","Instagram"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["instagram","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["instagram","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["wikipedia"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["wikipedia","Wikipedia"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[29,["https://wikipedia.org/wiki/",[30,0,["wikipedia"]]]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Wikipedia\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["address"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["home","Address"]],null],[1,"\\n "],[10,1],[12],[1,[30,0,["address"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["map-pin","Geo link"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["geoLink"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["visibleGeoLink"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["osmUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n OpenStreetMap\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["gmapsUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["gmapsUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Google Maps\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,0],[14,0,"meta-info"],[12],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["camera"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[11,"button"],[24,0,"btn-link"],[24,4,"button"],[4,[32,2],["click",[30,0,["openPhotoUploadModal"]]],null],[12],[1,"\\n Add a photo\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13],[1,"\\n\\n"],[41,[30,0,["isPhotoUploadModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closePhotoUploadModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,6],null,[["@place","@onClose"],[[30,0,["saveablePlace"]],[30,0,["closePhotoUploadModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,7],null,[["@onConnect"],[[30,0,["onNostrConnected"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-details.gjs",scope:()=>[NB,Rq,Sb,DB,qB,Eq,c$,kq],isStrictMode:!0}),this)}}const Lq=Ow(function([t]){return EN(t)});class Iq extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");createNewPlace(){const t=this.router.currentRoute.queryParams,e=t.lat,n=t.lon;e&&n?this.router.transitionTo("place.new",{queryParams:{lat:e,lon:n}}):this.router.transitionTo("place.new",{queryParams:{lat:0,lon:0}})}static{pF(this.prototype,"createNewPlace",[Pu])}selectPlace(t){this.args.onSelect&&this.args.onSelect(t)}static{pF(this.prototype,"selectPlace",[Pu])}clearSelection(){this.args.onSelect&&this.args.onSelect(null)}static{pF(this.prototype,"clearSelection",[Pu])}async toggleSave(t){if(t)if(t.createdAt)try{if(await this.storage.removePlace(t),console.debug("Place deleted:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate){const e={...t,id:void 0,geohash:void 0,createdAt:void 0};this.args.onUpdate(e)}this.args.onSelect&&this.args.onSelect(null),this.args.onClose&&this.args.onClose()}catch(ej){console.error("Failed to delete:",ej),alert("Failed to delete: "+ej.message)}else{const e={title:RN(t.osmTags,"Untitled Place"),lat:t.lat,lon:t.lon,tags:[],url:t.osmTags.website,osmId:String(t.osmId||t.id),osmType:t.osmType,osmTags:t.osmTags};try{const t=await this.storage.storePlace(e);console.debug("Place saved:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(t),this.args.onSelect&&this.args.onSelect(t)}catch(v5){console.error("Failed to save place:",v5),alert("Failed to save place: "+v5.message)}}}static{pF(this.prototype,"toggleSave",[Pu])}async updateBookmark(t){try{const e=await this.storage.updatePlace(t);console.debug("Place updated:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(e)}catch(ej){console.error("Failed to update place:",ej),alert("Failed to update place: "+ej.message)}}static{pF(this.prototype,"updateBookmark",[Pu])}get isNearbySearch(){const t=this.router.currentRoute.queryParams;return!t.q&&!t.category&&t.lat&&t.lon}get hasHeaderPhoto(){return this.args.selectedPlace&&this.nostrData.placePhotos&&this.nostrData.placePhotos.length>0}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[15,0,[29,["sidebar-header ",[52,[30,0,["hasHeaderPhoto"]],"no-border"]]]],[12],[1,"\\n"],[41,[30,1],[[[1," "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,0,["clearSelection"]]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["target",20,"#ea4335"]],null],[1,"\\n Nearby"],[13],[1,"\\n"]],[]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#333"]],null],[1," Results"],[13],[1,"\\n"]],[]]]],[]]],[1," "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n"],[41,[30,1],[[[1," "],[8,[32,2],null,[["@place","@onToggleSave","@onSave"],[[30,1],[30,0,["toggleSave"]],[30,0,["updateBookmark"]]]],null],[1,"\\n"]],[]],[[[41,[30,3],[[[1," "],[10,"ul"],[14,0,"places-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,3]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"place-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,3],[[30,0,["selectPlace"]],[30,4]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"place-name"],[12],[1,[28,[32,4],[[30,4,["title"]],[30,4,["osmTags","name"]],[30,4,["osmTags","name:en"]],"Unnamed Place"],null]],[13],[1,"\\n "],[10,0],[14,0,"place-type"],[12],[1,"\\n"],[41,[28,[32,5],[[30,4,["source"]],"osm"],null],[[[1," "],[1,[28,[32,6],[[30,4,["type"]]],null]],[1,"\\n"]],[]],[[[41,[28,[32,5],[[30,4,["source"]],"photon"],null],[[[1," "],[1,[30,4,["description"]]],[1,"\\n"]],[]],[[[41,[30,4,["osmTags"]],[[[1," "],[1,[28,[32,6],[[28,[32,7],[[30,4,["osmTags"]]],null]],null]],[1,"\\n"]],[]],[[[41,[30,4,["description"]],[[[1," "],[1,[30,4,["description"]]],[1,"\\n "]],[]],null]],[]]],[1," "]],[]]]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[4]],null],[1," "],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No places found nearby."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No results found."],[13],[1,"\\n"]],[]]]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline create-place"],[24,4,"button"],[4,[32,0],["click",[30,0,["createNewPlace"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["plus",18,"var(--link-color)"]],null],[1,"\\n Create new place\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"],[13]],["@selectedPlace","@onClose","@places","place"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/places-sidebar.gjs",scope:()=>[Sb,DB,Mq,AB,FB,zB,Lq,LN],isStrictMode:!0}),this)}}class Pq extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");selectPlace(t){t&&(this.mapUi.returnToSearch=!0,this.router.transitionTo("place",t))}static{pF(this.prototype,"selectPlace",[Pu])}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[8,[32,0],null,[["@places","@onSelect","@onClose"],[[30,1],[30,0,["selectPlace"]],[30,0,["close"]]]],null]],["@model"],[]]',moduleName:"/home/basti/src/marco/app/templates/search.gjs",scope:()=>[Iq],isStrictMode:!0}),this)}}const Aq=Object.freeze(Object.defineProperty({__proto__:null,default:Pq},Symbol.toStringTag,{value:"Module"})),Oq=Object.freeze(Object.defineProperty({__proto__:null,default:class extends cd{queryParams=["lat","lon","q","selected","category"];lat=null;lon=null;q=null;selected=null;category=null}},Symbol.toStringTag,{value:"Module"}));class Fq extends kp{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"photon",[$f])}#Ht=void fF(this,"photon");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0},q:{refreshModel:!0},selected:{refreshModel:!0},category:{refreshModel:!0}};async model(t){const e=t.lat?parseFloat(t.lat):null,n=t.lon?parseFloat(t.lon):null;let r=[],i=null,s=null;try{if(t.category&&e&&n){i="category",s=t.category,this.mapUi.startLoading(i,s);let o=this.mapUi.currentBounds;if(!o){const t=.01;o={minLat:e-t,maxLat:e+t,minLon:n-t,maxLon:n+t}}r=await this.osm.getCategoryPois(o,t.category,e,n),r=r.map(t=>({...t,_distance:jj(e,n,t.lat,t.lon)})).sort((t,e)=>t._distance-e._distance)}else if(t.q){i="text",s=t.q,this.mapUi.startLoading(i,s),r=await this.photon.search(t.q,e,n);const o=t.q.toLowerCase(),a=this.storage.savedPlaces.filter(t=>t.title?.toLowerCase().includes(o)||t.description?.toLowerCase().includes(o));a.forEach(t=>{r.find(e=>t.osmId&&e.osmId===t.osmId||e.id&&e.id===t.id)||r.push(t)})}else if(e&&n){const t=50;r=await this.osm.getNearbyPois(e,n,t);const i=this.storage.savedPlaces.filter(r=>jj(e,n,r.lat,r.lon)<=t);i.forEach(t=>{r.find(e=>t.osmId&&e.osmId===t.osmId||e.id&&e.id===t.id)||r.push(t)}),r=r.map(t=>({...t,_distance:jj(e,n,t.lat,t.lon)})).sort((t,e)=>t._distance-e._distance)}}finally{i&&s&&this.mapUi.stopLoading(i,s)}return r=r.map(t=>this.storage.findPlaceById(t.osmId)||t),r}afterModel(t,e){const{q:n,selected:r}=e.to.queryParams,i=r||n;if(i&&t.length>0){let e=null;if(e=t.find(t=>t.osmTags&&(t.osmTags.name===i||t.osmTags["name:en"]===i)),!e){const n=t[0];n._distance<=10&&(e=n)}if(e)return void this.router.replaceWith("place",e)}this.mapUi.stopSearch()}setupController(t,e){super.setupController(t,e),this.mapUi.stopSearch(),this.mapUi.setSearchResults(e);const{q:n,category:r,lat:i,lon:s}=this.paramsFor("search");this.mapUi.currentSearch={q:n,category:r,lat:i,lon:s}}error(t,e){return this.mapUi.stopSearch(),this.toast.show("Search request failed. Please try again."),e&&e.abort(),!1}static{pF(this.prototype,"error",[Pu])}}const zq=Object.freeze(Object.defineProperty({__proto__:null,default:Fq},Symbol.toStringTag,{value:"Module"}));var Dq,Nq,jq;let Bq=(Dq=$f("page-title"),Nq=class extends Mw{constructor(t){super(t),hB(this,"tokens",jq,this),uB(this,"tokenId",et(this)),this.tokens.push({id:this.tokenId})}compute(t,e){const n={...e,id:this.tokenId,title:t.join("")};return this.tokens.push(n),this.tokens.scheduleTitleUpdate(),""}willDestroy(){super.willDestroy(),this.tokens.remove(this.tokenId),this.tokens.scheduleTitleUpdate()}},jq=dB(Nq.prototype,"tokens",[Dq],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),Nq);const Uq="add",$q="remove",qq="propertychange",Vq="change",Wq="contextmenu",Hq="click",Gq="keydown",Kq="keypress",Zq="touchmove",Yq="wheel";class Xq{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}}function Jq(t,e){return t>e?1:te?-1:0}function tV(t,e,n){if(t[0]<=e)return 0;const r=t.length;if(e<=t[r-1])return r-1;if("function"==typeof n){for(let i=1;i0?i-1:i}return r-1}if(n>0){for(let n=1;n0)}removeEventListener(t,e){if(!this.listeners_)return;const n=this.listeners_[t];if(!n)return;const r=n.indexOf(e);-1!==r&&(this.pendingRemovals_&&t in this.pendingRemovals_?(n[r]=oV,++this.pendingRemovals_[t]):(n.splice(r,1),0===n.length&&delete this.listeners_[t]))}}function pV(t,e,n,r,i){if(i){const i=n;n=function(s){return t.removeEventListener(e,n),i.call(r??this,s)}}else r&&r!==t&&(n=n.bind(r));const s={target:t,type:e,listener:n};return t.addEventListener(e,n),s}function fV(t,e,n,r){return pV(t,e,n,r,!0)}function gV(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),cV(t))}class mV extends dV{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(Vq)}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const n=t.length,r=new Array(n);for(let i=0;i0;)this.pop()}extend(t){for(let e=0,n=t.length;ethis.getLength())throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e),this.array_.splice(t,0,e),this.updateLength_(),this.dispatchEvent(new CV(Uq,e,t))}pop(){return this.removeAt(this.getLength()-1)}push(t){const e=this.getLength();return this.insertAt(e,t),this.getLength()}remove(t){const e=this.array_;for(let n=0,r=e.length;n=this.getLength())return;const e=this.array_[t];return this.array_.splice(t,1),this.updateLength_(),this.dispatchEvent(new CV($q,e,t)),e}setAt(t,e){if(t>=this.getLength())return void this.insertAt(t,e);if(t<0)throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e,t);const n=this.array_[t];this.array_[t]=e,this.dispatchEvent(new CV($q,n,t)),this.dispatchEvent(new CV(Uq,e,t))}updateLength_(){this.set(xV,this.array_.length)}assertUnique_(t,e){const n=this.array_;for(let r=0,i=n.length;r{this.clickTimeoutId_=void 0;const e=new EV(TV.SINGLECLICK,this.map_,t);this.dispatchEvent(e)},250)}updateActivePointers_(t){const e=t,n=e.pointerId;if(e.type==TV.POINTERUP||e.type==TV.POINTERCANCEL){delete this.trackedTouches_[n];for(const t in this.trackedTouches_)if(this.trackedTouches_[t].target!==e.target){delete this.trackedTouches_[t];break}}else e.type!=TV.POINTERDOWN&&e.type!=TV.POINTERMOVE||(this.trackedTouches_[n]=e);this.activePointers_=Object.values(this.trackedTouches_)}handlePointerUp_(t){this.updateActivePointers_(t);const e=new EV(TV.POINTERUP,this.map_,t,void 0,void 0,this.activePointers_);this.dispatchEvent(e),this.emulateClicks_&&!e.defaultPrevented&&!this.dragging_&&this.isMouseActionButton_(t)&&this.emulateClick_(this.down_),0===this.activePointers_.length&&(this.dragListenerKeys_.forEach(gV),this.dragListenerKeys_.length=0,this.dragging_=!1,this.down_=null)}isMouseActionButton_(t){return 0===t.button}handlePointerDown_(t){this.emulateClicks_=0===this.activePointers_.length,this.updateActivePointers_(t);const e=new EV(TV.POINTERDOWN,this.map_,t,void 0,void 0,this.activePointers_);if(this.dispatchEvent(e),this.down_=new PointerEvent(t.type,t),Object.defineProperty(this.down_,"target",{writable:!1,value:t.target}),0===this.dragListenerKeys_.length){const t=this.map_.getOwnerDocument();this.dragListenerKeys_.push(pV(t,TV.POINTERMOVE,this.handlePointerMove_,this),pV(t,TV.POINTERUP,this.handlePointerUp_,this),pV(this.element_,TV.POINTERCANCEL,this.handlePointerUp_,this)),this.element_.getRootNode&&this.element_.getRootNode()!==t&&this.dragListenerKeys_.push(pV(this.element_.getRootNode(),TV.POINTERUP,this.handlePointerUp_,this))}}handlePointerMove_(t){if(this.isMoving_(t)){this.updateActivePointers_(t),this.dragging_=!0;const e=new EV(TV.POINTERDRAG,this.map_,t,this.dragging_,void 0,this.activePointers_);this.dispatchEvent(e)}}relayMoveEvent_(t){this.originalPointerMoveEvent_=t;const e=!(!this.down_||!this.isMoving_(t));this.dispatchEvent(new EV(TV.POINTERMOVE,this.map_,t,e))}handleTouchMove_(t){const e=this.originalPointerMoveEvent_;e&&!e.defaultPrevented||"boolean"==typeof t.cancelable&&!0!==t.cancelable||t.preventDefault()}isMoving_(t){return this.dragging_||Math.abs(t.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(t.clientY-this.down_.clientY)>this.moveTolerance_}disposeInternal(){this.relayedListenerKey_&&(gV(this.relayedListenerKey_),this.relayedListenerKey_=null),this.element_.removeEventListener(Zq,this.boundHandleTouchMove_),this.pointerdownListenerKey_&&(gV(this.pointerdownListenerKey_),this.pointerdownListenerKey_=null),this.dragListenerKeys_.forEach(gV),this.dragListenerKeys_.length=0,this.element_=null,super.disposeInternal()}}const NV="postrender",jV="loadstart",BV="loadend",UV="layergroup",$V="size",qV="target",VV="view";function WV(t,e){if(!t)throw new Error(e)}const HV=1/0;class GV{constructor(t,e){this.priorityFunction_=t,this.keyFunction_=e,this.elements_=[],this.priorities_=[],this.queuedElements_={}}clear(){this.elements_.length=0,this.priorities_.length=0,cV(this.queuedElements_)}dequeue(){const t=this.elements_,e=this.priorities_,n=t[0];1==t.length?(t.length=0,e.length=0):(t[0]=t.pop(),e[0]=e.pop(),this.siftUp_(0));const r=this.keyFunction_(n);return delete this.queuedElements_[r],n}enqueue(t){WV(!(this.keyFunction_(t)in this.queuedElements_),"Tried to enqueue an `element` that was already added to the queue");const e=this.priorityFunction_(t);return e!=HV&&(this.elements_.push(t),this.priorities_.push(e),this.queuedElements_[this.keyFunction_(t)]=!0,this.siftDown_(0,this.elements_.length-1),!0)}getCount(){return this.elements_.length}getLeftChildIndex_(t){return 2*t+1}getRightChildIndex_(t){return 2*t+2}getParentIndex_(t){return t-1>>1}heapify_(){let t;for(t=(this.elements_.length>>1)-1;t>=0;t--)this.siftUp_(t)}isEmpty(){return 0===this.elements_.length}isKeyQueued(t){return t in this.queuedElements_}isQueued(t){return this.isKeyQueued(this.keyFunction_(t))}siftUp_(t){const e=this.elements_,n=this.priorities_,r=e.length,i=e[t],s=n[t],o=t;for(;t>1;){const i=this.getLeftChildIndex_(t),s=this.getRightChildIndex_(t),o=st;){const t=this.getParentIndex_(e);if(!(r[t]>s))break;n[e]=n[t],r[e]=r[t],e=t}n[e]=i,r[e]=s}reprioritize(){const t=this.priorityFunction_,e=this.elements_,n=this.priorities_;let r=0;const i=e.length;let s,o,a;for(o=0;ot.apply(null,e),t=>t[0].getKey()),this.boundHandleTileChange_=this.handleTileChange.bind(this),this.tileChangeCallback_=e,this.tilesLoading_=0,this.tilesLoadingKeys_={}}enqueue(t){const e=super.enqueue(t);return e&&t[0].addEventListener(Vq,this.boundHandleTileChange_),e}getTilesLoading(){return this.tilesLoading_}handleTileChange(t){const e=t.target,n=e.getState();if(2===n||3===n||4===n){3!==n&&e.removeEventListener(Vq,this.boundHandleTileChange_);const t=e.getKey();t in this.tilesLoadingKeys_&&(delete this.tilesLoadingKeys_[t],--this.tilesLoading_),this.tileChangeCallback_()}}loadMoreTiles(t,e){let n=0;for(;this.tilesLoading_0;){const t=this.dequeue()[0],e=t.getKey();0!==t.getState()||e in this.tilesLoadingKeys_||(this.tilesLoadingKeys_[e]=!0,++this.tilesLoading_,++n,t.load())}}}const ZV={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};function YV(t,e,n){return Math.min(Math.max(t,e),n)}function XV(t,e,n,r,i,s){const o=i-n,a=s-r;if(0!==o||0!==a){const l=((t-n)*o+(e-r)*a)/(o*o+a*a);l>1?(n=i,r=s):l>0&&(n+=o*l,r+=a*l)}return JV(t,e,n,r)}function JV(t,e,n,r){const i=n-t,s=r-e;return i*i+s*s}function QV(t){return 180*t/Math.PI}function tW(t){return t*Math.PI/180}function eW(t,e){const n=t%e;return n*e<0?n+e:n}function nW(t,e,n){return t+n*(e-t)}function rW(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}function iW(t,e){return Math.floor(rW(t,e))}function sW(t,e){return Math.ceil(rW(t,e))}function oW(t,e,n){if(t>=e&&tp&&(d=(p+d)/2,p=d),f>g&&(f=(g+f)/2,g=f);let m=YV(r[0],d,p),y=YV(r[1],f,g);if(o&&n&&i){const t=30*i;m+=-t*Math.log(1+Math.max(0,d-r[0])/t)+t*Math.log(1+Math.max(0,r[0]-p)/t),y+=-t*Math.log(1+Math.max(0,f-r[1])/t)+t*Math.log(1+Math.max(0,r[1]-g)/t)}return[m,y]}}function lW(t){return t}function cW(t){const e=[1/0,1/0,-1/0,-1/0];for(let n=0,r=t.length;ni&&(l|=4),as&&(l|=2),0===l&&(l=1),l}function yW(t,e,n,r,i){return i?(i[0]=t,i[1]=e,i[2]=n,i[3]=r,i):[t,e,n,r]}function vW(t){return yW(1/0,1/0,-1/0,-1/0,t)}function bW(t,e){const n=t[0],r=t[1];return yW(n,r,n,r,e)}function wW(t,e,n,r,i){return SW(vW(i),t,e,n,r)}function _W(t,e){return t[0]==e[0]&&t[2]==e[2]&&t[1]==e[1]&&t[3]==e[3]}function xW(t,e){return e[0]t[2]&&(t[2]=e[2]),e[1]t[3]&&(t[3]=e[3]),t}function CW(t,e){e[0]t[2]&&(t[2]=e[0]),e[1]t[3]&&(t[3]=e[1])}function SW(t,e,n,r,i){for(;ne[0]?r[0]=t[0]:r[0]=e[0],t[1]>e[1]?r[1]=t[1]:r[1]=e[1],t[2]=e[0]&&t[1]<=e[3]&&t[3]>=e[1]}function BW(t){return t[2]1){const e=t[2]-t[0],n=t[3]-t[1];for(let s=0;s=n[2])){const e=NW(n),i=Math.floor((r[0]-n[0])/e)*e;t[0]-=i,t[2]-=i}return t}function qW(t,e,n){if(e.canWrapX()){const r=e.getExtent();if(!isFinite(t[0])||!isFinite(t[2]))return[[r[0],t[1],r[2],t[3]]];$W(t,e);const i=NW(r);if(NW(t)>i&&!n)return[[r[0],t[1],r[2],t[3]]];if(t[0]r[2])return[[t[0],t[1],r[2],t[3]],[r[0],t[1],t[2]-i,t[3]]]}return[t]}function VW(t,e){let n=!0;for(let r=t.length-1;r>=0;--r)if(t[r]!=e[r]){n=!1;break}return n}function WW(t,e){const n=Math.cos(e),r=Math.sin(e),i=t[0]*n-t[1]*r,s=t[1]*n+t[0]*r;return t[0]=i,t[1]=s,t}function HW(t,e){if(e.canWrapX()){const n=NW(e.getExtent()),r=function(t,e,n){const r=e.getExtent();let i=0;return e.canWrapX()&&(t[0]r[2])&&(n=n||NW(r),i=Math.floor((t[0]-r[0])/n)),i}(t,e,n);r&&(t[0]-=r*n)}return t}function GW(t){return Math.pow(t,3)}function KW(t){return 1-GW(1-t)}function ZW(t){return 3*t*t-2*t*t*t}function YW(t){return t}const XW=6371008.8;function JW(t,e,n){n=n||XW;const r=tW(t[1]),i=tW(e[1]),s=(i-r)/2,o=tW(e[0]-t[0])/2,a=Math.sin(s)*Math.sin(s)+Math.sin(o)*Math.sin(o)*Math.cos(r)*Math.cos(i);return 2*n*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function QW(t,e,n,r){r=r||XW;const i=tW(t[1]),s=tW(t[0]),o=e/r,a=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(n));return[QV(s+Math.atan2(Math.sin(n)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(a))),QV(a)]}function tH(...t){console.warn(...t)}const eH={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};class nH{constructor(t){this.code_=t.code,this.units_=t.units,this.extent_=void 0!==t.extent?t.extent:null,this.worldExtent_=void 0!==t.worldExtent?t.worldExtent:null,this.axisOrientation_=void 0!==t.axisOrientation?t.axisOrientation:"enu",this.global_=void 0!==t.global&&t.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=t.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=t.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||eH[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(t){this.global_=t,this.canWrapX_=!(!t||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(t){this.defaultTileGrid_=t}setExtent(t){this.extent_=t,this.canWrapX_=!(!this.global_||!t)}setWorldExtent(t){this.worldExtent_=t}setGetPointResolution(t){this.getPointResolutionFunc_=t}getPointResolutionFunc(){return this.getPointResolutionFunc_}}const rH=6378137,iH=Math.PI*rH,sH=[-iH,-iH,iH,iH],oH=[-180,-85,180,85],aH=rH*Math.log(Math.tan(Math.PI/2));class lH extends nH{constructor(t){super({code:t,units:"m",extent:sH,global:!0,worldExtent:oH,getPointResolution:function(t,e){return t/Math.cosh(e[1]/rH)}})}}const cH=[new lH("EPSG:3857"),new lH("EPSG:102100"),new lH("EPSG:102113"),new lH("EPSG:900913"),new lH("http://www.opengis.net/def/crs/EPSG/0/3857"),new lH("http://www.opengis.net/gml/srs/epsg.xml#3857")],uH=[-180,-90,180,90],hH=6378137*Math.PI/180;class dH extends nH{constructor(t,e){super({code:t,units:"degrees",extent:uH,axisOrientation:e,global:!0,metersPerUnit:hH,worldExtent:uH})}}const pH=[new dH("CRS:84"),new dH("EPSG:4326","neu"),new dH("urn:ogc:def:crs:OGC:1.3:CRS84"),new dH("urn:ogc:def:crs:OGC:2:84"),new dH("http://www.opengis.net/def/crs/OGC/1.3/CRS84"),new dH("http://www.opengis.net/gml/srs/epsg.xml#4326","neu"),new dH("http://www.opengis.net/def/crs/EPSG/0/4326","neu")];let fH={},gH={};function mH(t,e,n){const r=t.getCode(),i=e.getCode();r in gH||(gH[r]={}),gH[r][i]=n}function yH(t,e){return t in gH&&e in gH[t]?gH[t][e]:null}const vH=.9996,bH=.00669438,wH=bH*bH,_H=wH*bH,xH=bH/(1-bH),CH=Math.sqrt(1-bH),SH=(1-CH)/(1+CH),kH=SH*SH,EH=kH*SH,TH=EH*SH,RH=TH*SH,MH=.9983242984503243,LH=15*wH/256+45*_H/1024,IH=35*_H/3072,PH=1.5*SH-27/32*EH+269/512*RH,AH=21/16*kH-55/32*TH,OH=151/96*EH-417/128*RH,FH=1097/512*TH,zH=6378137;function DH(t,e,n){const r=t-5e5,i=(n.north?e:e-1e7)/vH/(zH*MH),s=i+PH*Math.sin(2*i)+AH*Math.sin(4*i)+OH*Math.sin(6*i)+FH*Math.sin(8*i),o=Math.sin(s),a=o*o,l=Math.cos(s),c=o/l,u=c*c,h=u*u,d=1-bH*a,p=Math.sqrt(1-bH*a),f=xH*l**2,g=f*f,m=r/(zH/p*vH),y=m*m,v=y*m,b=v*m,w=b*m,_=s-c/((1-bH)/d)*(y/2-b/24*(5+3*u+10*f-4*g-9*xH))+w*m/720*(61+90*u+298*f+45*h-252*xH-3*g);let x=(m-v/6*(1+2*u+f)+w/120*(5-2*f+28*u-3*g+8*xH+24*h))/l;return x=oW(x+tW(jH(n.number)),-Math.PI,Math.PI),[QV(x),QV(_)]}function NH(t,e,n){t=oW(t,-180,180),e<-80?e=-80:e>84&&(e=84);const r=tW(e),i=Math.sin(r),s=Math.cos(r),o=i/s,a=o*o,l=a*a,c=tW(t),u=tW(jH(n.number)),h=zH/Math.sqrt(1-bH*i**2),d=xH*s**2,p=s*oW(c-u,-Math.PI,Math.PI),f=p*p,g=f*p,m=g*p,y=m*p,v=y*p,b=zH*(MH*r-.002514607064228144*Math.sin(2*r)+LH*Math.sin(4*r)-IH*Math.sin(6*r)),w=vH*h*(p+g/6*(1-a+d)+y/120*(5-18*a+l+72*d-58*xH))+5e5;let _=vH*(b+h*o*(f/2+m/24*(5-a+9*d+4*d**2)+v/720*(61-58*a+l+600*d-330*xH)));return n.north||(_+=1e7),[w,_]}function jH(t){return 6*(t-1)-180+3}const BH=[/^EPSG:(\d+)$/,/^urn:ogc:def:crs:EPSG::(\d+)$/,/^http:\/\/www\.opengis\.net\/def\/crs\/EPSG\/0\/(\d+)$/];function UH(t){let e=0;for(const i of BH){const n=t.match(i);if(n){e=parseInt(n[1]);break}}if(!e)return null;let n=0,r=!1;return e>32700&&e<32761?n=e-32700:e>32600&&e<32661&&(r=!0,n=e-32600),n?{number:n,north:r}:null}function $H(t,e){return function(n,r,i,s){const o=n.length;i=i>1?i:2,s=s??i,r||(r=i>2?n.slice():new Array(o));for(let a=0;a180)&&(e[0]=eW(n+180,360)-180),e}function nG(t,e){if(t===e)return!0;const n=t.getUnits()===e.getUnits();return(t.getCode()===e.getCode()||rG(t,e)===GH)&&n}function rG(t,e){const n=t.getCode(),r=e.getCode();let i=yH(n,r);if(i)return i;let s=null,o=null;for(const l of qH)s||(s=l(t)),o||(o=l(e));if(!s&&!o)return null;const a="EPSG:4326";if(o)if(s)i=iG(s.inverse,o.forward);else{const t=yH(n,a);t&&(i=iG(t,o.forward))}else{const t=yH(a,r);t&&(i=iG(s.inverse,t))}return i&&(ZH(t),ZH(e),mH(t,e,i)),i}function iG(t,e){return function(n,r,i,s){return r=t(n,r,i,s),e(r,r,i,s)}}function sG(t,e){return rG(YH(t),YH(e))}function oG(t,e,n){const r=sG(e,n);if(!r){const t=YH(e).getCode(),r=YH(n).getCode();throw new Error(`No transform available between ${t} and ${r}`)}return r(t,void 0,t.length)}function aG(t,e,n,r){return UW(t,sG(e,n),void 0,r)}function lG(t){return t}function cG(t){return WH&&!VW(t,[0,0])&&t[0]>=-180&&t[0]<=180&&t[1]>=-90&&t[1]<=90&&(WH=!1,tH("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),t}function uG(t){return t}var hG,dG,pG;JH(cH),JH(pH),hG=cH,dG=function(t,e,n,r){const i=t.length;n=n>1?n:2,r=r??n,void 0===e&&(e=n>2?t.slice():new Array(i));for(let s=0;saH?n=aH:n<-aH&&(n=-aH),e[s+1]=n}return e},pG=function(t,e,n,r){const i=t.length;n=n>1?n:2,r=r??n,void 0===e&&(e=n>2?t.slice():new Array(i));for(let s=0;s{if(!n)return this.getSimplifiedGeometry(e);const r=this.clone();return r.applyTransform(n),r.getSimplifiedGeometry(e)})}simplifyTransformed(t,e){return this.simplifyTransformedInternal(this.getRevision(),t,e)}clone(){return yV()}closestPointXY(t,e,n,r){return yV()}containsXY(t,e){return 0===this.closestPointXY(t,e,TG,Number.MIN_VALUE)}getClosestPoint(t,e){return e=e||[NaN,NaN],this.closestPointXY(t[0],t[1],e,1/0),e}intersectsCoordinate(t){return this.containsXY(t[0],t[1])}computeExtent(t){return yV()}getExtent(t){if(this.extentRevision_!=this.getRevision()){const t=this.computeExtent(this.extent_);(isNaN(t[0])||isNaN(t[1]))&&vW(t),this.extentRevision_=this.getRevision()}return function(t,e){return e?(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e):t}(this.extent_,t)}rotate(t,e){yV()}scale(t,e,n){yV()}simplify(t){return this.getSimplifiedGeometry(t*t)}getSimplifiedGeometry(t){return yV()}getType(){return yV()}applyTransform(t){yV()}intersectsExtent(t){return yV()}translate(t,e){yV()}transform(t,e){const n=YH(t),r="tile-pixels"==n.getUnits()?function(t,r,i){const s=n.getExtent(),o=n.getWorldExtent(),a=OW(o)/OW(s);wG(EG,o[0],o[3],a,-a,0,0,0);const l=SG(t,0,t.length,i,EG,r),c=sG(n,e);return c?c(l,l,i):l}:sG(n,e);return this.applyTransform(r),this}}class MG extends RG{constructor(){super(),this.layout="XY",this.stride=2,this.flatCoordinates}computeExtent(t){return wW(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,t)}getCoordinates(){return yV()}getFirstCoordinate(){return this.flatCoordinates.slice(0,this.stride)}getFlatCoordinates(){return this.flatCoordinates}getLastCoordinate(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)}getLayout(){return this.layout}getSimplifiedGeometry(t){if(this.simplifiedGeometryRevision!==this.getRevision()&&(this.simplifiedGeometryMaxMinSquaredTolerance=0,this.simplifiedGeometryRevision=this.getRevision()),t<0||0!==this.simplifiedGeometryMaxMinSquaredTolerance&&t<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;const e=this.getSimplifiedGeometryInternal(t);return e.getFlatCoordinates().length1)h=n;else{if(d>0){for(let i=0;ii&&(i=a),s=n,o=r}return i}function zG(t,e,n,r,i){for(let s=0,o=n.length;s0;){const n=c.pop(),s=c.pop();let o=0;const a=t[s],h=t[s+1],d=t[n],p=t[n+1];for(let e=s+r;eo&&(u=e,o=n)}o>i&&(l[(u-e)/r]=1,s+r0&&f>d)&&(p<0&&g0&&g>p)?(a=n,l=h):(s[o++]=a,s[o++]=l,c=a,u=l,a=n,l=h)}return s[o++]=a,s[o++]=l,o}function ZG(t,e,n,r,i,s,o,a){for(let l=0,c=n.length;ls&&(n-a)*(s-l)-(i-a)*(r-l)>0&&o++:r<=s&&(n-a)*(s-l)-(i-a)*(r-l)<0&&o--,a=n,l=r}return 0!==o}function tK(t,e,n,r,i,s){if(0===n.length)return!1;if(!QG(t,e,n[0],r,i,s))return!1;for(let o=1,a=n.length;oy&&(c=(u+h)/2,tK(t,e,n,r,c,f)&&(m=c,y=i)),u=h}return isNaN(m)&&(m=i[s]),o?(o.push(m,f,y),o):[m,f,y]}function nK(t,e,n,r,i){let s=[];for(let o=0,a=n.length;o=i[0]&&s[2]<=i[2]||s[1]>=i[1]&&s[3]<=i[3]||rK(t,e,n,r,function(t,e){return function(t,e,n){let r=!1;const i=mW(t,e),s=mW(t,n);if(1===i||1===s)r=!0;else{const o=t[0],a=t[1],l=t[2],c=t[3],u=e[0],h=e[1],d=n[0],p=n[1],f=(p-h)/(d-u);let g,m;2&s&&!(2&i)&&(g=d-(p-c)/f,r=g>=o&&g<=l),r||!(4&s)||4&i||(m=p-(d-l)*f,r=m>=a&&m<=c),r||!(8&s)||8&i||(g=d-(p-a)/f,r=g>=o&&g<=l),r||!(16&s)||16&i||(m=p-(d-o)*f,r=m>=a&&m<=c)}return r}(i,t,e)}))}function sK(t,e,n,r,i){return!!(iK(t,e,n,r,i)||QG(t,e,n,r,i[0],i[1])||QG(t,e,n,r,i[0],i[3])||QG(t,e,n,r,i[2],i[1])||QG(t,e,n,r,i[2],i[3]))}function oK(t,e,n,r,i){if(!sK(t,e,n[0],r,i))return!1;if(1===n.length)return!0;for(let s=1,o=n.length;s0}function cK(t,e,n,r,i){i=void 0!==i&&i;for(let s=0,o=n.length;su&&d1&&"function"==typeof arguments[n-1]&&(e=arguments[n-1],--n);let r=0;for(;r0}getInteracting(){return this.hints_[1]>0}cancelAnimations(){let t;this.setHint(0,-this.hints_[0]);for(let e=0,n=this.animations_.length;e=0;--n){const r=this.animations_[n];let i=!0;for(let n=0,s=r.length;n0?o/s.duration:1;a>=1?(s.complete=!0,a=1):i=!1;const l=s.easing(a);if(s.sourceCenter){const t=s.sourceCenter[0],e=s.sourceCenter[1],n=s.targetCenter[0],r=s.targetCenter[1];this.nextCenter_=s.targetCenter;const i=t+l*(n-t),o=e+l*(r-e);this.targetCenter_=[i,o]}if(s.sourceResolution&&s.targetResolution){const t=1===l?s.targetResolution:s.sourceResolution+l*(s.targetResolution-s.sourceResolution);if(s.anchor){const e=this.getViewportSize_(this.getRotation()),n=this.constraints_.resolution(t,0,e,!0);this.targetCenter_=this.calculateCenterZoom(n,s.anchor)}this.nextResolution_=s.targetResolution,this.targetResolution_=t,this.applyTargetState_(!0)}if(void 0!==s.sourceRotation&&void 0!==s.targetRotation){const t=1===l?eW(s.targetRotation+Math.PI,2*Math.PI)-Math.PI:s.sourceRotation+l*(s.targetRotation-s.sourceRotation);if(s.anchor){const e=this.constraints_.rotation(t,!0);this.targetCenter_=this.calculateCenterRotate(e,s.anchor)}this.nextRotation_=s.targetRotation,this.targetRotation_=t}if(this.applyTargetState_(!0),e=!0,!s.complete)break}if(i){this.animations_[n]=null,this.setHint(0,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const t=r[0].callback;t&&xK(t,!0)}}this.animations_=this.animations_.filter(Boolean),e&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(t,e){let n;const r=this.getCenterInternal();var i,s;return void 0!==r&&(n=[r[0]-e[0],r[1]-e[1]],WW(n,t-this.getRotation()),s=e,(i=n)[0]+=+s[0],i[1]+=+s[1]),n}calculateCenterZoom(t,e){let n;const r=this.getCenterInternal(),i=this.getResolution();return void 0!==r&&void 0!==i&&(n=[e[0]-t*(e[0]-r[0])/i,e[1]-t*(e[1]-r[1])/i]),n}getViewportSize_(t){const e=this.viewportSize_;if(t){const n=e[0],r=e[1];return[Math.abs(n*Math.cos(t))+Math.abs(r*Math.sin(t)),Math.abs(n*Math.sin(t))+Math.abs(r*Math.cos(t))]}return e}setViewportSize(t){this.viewportSize_=Array.isArray(t)?t.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const t=this.getCenterInternal();return t?lG(t,this.getProjection()):t}getCenterInternal(){return this.get(ZV.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(t){return void 0!==t?(t[0]=this.hints_[0],t[1]=this.hints_[1],t):this.hints_.slice()}calculateExtent(t){return e=this.calculateExtentInternal(t),this.getProjection(),e;var e}calculateExtentInternal(t){t=t||this.getViewportSizeMinusPadding_();const e=this.getCenterInternal();WV(e,"The view center is not defined");const n=this.getResolution();WV(void 0!==n,"The view resolution is not defined");const r=this.getRotation();return WV(void 0!==r,"The view rotation is not defined"),PW(e,n,r,t)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(t){this.applyOptions_(this.getUpdatedOptions_({maxZoom:t}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(t){this.applyOptions_(this.getUpdatedOptions_({minZoom:t}))}setConstrainResolution(t){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:t}))}getProjection(){return this.projection_}getResolution(){return this.get(ZV.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(t,e){return this.getResolutionForExtentInternal(uG(t,this.getProjection()),e)}getResolutionForExtentInternal(t,e){e=e||this.getViewportSizeMinusPadding_();const n=NW(t)/e[0],r=OW(t)/e[1];return Math.max(n,r)}getResolutionForValueFunction(t){t=t||2;const e=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,r=Math.log(e/n)/Math.log(t);return function(n){return e/Math.pow(t,n*r)}}getRotation(){return this.get(ZV.ROTATION)}getValueForResolutionFunction(t){const e=Math.log(t||2),n=this.getConstrainedResolution(this.maxResolution_),r=this.minResolution_,i=Math.log(n/r)/e;return function(t){return Math.log(n/t)/e/i}}getViewportSizeMinusPadding_(t){let e=this.getViewportSize_(t);const n=this.padding_;return n&&(e=[e[0]-n[1]-n[3],e[1]-n[0]-n[2]]),e}getState(){const t=this.getProjection(),e=this.getResolution(),n=this.getRotation();let r=this.getCenterInternal();const i=this.padding_;if(i){const t=this.getViewportSizeMinusPadding_();r=SK(r,this.getViewportSize_(),[t[0]/2+i[3],t[1]/2+i[0]],e,n)}return{center:r.slice(0),projection:void 0!==t?t:null,resolution:e,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:n,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let t;const e=this.getResolution();return void 0!==e&&(t=this.getZoomForResolution(e)),t}getZoomForResolution(t){let e,n,r=this.minZoom_||0;if(this.resolutions_){const i=tV(this.resolutions_,t,1);r=i,e=this.resolutions_[i],n=i==this.resolutions_.length-1?2:e/this.resolutions_[i+1]}else e=this.maxResolution_,n=this.zoomFactor_;return r+Math.log(e/t)/Math.log(n)}getResolutionForZoom(t){if(this.resolutions_?.length){if(1===this.resolutions_.length)return this.resolutions_[0];const e=YV(Math.floor(t),0,this.resolutions_.length-2),n=this.resolutions_[e]/this.resolutions_[e+1];return this.resolutions_[e]/Math.pow(n,YV(t-e,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,t-this.minZoom_)}fit(t,e){let n;if(WV(Array.isArray(t)||"function"==typeof t.getSimplifiedGeometry,"Invalid extent or geometry provided as `geometry`"),Array.isArray(t))WV(!BW(t),"Cannot fit empty extent provided as `geometry`"),n=gK(uG(t,this.getProjection()));else if("Circle"===t.getType()){const e=uG(t.getExtent(),this.getProjection());n=gK(e),n.rotate(this.getRotation(),LW(e))}else n=t;this.fitInternal(n,e)}rotatedExtentForGeometry(t){const e=this.getRotation(),n=Math.cos(e),r=Math.sin(-e),i=t.getFlatCoordinates(),s=t.getStride();let o=1/0,a=1/0,l=-1/0,c=-1/0;for(let u=0,h=i.length;ut.trim().replace(/^['"]|['"]$/g,"")),n};function AK(t,e,n,r){let i;return i=n&&n.length?n.shift():PV?new class extends OffscreenCanvas{style={}}(t??300,e??150):document.createElement("canvas"),t&&(i.width=t),e&&(i.height=e),i.getContext("2d",r)}let OK;function FK(){return OK||(OK=AK(1,1)),OK}function zK(t){const e=t.canvas;e.width=1,e.height=1,t.clearRect(0,0,1,1)}function DK(t){let e=t.offsetWidth;const n=getComputedStyle(t);return e+=parseInt(n.marginLeft,10)+parseInt(n.marginRight,10),e}function NK(t){let e=t.offsetHeight;const n=getComputedStyle(t);return e+=parseInt(n.marginTop,10)+parseInt(n.marginBottom,10),e}function jK(t,e){const n=e.parentNode;n&&n.replaceChild(t,e)}function BK(t){for(;t.lastChild;)t.lastChild.remove()}function UK(){const t=new Proxy({childNodes:[],appendChild:function(t){return this.childNodes.push(t),t},remove:function(){},removeChild:function(t){const e=this.childNodes.indexOf(t);if(-1===e)throw new Error("Node to remove was not found");return this.childNodes.splice(e,1),t},insertBefore:function(t,e){const n=this.childNodes.indexOf(e);if(-1===n)throw new Error("Reference node not found");return this.childNodes.splice(n,0,t),t},style:{}},{get:(t,e,n)=>"firstElementChild"===e?t.childNodes.length>0?t.childNodes[0]:null:Reflect.get(t,e,n)});return t}function $K(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}class qK extends _V{constructor(t){super();const e=t.element;!e||t.target||e.style.pointerEvents||(e.style.pointerEvents="auto"),this.element=e||null,this.target_=null,this.map_=null,this.listenerKeys=[],t.render&&(this.render=t.render),t.target&&this.setTarget(t.target)}disposeInternal(){this.element?.remove(),super.disposeInternal()}getMap(){return this.map_}setMap(t){this.map_&&this.element?.remove();for(let e=0,n=this.listenerKeys.length;ee.getAttributions(t)));if(void 0!==this.attributions_&&(Array.isArray(this.attributions_)?this.attributions_.forEach(t=>n.add(t)):n.add(this.attributions_)),!this.overrideCollapsible_){const t=!e.some(t=>!1===t.getSource()?.getAttributionsCollapsible());this.setCollapsible(t)}return Array.from(n)}async updateElement_(t){if(!t)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const e=await Promise.all(this.collectSourceAttributions_(t).map(t=>lV(()=>t))),n=e.length>0;if(this.renderedVisible_!=n&&(this.element.style.display=n?"":"none",this.renderedVisible_=n),!rV(e,this.renderedAttributions_)){BK(this.ulElement_);for(let t=0,n=e.length;t0&&e%(2*Math.PI)!=0?t.animate({rotation:0,duration:this.duration_,easing:KW}):t.setRotation(0))}render(t){const e=t.frameState;if(!e)return;const n=e.viewState.rotation;if(n!=this.rotation_){const t="rotate("+n+"rad)";if(this.autoHide_){const t=this.element.classList.contains(kK);t||0!==n?t&&0!==n&&this.element.classList.remove(kK):this.element.classList.add(kK)}this.label_.style.transform=t}this.rotation_=n}}class HK extends qK{constructor(t){t=t||{},super({element:document.createElement("div"),target:t.target});const e=void 0!==t.className?t.className:"ol-zoom",n=void 0!==t.delta?t.delta:1,r=void 0!==t.zoomInClassName?t.zoomInClassName:e+"-in",i=void 0!==t.zoomOutClassName?t.zoomOutClassName:e+"-out",s=void 0!==t.zoomInLabel?t.zoomInLabel:"+",o=void 0!==t.zoomOutLabel?t.zoomOutLabel:"–",a=void 0!==t.zoomInTipLabel?t.zoomInTipLabel:"Zoom in",l=void 0!==t.zoomOutTipLabel?t.zoomOutTipLabel:"Zoom out",c=document.createElement("button");c.className=r,c.setAttribute("type","button"),c.title=a,c.appendChild("string"==typeof s?document.createTextNode(s):s),c.addEventListener(Hq,this.handleClick_.bind(this,n),!1);const u=document.createElement("button");u.className=i,u.setAttribute("type","button"),u.title=l,u.appendChild("string"==typeof o?document.createTextNode(o):o),u.addEventListener(Hq,this.handleClick_.bind(this,-n),!1);const h=e+" "+EK+" "+TK,d=this.element;d.className=h,d.appendChild(c),d.appendChild(u),this.duration_=void 0!==t.duration?t.duration:250}handleClick_(t,e){e.preventDefault(),this.zoomByDelta_(t)}zoomByDelta_(t){const e=this.getMap().getView();if(!e)return;const n=e.getZoom();if(void 0!==n){const r=e.getConstrainedZoom(n+t);this.duration_>0?(e.getAnimating()&&e.cancelAnimations(),e.animate({zoom:r,duration:this.duration_,easing:KW})):e.setZoom(r)}}}function GK(t){t=t||{};const e=new SV;return(void 0===t.zoom||t.zoom)&&e.push(new HK(t.zoomOptions)),(void 0===t.rotate||t.rotate)&&e.push(new WK(t.rotateOptions)),(void 0===t.attribution||t.attribution)&&e.push(new VK(t.attributionOptions)),e}class KK{constructor(t,e,n){this.decay_=t,this.minVelocity_=e,this.delay_=n,this.points_=[],this.angle_=0,this.initialVelocity_=0}begin(){this.points_.length=0,this.angle_=0,this.initialVelocity_=0}update(t,e){this.points_.push(t,e,Date.now())}end(){if(this.points_.length<6)return!1;const t=Date.now()-this.delay_,e=this.points_.length-3;if(this.points_[e+2]0&&this.points_[n+2]>t;)n-=3;const r=this.points_[e+2]-this.points_[n+2];if(r<1e3/60)return!1;const i=this.points_[e]-this.points_[n],s=this.points_[e+1]-this.points_[n+1];return this.angle_=Math.atan2(s,i),this.initialVelocity_=Math.sqrt(i*i+s*s)/r,this.initialVelocity_>this.minVelocity_}getDistance(){return(this.minVelocity_-this.initialVelocity_)/this.decay_}getAngle(){return this.angle_}}const ZK="active";class YK extends _V{constructor(t){super(),this.on,this.once,this.un,t&&t.handleEvent&&(this.handleEvent=t.handleEvent),this.map_=null,this.setActive(!0)}getActive(){return this.get(ZK)}getMap(){return this.map_}handleEvent(t){return!0}setActive(t){this.set(ZK,t)}setMap(t){this.map_=t}}function XK(t,e,n,r){const i=t.getZoom();if(void 0===i)return;const s=t.getConstrainedZoom(i+e),o=t.getResolutionForZoom(s);t.getAnimating()&&t.cancelAnimations(),t.animate({resolution:o,anchor:n,duration:void 0!==r?r:250,easing:KW})}class JK extends YK{constructor(t){super(),t=t||{},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:250}handleEvent(t){let e=!1;if(t.type==TV.DBLCLICK){const n=t.originalEvent,r=t.map,i=t.coordinate,s=n.shiftKey?-this.delta_:this.delta_;XK(r.getView(),s,i,this.duration_),n.preventDefault(),e=!0}return!e}}function QK(t){const e=arguments;return function(t){let n=!0;for(let r=0,i=e.length;r0}}else if(t.type==TV.POINTERDOWN){const n=this.handleDownEvent(t);this.handlingDownUpSequence=n,e=this.stopDown(n)}else t.type==TV.POINTERMOVE&&this.handleMoveEvent(t);return!e}handleMoveEvent(t){}handleUpEvent(t){return!1}stopDown(t){return t}updateTrackedPointers_(t){t.activePointers&&(this.targetPointers=t.activePointers)}}function uZ(t){const e=t.length;let n=0,r=0;for(let i=0;i0&&this.condition_(t)){const e=t.map.getView();return this.lastCentroid=null,e.getAnimating()&&e.cancelAnimations(),this.kinetic_&&this.kinetic_.begin(),this.noKinetic_=this.targetPointers.length>1,!0}return!1}}class dZ extends cZ{constructor(t){t=t||{},super({stopDown:sV}),this.condition_=t.condition?t.condition:tZ,this.lastAngle_=void 0,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){if(!aZ(t))return;const e=t.map,n=e.getView();if(n.getConstraints().rotation===bK)return;const r=e.getSize(),i=t.pixel,s=Math.atan2(r[1]/2-i[1],i[0]-r[0]/2);if(void 0!==this.lastAngle_){const t=s-this.lastAngle_;n.adjustRotationInternal(-t)}this.lastAngle_=s}handleUpEvent(t){return!aZ(t)||(t.map.getView().endInteraction(this.duration_),!1)}handleDownEvent(t){return!(!aZ(t)||!rZ(t)||!this.condition_(t)||(t.map.getView().beginInteraction(),this.lastAngle_=void 0,0))}}class pZ extends Xq{constructor(t){super(),this.geometry_=null,this.element_=document.createElement("div"),this.element_.style.position="absolute",this.element_.style.pointerEvents="auto",this.element_.className="ol-box "+t,this.map_=null,this.startPixel_=null,this.endPixel_=null}disposeInternal(){this.setMap(null)}render_(){const t=this.startPixel_,e=this.endPixel_,n="px",r=this.element_.style;r.left=Math.min(t[0],e[0])+n,r.top=Math.min(t[1],e[1])+n,r.width=Math.abs(e[0]-t[0])+n,r.height=Math.abs(e[1]-t[1])+n}setMap(t){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);const t=this.element_.style;t.left="inherit",t.top="inherit",t.width="inherit",t.height="inherit"}this.map_=t,this.map_&&this.map_.getOverlayContainer().appendChild(this.element_)}setPixels(t,e){this.startPixel_=t,this.endPixel_=e,this.createOrUpdateGeometry(),this.render_()}createOrUpdateGeometry(){if(!this.map_)return;const t=this.startPixel_,e=this.endPixel_,n=[t,[t[0],e[1]],e,[e[0],t[1]]].map(this.map_.getCoordinateFromPixelInternal,this.map_);n[4]=n[0].slice(),this.geometry_?this.geometry_.setCoordinates([n]):this.geometry_=new fK([n])}getGeometry(){return this.geometry_}}const fZ="boxcancel";class gZ extends hV{constructor(t,e,n){super(t),this.coordinate=e,this.mapBrowserEvent=n}}class mZ extends cZ{constructor(t){super(),this.on,this.once,this.un,t=t??{},this.box_=new pZ(t.className||"ol-dragbox"),this.minArea_=t.minArea??64,t.onBoxEnd&&(this.onBoxEnd=t.onBoxEnd),this.startPixel_=null,this.condition_=t.condition??rZ,this.boxEndCondition_=t.boxEndCondition??this.defaultBoxEndCondition}defaultBoxEndCondition(t,e,n){const r=n[0]-e[0],i=n[1]-e[1];return r*r+i*i>=this.minArea_}getGeometry(){return this.box_.getGeometry()}handleDragEvent(t){this.startPixel_&&(this.box_.setPixels(this.startPixel_,t.pixel),this.dispatchEvent(new gZ("boxdrag",t.coordinate,t)))}handleUpEvent(t){if(!this.startPixel_)return!1;const e=this.boxEndCondition_(t,this.startPixel_,t.pixel);return e&&this.onBoxEnd(t),this.dispatchEvent(new gZ(e?"boxend":fZ,t.coordinate,t)),this.box_.setMap(null),this.startPixel_=null,!1}handleDownEvent(t){return!!this.condition_(t)&&(this.startPixel_=t.pixel,this.box_.setMap(t.map),this.box_.setPixels(this.startPixel_,this.startPixel_),this.dispatchEvent(new gZ("boxstart",t.coordinate,t)),!0)}onBoxEnd(t){}setActive(t){t||(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new gZ(fZ,this.startPixel_,null)),this.startPixel_=null)),super.setActive(t)}setMap(t){this.getMap()&&(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new gZ(fZ,this.startPixel_,null)),this.startPixel_=null)),super.setMap(t)}}class yZ extends mZ{constructor(t){super({condition:(t=t||{}).condition?t.condition:sZ,className:t.className||"ol-dragzoom",minArea:t.minArea}),this.duration_=void 0!==t.duration?t.duration:200,this.out_=void 0!==t.out&&t.out}onBoxEnd(t){const e=this.getMap().getView();let n=this.getGeometry();if(this.out_){const t=e.rotatedExtentForGeometry(n),r=e.getResolutionForExtentInternal(t),i=e.getResolution()/r;n=n.clone(),n.scale(i*i)}e.fitInternal(n,{duration:this.duration_,easing:KW})}}const vZ="ArrowLeft",bZ="ArrowRight",wZ="ArrowDown";class _Z extends YK{constructor(t){super(),t=t||{},this.defaultCondition_=function(t){return iZ(t)&&oZ(t)},this.condition_=void 0!==t.condition?t.condition:this.defaultCondition_,this.duration_=void 0!==t.duration?t.duration:100,this.pixelDelta_=void 0!==t.pixelDelta?t.pixelDelta:128}handleEvent(t){let e=!1;if(t.type==Gq){const n=t.originalEvent,r=n.key;if(this.condition_(t)&&(r==wZ||r==vZ||r==bZ||"ArrowUp"==r)){const i=t.map.getView(),s=i.getResolution()*this.pixelDelta_;let o=0,a=0;r==wZ?a=-s:r==vZ?o=-s:r==bZ?o=s:a=s;const l=[o,a];WW(l,i.getRotation()),function(t,e,n){const r=t.getCenterInternal();if(r){const i=[r[0]+e[0],r[1]+e[1]];t.animateInternal({duration:void 0!==n?n:250,easing:YW,center:t.getConstrainedCenter(i)})}}(i,l,this.duration_),n.preventDefault(),e=!0}}return!e}}class xZ extends YK{constructor(t){super(),t=t||{},this.condition_=t.condition?t.condition:function(t){return!function(t){const e=t.originalEvent;return LV?e.metaKey:e.ctrlKey}(t)&&oZ(t)},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:100}handleEvent(t){let e=!1;if(t.type==Gq||t.type==Kq){const n=t.originalEvent,r=n.key;if(this.condition_(t)&&("+"===r||"-"===r)){const i=t.map,s="+"===r?this.delta_:-this.delta_;XK(i.getView(),s,void 0,this.duration_),n.preventDefault(),e=!0}}return!e}}class CZ extends YK{constructor(t){super(t=t||{}),this.totalDelta_=0,this.lastDelta_=0,this.maxDelta_=void 0!==t.maxDelta?t.maxDelta:1,this.duration_=void 0!==t.duration?t.duration:250,this.timeout_=void 0!==t.timeout?t.timeout:80,this.useAnchor_=void 0===t.useAnchor||t.useAnchor,this.constrainResolution_=void 0!==t.constrainResolution&&t.constrainResolution;const e=t.condition?t.condition:nZ;this.condition_=t.onFocusOnly?QK(eZ,e):e,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_,this.mode_=void 0,this.trackpadEventGap_=400,this.trackpadTimeoutId_,this.deltaPerZoom_=300}endInteraction_(){this.trackpadTimeoutId_=void 0;const t=this.getMap();t&&t.getView().endInteraction(void 0,this.lastDelta_?this.lastDelta_>0?1:-1:0,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null)}handleEvent(t){if(!this.condition_(t))return!0;if(t.type!==Yq)return!0;const e=t.map,n=t.originalEvent;n.preventDefault(),this.useAnchor_&&(this.lastAnchor_=t.pixel);let r=n.deltaY;switch(n.deltaMode){case WheelEvent.DOM_DELTA_LINE:r*=40;break;case WheelEvent.DOM_DELTA_PAGE:r*=300}if(0===r)return!1;this.lastDelta_=r;const i=Date.now();void 0===this.startTime_&&(this.startTime_=i),(!this.mode_||i-this.startTime_>this.trackpadEventGap_)&&(this.mode_=Math.abs(r)<4?"trackpad":"wheel");const s=e.getView();if("trackpad"===this.mode_&&!s.getConstrainResolution()&&!this.constrainResolution_)return this.trackpadTimeoutId_?clearTimeout(this.trackpadTimeoutId_):(s.getAnimating()&&s.cancelAnimations(),s.beginInteraction()),this.trackpadTimeoutId_=setTimeout(this.endInteraction_.bind(this),this.timeout_),s.adjustZoom(-r/this.deltaPerZoom_,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null),this.startTime_=i,!1;this.totalDelta_+=r;const o=Math.max(this.timeout_-(i-this.startTime_),0);return clearTimeout(this.timeoutId_),this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,e),o),!1}handleWheelZoom_(t){const e=t.getView();e.getAnimating()&&e.cancelAnimations();let n=-YV(this.totalDelta_,-this.maxDelta_*this.deltaPerZoom_,this.maxDelta_*this.deltaPerZoom_)/this.deltaPerZoom_;(e.getConstrainResolution()||this.constrainResolution_)&&(n=n?n>0?1:-1:0),XK(e,n,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null,this.duration_),this.mode_=void 0,this.totalDelta_=0,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_=void 0}setMouseAnchor(t){this.useAnchor_=t,t||(this.lastAnchor_=null)}}class SZ extends cZ{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=sV),super(e),this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.threshold_=void 0!==t.threshold?t.threshold:.3,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){let e=0;const n=this.targetPointers[0],r=this.targetPointers[1],i=Math.atan2(r.clientY-n.clientY,r.clientX-n.clientX);if(void 0!==this.lastAngle_){const t=i-this.lastAngle_;this.rotationDelta_+=t,!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_&&(this.rotating_=!0),e=t}this.lastAngle_=i;const s=t.map,o=s.getView();o.getConstraints().rotation!==bK&&(this.anchor_=s.getCoordinateFromPixelInternal(s.getEventPixel(uZ(this.targetPointers))),this.rotating_&&(s.render(),o.adjustRotationInternal(e,this.anchor_)))}handleUpEvent(t){return!(this.targetPointers.length<2&&(t.map.getView().endInteraction(this.duration_),1))}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}}class kZ extends cZ{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=sV),super(e),this.anchor_=null,this.duration_=void 0!==t.duration?t.duration:400,this.lastDistance_=void 0,this.lastScaleDelta_=1}handleDragEvent(t){let e=1;const n=this.targetPointers[0],r=this.targetPointers[1],i=n.clientX-r.clientX,s=n.clientY-r.clientY,o=Math.sqrt(i*i+s*s);void 0!==this.lastDistance_&&(e=this.lastDistance_/o),this.lastDistance_=o;const a=t.map,l=a.getView();1!=e&&(this.lastScaleDelta_=e),this.anchor_=a.getCoordinateFromPixelInternal(a.getEventPixel(uZ(this.targetPointers))),a.render(),l.adjustResolutionInternal(e,this.anchor_)}handleUpEvent(t){if(this.targetPointers.length<2){const e=t.map.getView(),n=this.lastScaleDelta_>1?1:-1;return e.endInteraction(this.duration_,n),!1}return!0}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}}function EZ(t){t=t||{};const e=new SV,n=new KK(-.005,.05,100);return(void 0===t.altShiftDragRotate||t.altShiftDragRotate)&&e.push(new dZ),(void 0===t.doubleClickZoom||t.doubleClickZoom)&&e.push(new JK({delta:t.zoomDelta,duration:t.zoomDuration})),(void 0===t.dragPan||t.dragPan)&&e.push(new hZ({onFocusOnly:t.onFocusOnly,kinetic:n})),(void 0===t.pinchRotate||t.pinchRotate)&&e.push(new SZ),(void 0===t.pinchZoom||t.pinchZoom)&&e.push(new kZ({duration:t.zoomDuration})),(void 0===t.keyboard||t.keyboard)&&(e.push(new _Z),e.push(new xZ({delta:t.zoomDelta,duration:t.zoomDuration}))),(void 0===t.mouseWheelZoom||t.mouseWheelZoom)&&e.push(new CZ({onFocusOnly:t.onFocusOnly,duration:t.zoomDuration})),(void 0===t.shiftDragZoom||t.shiftDragZoom)&&e.push(new yZ({duration:t.zoomDuration})),e}const TZ="opacity",RZ="visible",MZ="extent",LZ="zIndex",IZ="maxResolution",PZ="minResolution",AZ="maxZoom",OZ="minZoom",FZ="source";class zZ extends _V{constructor(t){super(),this.on,this.once,this.un,this.background_=t.background;const e=Object.assign({},t);"object"==typeof t.properties&&(delete e.properties,Object.assign(e,t.properties)),e[TZ]=void 0!==t.opacity?t.opacity:1,WV("number"==typeof e[TZ],"Layer opacity must be a number"),e[RZ]=void 0===t.visible||t.visible,e[LZ]=t.zIndex,e[IZ]=void 0!==t.maxResolution?t.maxResolution:1/0,e[PZ]=void 0!==t.minResolution?t.minResolution:0,e[OZ]=void 0!==t.minZoom?t.minZoom:-1/0,e[AZ]=void 0!==t.maxZoom?t.maxZoom:1/0,this.className_=void 0!==e.className?e.className:"ol-layer",delete e.className,this.setProperties(e),this.state_=null}getBackground(){return this.background_}getClassName(){return this.className_}getLayerState(t){const e=this.state_||{layer:this,managed:void 0===t||t},n=this.getZIndex();return e.opacity=YV(Math.round(100*this.getOpacity())/100,0,1),e.visible=this.getVisible(),e.extent=this.getExtent(),e.zIndex=void 0!==n||e.managed?n:1/0,e.maxResolution=this.getMaxResolution(),e.minResolution=Math.max(this.getMinResolution(),0),e.minZoom=this.getMinZoom(),e.maxZoom=this.getMaxZoom(),this.state_=e,e}getLayersArray(t){return yV()}getLayerStatesArray(t){return yV()}getExtent(){return this.get(MZ)}getMaxResolution(){return this.get(IZ)}getMinResolution(){return this.get(PZ)}getMinZoom(){return this.get(OZ)}getMaxZoom(){return this.get(AZ)}getOpacity(){return this.get(TZ)}getSourceState(){return yV()}getVisible(){return this.get(RZ)}getZIndex(){return this.get(LZ)}setBackground(t){this.background_=t,this.changed()}setExtent(t){this.set(MZ,t)}setMaxResolution(t){this.set(IZ,t)}setMinResolution(t){this.set(PZ,t)}setMaxZoom(t){this.set(AZ,t)}setMinZoom(t){this.set(OZ,t)}setOpacity(t){WV("number"==typeof t,"Layer opacity must be a number"),this.set(TZ,t)}setVisible(t){this.set(RZ,t)}setZIndex(t){this.set(LZ,t)}disposeInternal(){this.state_&&(this.state_.layer=null,this.state_=null),super.disposeInternal()}}const DZ="addlayer",NZ="removelayer";class jZ extends hV{constructor(t,e){super(t),this.layer=e}}const BZ="layers";class UZ extends zZ{constructor(t){t=t||{};const e=Object.assign({},t);delete e.layers;let n=t.layers;super(e),this.on,this.once,this.un,this.layersListenerKeys_=[],this.listenerKeys_={},this.addChangeListener(BZ,this.handleLayersChanged_),n?Array.isArray(n)?n=new SV(n.slice(),{unique:!0}):WV("function"==typeof n.getArray,"Expected `layers` to be an array or a `Collection`"):n=new SV(void 0,{unique:!0}),this.setLayers(n)}handleLayerChange_(){this.changed()}handleLayersChanged_(){this.layersListenerKeys_.forEach(gV),this.layersListenerKeys_.length=0;const t=this.getLayers();this.layersListenerKeys_.push(pV(t,Uq,this.handleLayersAdd_,this),pV(t,$q,this.handleLayersRemove_,this));for(const n in this.listenerKeys_)this.listenerKeys_[n].forEach(gV);cV(this.listenerKeys_);const e=t.getArray();for(let n=0,r=e.length;n{this.dispatchEvent("sourceready")},0))),this.changed()}getFeatures(t){return this.renderer_?this.renderer_.getFeatures(t):Promise.resolve([])}getData(t){return this.renderer_&&this.rendered?this.renderer_.getData(t):null}isVisible(t){let e;const n=this.getMapInternal();let r;if(!t&&n&&(t=n.getView()),e=t instanceof _K?{viewState:t.getState(),extent:t.calculateExtent()}:t,!e.layerStatesArray&&n&&(e.layerStatesArray=n.getLayerGroup().getLayerStatesArray()),e.layerStatesArray){if(r=e.layerStatesArray.find(t=>t.layer===this),!r)return!1}else r=this.getLayerState();const i=this.getExtent();return GZ(r,e.viewState)&&(!i||jW(i,e.extent))}getAttributions(t){if(!this.isVisible(t))return[];const e=this.getSource()?.getAttributions();if(!e)return[];let n=e(t instanceof _K?t.getViewStateAndExtent():t);return Array.isArray(n)||(n=[n]),n}render(t,e){const n=this.getRenderer();return n.prepareFrame(t)?(this.rendered=!0,n.renderFrame(t,e)):null}unrender(){this.rendered=!1}getDeclutter(){}renderDeclutter(t,e){}renderDeferred(t){const e=this.getRenderer();e&&e.renderDeferred(t)}setMapInternal(t){t||this.unrender(),this.set("map",t)}getMapInternal(){return this.get("map")}setMap(t){this.mapPrecomposeKey_&&(gV(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),t||this.changed(),this.mapRenderKey_&&(gV(this.mapRenderKey_),this.mapRenderKey_=null),t&&(this.mapPrecomposeKey_=pV(t,VZ,this.handlePrecompose_,this),this.mapRenderKey_=pV(this,Vq,t.render,t),this.changed())}handlePrecompose_(t){const e=t.frameState.layerStatesArray,n=this.getLayerState(!1);WV(!e.some(t=>t.layer===n.layer),"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both."),e.push(n)}setSource(t){this.set(FZ,t)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}clearRenderer(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_)}disposeInternal(){this.clearRenderer(),this.setSource(null),super.disposeInternal()}}function GZ(t,e){if(!t.visible)return!1;const n=e.resolution;if(n=t.maxResolution)return!1;const r=e.zoom;return r>t.minZoom&&r<=t.maxZoom}function KZ(t,e,n=0,r=t.length-1,i=YZ){for(;r>n;){if(r-n>600){const s=r-n+1,o=e-n+1,a=Math.log(s),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(s-l)/s)*(o-s/2<0?-1:1);KZ(t,e,Math.max(n,Math.floor(e-o*l/s+c)),Math.min(r,Math.floor(e+(s-o)*l/s+c)),i)}const s=t[e];let o=n,a=r;for(ZZ(t,n,e),i(t[r],s)>0&&ZZ(t,n,r);o0;)a--}0===i(t[n],s)?ZZ(t,n,a):(a++,ZZ(t,a,r)),a<=e&&(n=a+1),e<=a&&(r=a-1)}}function ZZ(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function YZ(t,e){return te?1:0}let XZ=class{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const n=[];if(!cY(t,e))return n;const r=this.toBBox,i=[];for(;e;){for(let s=0;s=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}_split(t,e){const n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);const s=this._chooseSplitIndex(n,i,r),o=uY(n.children.splice(s,n.children.length-s));o.height=n.height,o.leaf=n.leaf,QZ(n,this.toBBox),QZ(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(n,o)}_splitRoot(t,e){this.data=uY([t,e]),this.data.height=t.height+1,this.data.leaf=!1,QZ(this.data,this.toBBox)}_chooseSplitIndex(t,e,n){let r,i=1/0,s=1/0;for(let o=e;o<=n-e;o++){const e=tY(t,0,o,this.toBBox),a=tY(t,o,n,this.toBBox),l=aY(e,a),c=iY(e)+iY(a);l=e;l--){const e=t.children[l];eY(o,t.leaf?i(e):e),a+=sY(o)}return a}_adjustParentBBoxes(t,e,n){for(let r=n;r>=0;r--)eY(e[r],t)}_condense(t){for(let e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children,e.splice(e.indexOf(t[n]),1)):this.clear():QZ(t[n],this.toBBox)}};function JZ(t,e,n){if(!n)return e.indexOf(t);for(let r=0;r=t.minX&&e.maxY>=t.minY}function uY(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function hY(t,e,n,r,i){const s=[e,n];for(;s.length;){if((n=s.pop())-(e=s.pop())<=r)continue;const o=e+Math.ceil((n-e)/r/2)*r;KZ(t,o,e,n,i),s.push(e,o,o,n)}}const dY=[NaN,NaN,NaN,0];let pY;const fY=/^rgba?\(\s*(\d+%?)\s+(\d+%?)\s+(\d+%?)(?:\s*\/\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,gY=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,mY=/^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,yY=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;function vY(t,e){return t.endsWith("%")?Number(t.substring(0,t.length-1))/e:Number(t)}function bY(t){throw new Error('failed to parse "'+t+'" as color')}function wY(t){if(t.toLowerCase().startsWith("rgb")){const e=t.match(gY)||t.match(fY)||t.match(mY);if(e){const t=e[4],n=100/255;return[YV(vY(e[1],n)+.5|0,0,255),YV(vY(e[2],n)+.5|0,0,255),YV(vY(e[3],n)+.5|0,0,255),void 0!==t?YV(vY(t,100),0,1):1]}bY(t)}if(t.startsWith("#")){if(yY.test(t)){const e=t.substring(1),n=e.length<=4?1:2,r=[0,0,0,255];for(let t=0,i=e.length;t.0031308?269.025*Math.pow(t,1/2.4)-14.025:3294.6*t}function kY(t){return t>.2068965?Math.pow(t,3):108/841*(t-4/29)}function EY(t){return t>10.314724?Math.pow((t+14.025)/269.025,2.4):t/3294.6}function TY(t){return t>.0088564?Math.pow(t,1/3):t/(108/841)+4/29}function RY(t){const e=EY(t[0]),n=EY(t[1]),r=EY(t[2]),i=TY(.222488403*e+.716873169*n+.06060791*r),s=500*(TY(.452247074*e+.399439023*n+.148375274*r)-i),o=200*(i-TY(.016863605*e+.117638439*n+.865350722*r)),a=Math.atan2(o,s)*(180/Math.PI);return[116*i-16,Math.sqrt(s*s+o*o),a<0?a+360:a,t[3]]}function MY(t){if("none"===t)return dY;if(_Y.hasOwnProperty(t))return _Y[t];if(xY>=1024){let t=0;for(const e in _Y)3&t++||(delete _Y[e],--xY)}const e=wY(t);4!==e.length&&bY(t);for(const n of e)isNaN(n)&&bY(t);return _Y[t]=e,++xY,e}function LY(t){return Array.isArray(t)?t:MY(t)}function IY(t){let e=t[0];e!=(0|e)&&(e=e+.5|0);let n=t[1];n!=(0|n)&&(n=n+.5|0);let r=t[2];return r!=(0|r)&&(r=r+.5|0),"rgba("+e+","+n+","+r+","+(void 0===t[3]?1:Math.round(1e3*t[3])/1e3)+")"}function PY(t){return t[0]>0&&t[1]>0}function AY(t,e){return Array.isArray(t)?t:(void 0===e?e=[t,t]:(e[0]=t,e[1]=t),e)}let OY=0;const FY=1<e)throw new Error(`expected ${e===1/0?`${t} or more`:`${t} to ${e}`} arguments for ${r}, got ${i}`)}}function ZX(t,e,n){const r=t.length-1,i=new Array(r);for(let s=0;s{for(let e=0;e{for(let i=0;i{const r=t.args;let i=n.properties[e];for(let t=1,e=r.length;tt.variables[e];case qX:return n=>{const r=t.args;if(!(e in n.properties))return!1;let i=n.properties[e];for(let t=1,e=r.length;tt.featureId;case tX:return t=>t.geometryType;case QY:{const e=t.args.map(t=>eJ(t));return t=>"".concat(...e.map(e=>e(t).toString()))}case sX:return t=>t.resolution;case nX:case rX:case LX:case OX:case"!":return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{for(let e=0;e{for(let e=0;e{const e=r[0](t),n=r[1](t),i=r[2](t);return e>=n&&e<=i};case OX:return t=>{const e=r[0](t);for(let i=1;i!r[0](t);default:throw new Error(`Unsupported logical operator ${e}`)}}(t);case lX:case cX:case"<":case pX:case">":case hX:return function(t){const e=t.operator,n=eJ(t.args[0]),r=eJ(t.args[1]);switch(e){case lX:return t=>n(t)===r(t);case cX:return t=>n(t)!==r(t);case"<":return t=>n(t)n(t)<=r(t);case">":return t=>n(t)>r(t);case hX:return t=>n(t)>=r(t);default:throw new Error(`Unsupported comparison operator ${e}`)}}(t);case"*":case"/":case"+":case"-":case vX:case"%":case"^":case _X:case xX:case CX:case SX:case kX:case EX:case TX:case RX:return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{let e=1;for(let i=0;ir[0](t)/r[1](t);case"+":return t=>{let e=0;for(let i=0;ir[0](t)-r[1](t);case vX:return t=>{const e=r[0](t),n=r[1](t);if(ei?i:e};case"%":return t=>r[0](t)%r[1](t);case"^":return t=>Math.pow(r[0](t),r[1](t));case _X:return t=>Math.abs(r[0](t));case xX:return t=>Math.floor(r[0](t));case CX:return t=>Math.ceil(r[0](t));case SX:return t=>Math.round(r[0](t));case kX:return t=>Math.sin(r[0](t));case EX:return t=>Math.cos(r[0](t));case TX:return 2===n?t=>Math.atan2(r[0](t),r[1](t)):t=>Math.atan(r[0](t));case RX:return t=>Math.sqrt(r[0](t));default:throw new Error(`Unsupported numeric operator ${e}`)}}(t);case AX:return function(t){const e=t.args.length,n=new Array(e);for(let r=0;r{for(let r=0;r{const r=n[0](t);for(let i=1;i{const r=n[0](t),i=n[1](t);let s,o;for(let a=2;a=i)return 2===a?l:c?rJ(r,i,s,o,e,l):nJ(r,i,s,o,e,l);s=e,o=l}return o}}(t);case $X:return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{const n=r[0](e);return t.args[0].type===NY?IY(n):n.toString()};throw new Error(`Unsupported convert operator ${e}`)}(t);default:throw new Error(`Unsupported operator ${e}`)}}function nJ(t,e,n,r,i,s){const o=i-n;if(0===o)return r;const a=e-n;return r+(1===t?a/o:(Math.pow(t,a)-1)/(Math.pow(t,o)-1))*(s-r)}function rJ(t,e,n,r,i,s){if(0===i-n)return r;const o=RY(r),a=RY(s);let l=a[2]-o[2];return l>180?l-=360:l<-180&&(l+=360),function(t){const e=(t[0]+16)/116,n=t[1],r=t[2]*Math.PI/180,i=kY(e),s=kY(e+n/500*Math.cos(r)),o=kY(e-n/200*Math.sin(r)),a=SY(3.021973625*s-1.617392459*i-.404875592*o),l=SY(-.943766287*s+1.916279586*i+.027607165*o),c=SY(.069407491*s-.22898585*i+1.159737864*o);return[YV(a+.5|0,0,255),YV(l+.5|0,0,255),YV(c+.5|0,0,255),t[3]]}([nJ(t,e,n,o[0],i,a[0]),nJ(t,e,n,o[1],i,a[1]),o[2]+nJ(t,e,n,0,i,l),nJ(t,e,n,r[3],i,s[3])])}class iJ extends dV{constructor(t,e,n,r){super(),this.extent=t,this.pixelRatio_=n,this.resolution=e,this.state="function"==typeof r?0:r,this.image_=null,this.loader="function"==typeof r?r:null}changed(){this.dispatchEvent(Vq)}getExtent(){return this.extent}getImage(){return this.image_}getPixelRatio(){return this.pixelRatio_}getResolution(){return this.resolution}getState(){return this.state}load(){if(0==this.state&&this.loader){this.state=1,this.changed();const t=this.getResolution(),e=Array.isArray(t)?t[0]:t;lV(()=>this.loader(this.getExtent(),e,this.getPixelRatio())).then(t=>{"image"in t&&(this.image_=t.image),"extent"in t&&(this.extent=t.extent),"resolution"in t&&(this.resolution=t.resolution),"pixelRatio"in t&&(this.pixelRatio_=t.pixelRatio),(t instanceof HTMLImageElement||OV&&t instanceof ImageBitmap||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)&&(this.image_=t),this.state=2}).catch(t=>{this.state=3,console.error(t)}).finally(()=>this.changed())}}setImage(t){this.image_=t}setResolution(t){this.resolution=t}}function sJ(t,e,n){return e+":"+t+":"+(n?LY(n):"null")}const oJ=new class{constructor(){this.cache_={},this.patternCache_={},this.cacheSize_=0,this.maxCacheSize_=1024}clear(){this.cache_={},this.patternCache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let t=0;for(const e in this.cache_){const n=this.cache_[e];3&t++||n.hasListener()||(delete this.cache_[e],delete this.patternCache_[e],--this.cacheSize_)}}}get(t,e,n){const r=sJ(t,e,n);return r in this.cache_?this.cache_[r]:null}getPattern(t,e,n){const r=sJ(t,e,n);return r in this.patternCache_?this.patternCache_[r]:null}set(t,e,n,r,i){const s=sJ(t,e,n),o=s in this.cache_;this.cache_[s]=r,i&&(0===r.getImageState()&&r.load(),1===r.getImageState()?r.ready().then(()=>{this.patternCache_[s]=FK().createPattern(r.getImage(1),"repeat")}):this.patternCache_[s]=FK().createPattern(r.getImage(1),"repeat")),o||++this.cacheSize_}setSize(t){this.maxCacheSize_=t,this.expire()}};let aJ=null;class lJ extends dV{constructor(t,e,n,r,i){super(),this.hitDetectionImage_=null,this.image_=t,this.crossOrigin_=n,this.canvas_={},this.color_=i,this.imageState_=void 0===r?0:r,this.size_=t&&t.width&&t.height?[t.width,t.height]:null,this.src_=e,this.tainted_,this.ready_=null}initializeImage_(){this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)}isTainted_(){if(void 0===this.tainted_&&2===this.imageState_){aJ||(aJ=AK(1,1,void 0,{willReadFrequently:!0})),aJ.drawImage(this.image_,0,0);try{aJ.getImageData(0,0,1,1),this.tainted_=!1}catch{aJ=null,this.tainted_=!0}}return!0===this.tainted_}dispatchChangeEvent_(){this.dispatchEvent(Vq)}handleImageError_(){this.imageState_=3,this.dispatchChangeEvent_()}handleImageLoad_(){this.imageState_=2,this.size_=[this.image_.width,this.image_.height],this.dispatchChangeEvent_()}getImage(t){return this.image_||this.initializeImage_(),this.replaceColor_(t),this.canvas_[t]?this.canvas_[t]:this.image_}getPixelRatio(t){return this.replaceColor_(t),this.canvas_[t]?t:1}getImageState(){return this.imageState_}getHitDetectionImage(){if(this.image_||this.initializeImage_(),!this.hitDetectionImage_)if(this.isTainted_()){const t=this.size_[0],e=this.size_[1],n=AK(t,e);n.fillRect(0,0,t,e),this.hitDetectionImage_=n.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_}getSize(){return this.size_}getSrc(){return this.src_}load(){if(0===this.imageState_){this.image_||this.initializeImage_(),this.imageState_=1;try{void 0!==this.src_&&(this.image_.src=this.src_)}catch{this.handleImageError_()}this.image_ instanceof HTMLImageElement&&(t=this.image_,e=this.src_,e&&(t.src=e),t.src&&AV?new Promise((e,n)=>t.decode().then(()=>e(t)).catch(r=>t.complete&&t.width?e(t):n(r))):function(t){return new Promise((e,n)=>{function r(){s(),e(t)}function i(){s(),n(new Error("Image load error"))}function s(){t.removeEventListener("load",r),t.removeEventListener("error",i)}t.addEventListener("load",r),t.addEventListener("error",i)})}(t)).then(t=>{this.image_=t,this.handleImageLoad_()}).catch(this.handleImageError_.bind(this))}var t,e}replaceColor_(t){if(!this.color_||this.canvas_[t]||2!==this.imageState_)return;const e=this.image_,n=AK(Math.ceil(e.width*t),Math.ceil(e.height*t)),r=n.canvas;var i;n.scale(t,t),n.drawImage(e,0,0),n.globalCompositeOperation="multiply",n.fillStyle="string"==typeof(i=this.color_)?i:IY(i),n.fillRect(0,0,r.width/t,r.height/t),n.globalCompositeOperation="destination-in",n.drawImage(e,0,0),this.canvas_[t]=r}ready(){return this.ready_||(this.ready_=new Promise(t=>{if(2===this.imageState_||3===this.imageState_)t();else{const e=()=>{2!==this.imageState_&&3!==this.imageState_||(this.removeEventListener(Vq,e),t())};this.addEventListener(Vq,e)}})),this.ready_}}function cJ(t,e,n,r,i,s){let o=void 0===e?void 0:oJ.get(e,n,i);return o||(o=new lJ(t,t&&"src"in t?t.src||void 0:e,n,r,i),oJ.set(e,n,i,o,s)),s&&o&&!oJ.getPattern(e,n,i)&&oJ.set(e,n,i,o,s),o}function uJ(t){return t?Array.isArray(t)?IY(t):"object"==typeof t&&"src"in t?function(t){if(!t.offset||!t.size)return oJ.getPattern(t.src,"anonymous",t.color);const e=t.src+":"+t.offset,n=oJ.getPattern(e,void 0,t.color);if(n)return n;const r=oJ.get(t.src,"anonymous",null);if(2!==r.getImageState())return null;const i=AK(t.size[0],t.size[1]);return i.drawImage(r.getImage(1),t.offset[0],t.offset[1],t.size[0],t.size[1],0,0,t.size[0],t.size[1]),cJ(i.canvas,e,void 0,2,t.color,!0),oJ.getPattern(e,void 0,t.color)}(t):t:null}const hJ="10px sans-serif",dJ="#000",pJ="round",fJ=[],gJ="round",mJ="#000",yJ="center",vJ="middle",bJ=[0,0,0,0],wJ=new _V;let _J,xJ=null;const CJ={},SJ=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"]);function kJ(t,e,n){return`${t} ${e} 16px "${n}"`}const EJ=function(){const t=100;let e,n;async function r(t){await n.ready;const e=await n.load(t);if(0===e.length)return!1;const r=PK(t),i=r.families[0].toLowerCase(),s=r.weight;return e.some(t=>{const e=t.family.replace(/^['"]|['"]$/g,"").toLowerCase(),n=IK[t.weight]||t.weight;return e===i&&t.style===r.style&&n==s})}async function i(){await n.ready;let s=!0;const o=wJ.getProperties(),a=Object.keys(o).filter(e=>o[e]=0;--e){const n=a[e];let i=o[n];iMath.max(e,MJ(t,n)),0);return n[e]=r,r}class IJ{constructor(t){this.opacity_=t.opacity,this.rotateWithView_=t.rotateWithView,this.rotation_=t.rotation,this.scale_=t.scale,this.scaleArray_=AY(t.scale),this.displacement_=t.displacement,this.declutterMode_=t.declutterMode}clone(){const t=this.getScale();return new IJ({opacity:this.getOpacity(),scale:Array.isArray(t)?t.slice():t,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getOpacity(){return this.opacity_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getDisplacement(){return this.displacement_}getDeclutterMode(){return this.declutterMode_}getAnchor(){return yV()}getImage(t){return yV()}getHitDetectionImage(){return yV()}getPixelRatio(t){return 1}getImageState(){return yV()}getImageSize(){return yV()}getOrigin(){return yV()}getSize(){return yV()}setDisplacement(t){this.displacement_=t}setOpacity(t){this.opacity_=t}setRotateWithView(t){this.rotateWithView_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=AY(t)}listenImageChange(t){yV()}load(){yV()}unlistenImageChange(t){yV()}ready(){return Promise.resolve()}}class PJ extends IJ{constructor(t){super({opacity:1,rotateWithView:void 0!==t.rotateWithView&&t.rotateWithView,rotation:void 0!==t.rotation?t.rotation:0,scale:void 0!==t.scale?t.scale:1,displacement:void 0!==t.displacement?t.displacement:[0,0],declutterMode:t.declutterMode}),this.hitDetectionCanvas_=null,this.fill_=void 0!==t.fill?t.fill:null,this.origin_=[0,0],this.points_=t.points,this.radius=t.radius,this.radius2_=t.radius2,this.angle_=void 0!==t.angle?t.angle:0,this.stroke_=void 0!==t.stroke?t.stroke:null,this.size_,this.renderOptions_,this.imageState_=this.fill_&&this.fill_.loading()?1:2,1===this.imageState_&&this.ready().then(()=>this.imageState_=2),this.render()}clone(){const t=this.getScale(),e=new PJ({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return e.setOpacity(this.getOpacity()),e}getAnchor(){const t=this.size_,e=this.getDisplacement(),n=this.getScaleArray();return[t[0]/2-e[0]/n[0],t[1]/2+e[1]/n[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(t){this.fill_=t,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.createHitDetectionCanvas_(this.renderOptions_)),this.hitDetectionCanvas_}getImage(t){const e=this.fill_?.getKey(),n=`${t},${this.angle_},${this.radius},${this.radius2_},${this.points_},${e}`+Object.values(this.renderOptions_).join(",");let r=oJ.get(n,null,null)?.getImage(1);if(!r){const e=this.renderOptions_,i=Math.ceil(e.size*t),s=AK(i,i);this.draw_(e,s,t),r=s.canvas,oJ.set(n,null,null,new lJ(r,void 0,null,2,null))}return r}getPixelRatio(t){return t}getImageSize(){return this.size_}getImageState(){return this.imageState_}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t,this.render()}listenImageChange(t){}load(){}unlistenImageChange(t){}calculateLineJoinSize_(t,e,n){if(0===e||this.points_===1/0||"bevel"!==t&&"miter"!==t)return e;let r=this.radius,i=void 0===this.radius2_?r:this.radius2_;if(r{this.patternImage_=null}),0===e.getImageState()&&e.load(),1===e.getImageState()&&(this.patternImage_=e)}this.color_=t}getKey(){const t=this.getColor();return t?t instanceof CanvasPattern||t instanceof CanvasGradient?bV(t):"object"==typeof t&&"src"in t?t.src+":"+t.offset:LY(t).toString():""}loading(){return!!this.patternImage_}ready(){return this.patternImage_?this.patternImage_.ready():Promise.resolve()}}function FJ(t,e,n,r){return void 0!==n&&void 0!==r?[n/t,r/e]:void 0!==n?n/t:void 0!==r?r/e:1}class zJ extends IJ{constructor(t){const e=void 0!==(t=t||{}).opacity?t.opacity:1,n=void 0!==t.rotation?t.rotation:0,r=void 0!==t.scale?t.scale:1,i=void 0!==t.rotateWithView&&t.rotateWithView;super({opacity:e,rotation:n,scale:r,displacement:void 0!==t.displacement?t.displacement:[0,0],rotateWithView:i,declutterMode:t.declutterMode}),this.anchor_=void 0!==t.anchor?t.anchor:[.5,.5],this.normalizedAnchor_=null,this.anchorOrigin_=void 0!==t.anchorOrigin?t.anchorOrigin:"top-left",this.anchorXUnits_=void 0!==t.anchorXUnits?t.anchorXUnits:"fraction",this.anchorYUnits_=void 0!==t.anchorYUnits?t.anchorYUnits:"fraction",this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null;const s=void 0!==t.img?t.img:null;let o,a=t.src;if(WV(!(void 0!==a&&s),"`image` and `src` cannot be provided at the same time"),void 0!==a&&0!==a.length||!s||(a=s.src||bV(s)),WV(void 0!==a&&a.length>0,"A defined and non-empty `src` or `image` must be provided"),WV(!((void 0!==t.width||void 0!==t.height)&&void 0!==t.scale),"`width` or `height` cannot be provided together with `scale`"),void 0!==t.src?o=0:void 0!==s&&(o="complete"in s?s.complete?s.src?2:0:1:2),this.color_=void 0!==t.color?LY(t.color):null,this.iconImage_=cJ(s,a,this.crossOrigin_,o,this.color_),this.offset_=void 0!==t.offset?t.offset:[0,0],this.offsetOrigin_=void 0!==t.offsetOrigin?t.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==t.size?t.size:null,this.initialOptions_,void 0!==t.width||void 0!==t.height){let e,n;if(t.size)[e,n]=t.size;else{const r=this.getImage(1);if(r.width&&r.height)e=r.width,n=r.height;else if(r instanceof HTMLImageElement){this.initialOptions_=t;const e=()=>{if(this.unlistenImageChange(e),!this.initialOptions_)return;const n=this.iconImage_.getSize();this.setScale(FJ(n[0],n[1],t.width,t.height))};return void this.listenImageChange(e)}}void 0!==e&&this.setScale(FJ(e,n,t.width,t.height))}}clone(){let t,e,n;return this.initialOptions_?(e=this.initialOptions_.width,n=this.initialOptions_.height):(t=this.getScale(),t=Array.isArray(t)?t.slice():t),new zJ({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:t,width:e,height:n,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let t=this.normalizedAnchor_;if(!t){t=this.anchor_;const e=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!e)return null;t=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(t[0]*=e[0]),"fraction"==this.anchorYUnits_&&(t[1]*=e[1])}if("top-left"!=this.anchorOrigin_){if(!e)return null;t===this.anchor_&&(t=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[0]=-t[0]+e[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[1]=-t[1]+e[1])}this.normalizedAnchor_=t}const e=this.getDisplacement(),n=this.getScaleArray();return[t[0]-e[0]/n[0],t[1]+e[1]/n[1]]}setAnchor(t){this.anchor_=t,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(t){return this.iconImage_.getImage(t)}getPixelRatio(t){return this.iconImage_.getPixelRatio(t)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let t=this.offset_;if("top-left"!=this.offsetOrigin_){const e=this.getSize(),n=this.iconImage_.getSize();if(!e||!n)return null;t=t.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[0]=n[0]-e[0]-t[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[1]=n[1]-e[1]-t[1])}return this.origin_=t,this.origin_}getSrc(){return this.iconImage_.getSrc()}setSrc(t){this.iconImage_=cJ(null,t,this.crossOrigin_,0,this.color_)}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const t=this.getScaleArray();return this.size_?this.size_[0]*t[0]:2==this.iconImage_.getImageState()?this.iconImage_.getSize()[0]*t[0]:void 0}getHeight(){const t=this.getScaleArray();return this.size_?this.size_[1]*t[1]:2==this.iconImage_.getImageState()?this.iconImage_.getSize()[1]*t[1]:void 0}setScale(t){delete this.initialOptions_,super.setScale(t)}listenImageChange(t){this.iconImage_.addEventListener(Vq,t)}load(){this.iconImage_.load()}unlistenImageChange(t){this.iconImage_.removeEventListener(Vq,t)}ready(){return this.iconImage_.ready()}}class DJ{constructor(t){t=t||{},this.color_=void 0!==t.color?t.color:null,this.lineCap_=t.lineCap,this.lineDash_=void 0!==t.lineDash?t.lineDash:null,this.lineDashOffset_=t.lineDashOffset,this.lineJoin_=t.lineJoin,this.miterLimit_=t.miterLimit,this.width_=t.width}clone(){const t=this.getColor();return new DJ({color:Array.isArray(t)?t.slice():t||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(t){this.color_=t}setLineCap(t){this.lineCap_=t}setLineDash(t){this.lineDash_=t}setLineDashOffset(t){this.lineDashOffset_=t}setLineJoin(t){this.lineJoin_=t}setMiterLimit(t){this.miterLimit_=t}setWidth(t){this.width_=t}}class NJ{constructor(t){t=t||{},this.geometry_=null,this.geometryFunction_=UJ,void 0!==t.geometry&&this.setGeometry(t.geometry),this.fill_=void 0!==t.fill?t.fill:null,this.image_=void 0!==t.image?t.image:null,this.renderer_=void 0!==t.renderer?t.renderer:null,this.hitDetectionRenderer_=void 0!==t.hitDetectionRenderer?t.hitDetectionRenderer:null,this.stroke_=void 0!==t.stroke?t.stroke:null,this.text_=void 0!==t.text?t.text:null,this.zIndex_=t.zIndex}clone(){let t=this.getGeometry();return t&&"object"==typeof t&&(t=t.clone()),new NJ({geometry:t??void 0,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer()??void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(t){this.renderer_=t}setHitDetectionRenderer(t){this.hitDetectionRenderer_=t}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(t){this.fill_=t}getImage(){return this.image_}setImage(t){this.image_=t}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t}getText(){return this.text_}setText(t){this.text_=t}getZIndex(){return this.zIndex_}setGeometry(t){"function"==typeof t?this.geometryFunction_=t:"string"==typeof t?this.geometryFunction_=function(e){return e.get(t)}:t?void 0!==t&&(this.geometryFunction_=function(){return t}):this.geometryFunction_=UJ,this.geometry_=t}setZIndex(t){this.zIndex_=t}}let jJ=null;function BJ(){if(!jJ){const t=new OJ({color:"rgba(255,255,255,0.4)"}),e=new DJ({color:"#3399CC",width:1.25});jJ=[new NJ({image:new AJ({fill:t,stroke:e,radius:5}),fill:t,stroke:e})]}return jJ}function UJ(t){return t.getGeometry()}let $J=class t{constructor(t){t=t||{},this.font_=t.font,this.rotation_=t.rotation,this.rotateWithView_=t.rotateWithView,this.keepUpright_=t.keepUpright,this.scale_=t.scale,this.scaleArray_=AY(void 0!==t.scale?t.scale:1),this.text_=t.text,this.textAlign_=t.textAlign,this.justify_=t.justify,this.repeat_=t.repeat,this.textBaseline_=t.textBaseline,this.fill_=void 0!==t.fill?t.fill:new OJ({color:"#333"}),this.maxAngle_=void 0!==t.maxAngle?t.maxAngle:Math.PI/4,this.placement_=void 0!==t.placement?t.placement:"point",this.overflow_=!!t.overflow,this.stroke_=void 0!==t.stroke?t.stroke:null,this.offsetX_=void 0!==t.offsetX?t.offsetX:0,this.offsetY_=void 0!==t.offsetY?t.offsetY:0,this.backgroundFill_=t.backgroundFill?t.backgroundFill:null,this.backgroundStroke_=t.backgroundStroke?t.backgroundStroke:null,this.padding_=void 0===t.padding?null:t.padding,this.declutterMode_=t.declutterMode}clone(){const e=this.getScale();return new t({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),keepUpright:this.getKeepUpright(),scale:Array.isArray(e)?e.slice():e,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()instanceof OJ?this.getFill().clone():this.getFill(),stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0,declutterMode:this.getDeclutterMode()})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getKeepUpright(){return this.keepUpright_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}getDeclutterMode(){return this.declutterMode_}setOverflow(t){this.overflow_=t}setFont(t){this.font_=t}setMaxAngle(t){this.maxAngle_=t}setOffsetX(t){this.offsetX_=t}setOffsetY(t){this.offsetY_=t}setPlacement(t){this.placement_=t}setRepeat(t){this.repeat_=t}setRotateWithView(t){this.rotateWithView_=t}setKeepUpright(t){this.keepUpright_=t}setFill(t){this.fill_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=AY(void 0!==t?t:1)}setStroke(t){this.stroke_=t}setText(t){this.text_=t}setTextAlign(t){this.textAlign_=t}setJustify(t){this.justify_=t}setTextBaseline(t){this.textBaseline_=t}setBackgroundFill(t){this.backgroundFill_=t}setBackgroundStroke(t){this.backgroundStroke_=t}setPadding(t){this.padding_=t}};function qJ(){return!0}function VJ(t){const e=ZY(),n=function(t,e){const n=t.length,r=new Array(n);for(let i=0;inull;r=JJ(t,e+"fill-color",n)}if(!r)return null;const i=new OJ;return function(t){const e=r(t);return e===dY?null:(i.setColor(e),i)}}function KJ(t,e,n){const r=ZJ(t,e+"stroke-width",n),i=JJ(t,e+"stroke-color",n);if(!r&&!i)return null;const s=YJ(t,e+"stroke-line-cap",n),o=YJ(t,e+"stroke-line-join",n),a=QJ(t,e+"stroke-line-dash",n),l=ZJ(t,e+"stroke-line-dash-offset",n),c=ZJ(t,e+"stroke-miter-limit",n),u=new DJ;return function(t){if(i){const e=i(t);if(e===dY)return null;u.setColor(e)}if(r&&u.setWidth(r(t)),s){const e=s(t);if("butt"!==e&&"round"!==e&&"square"!==e)throw new Error("Expected butt, round, or square line cap");u.setLineCap(e)}if(o){const e=o(t);if("bevel"!==e&&"round"!==e&&"miter"!==e)throw new Error("Expected bevel, round, or miter line join");u.setLineJoin(e)}return a&&u.setLineDash(a(t)),l&&u.setLineDashOffset(l(t)),c&&u.setMiterLimit(c(t)),u}}function ZJ(t,e,n){if(!(e in t))return;const r=tJ(t[e],zY,n);return function(t){return cQ(r(t),e)}}function YJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],DY,n);return function(t){return lQ(r(t),e)}}function XJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],FY,n);return function(t){const n=r(t);if("boolean"!=typeof n)throw new Error(`Expected a boolean for ${e}`);return n}}function JJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],NY,n);return function(t){return uQ(r(t),e)}}function QJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){return aQ(r(t),e)}}function tQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){const n=aQ(r(t),e);if(2!==n.length)throw new Error(`Expected two numbers for ${e}`);return n}}function eQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){return hQ(r(t),e)}}function nQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY|zY,n);return function(t){return function(t,e){return"number"==typeof t?t:hQ(t,e)}(r(t),e)}}function rQ(t,e){const n=t[e];if(void 0!==n){if("number"!=typeof n)throw new Error(`Expected a number for ${e}`);return n}}function iQ(t,e){const n=t[e];if(void 0!==n){if("bottom-left"!==n&&"bottom-right"!==n&&"top-left"!==n&&"top-right"!==n)throw new Error(`Expected bottom-left, bottom-right, top-left, or top-right for ${e}`);return n}}function sQ(t,e){const n=t[e];if(void 0!==n){if("pixels"!==n&&"fraction"!==n)throw new Error(`Expected pixels or fraction for ${e}`);return n}}function oQ(t,e){const n=t[e];if(void 0!==n){if("string"!=typeof n)throw new Error(`Expected a string for ${e}`);if("declutter"!==n&&"obstacle"!==n&&"none"!==n)throw new Error(`Expected declutter, obstacle, or none for ${e}`);return n}}function aQ(t,e){if(!Array.isArray(t))throw new Error(`Expected an array for ${e}`);const n=t.length;for(let r=0;r4)throw new Error(`Expected a color with 3 or 4 values for ${e}`);return n}function hQ(t,e){const n=aQ(t,e);if(2!==n.length)throw new Error(`Expected an array of two numbers for ${e}`);return n}const dQ="renderOrder";class pQ extends HZ{constructor(t){t=t||{};const e=Object.assign({},t);delete e.style,delete e.renderBuffer,delete e.updateWhileAnimating,delete e.updateWhileInteracting,super(e),this.declutter_=t.declutter?String(t.declutter):void 0,this.renderBuffer_=void 0!==t.renderBuffer?t.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(t.style),this.updateWhileAnimating_=void 0!==t.updateWhileAnimating&&t.updateWhileAnimating,this.updateWhileInteracting_=void 0!==t.updateWhileInteracting&&t.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(t){return super.getFeatures(t)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(dQ)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(t,e){const n=this.getDeclutter();n in t.declutter==0&&(t.declutter[n]=new XZ(9)),this.getRenderer().renderDeclutter(t,e)}setRenderOrder(t){this.set(dQ,t)}setStyle(t){this.style_=void 0===t?BJ:t;const e=function(t){if(void 0===t)return BJ;if(!t)return null;if("function"==typeof t)return t;if(t instanceof NJ)return t;if(!Array.isArray(t))return WJ([t]);if(0===t.length)return[];const e=t.length,n=t[0];if(n instanceof NJ){const n=new Array(e);for(let r=0;r=0;--r){const i=f[r],s=i.layer;if(s.hasRenderer()&&GZ(i,c)&&o.call(a,s)){const r=s.getRenderer(),o=s.getSource();if(r&&o){const s=o.getWrapX()?d:t,a=u.bind(null,i.managed);y[0]=s[0]+p[b][0],y[1]=s[1]+p[b][1],l=r.forEachFeatureAtCoordinate(y,e,n,a,m)}if(l)return l}}if(0===m.length)return;const v=1/m.length;return m.forEach((t,e)=>t.distanceSq+=e*v),m.sort((t,e)=>t.distanceSq-e.distanceSq),m.some(t=>l=t.callback(t.feature,t.layer,t.geometry)),l}hasFeatureAtCoordinate(t,e,n,r,i,s){return void 0!==this.forEachFeatureAtCoordinate(t,e,n,r,iV,this,i,s)}getMap(){return this.map_}renderFrame(t){yV()}scheduleExpireIconCache(t){oJ.canExpireCache()&&t.postRenderFunctions.push(mQ)}}function mQ(){oJ.expire()}class yQ extends gQ{constructor(t){super(t),this.fontChangeListenerKey_=pV(wJ,qq,t.redrawText,t),this.element_=PV?UK():document.createElement("div");const e=this.element_.style;e.position="absolute",e.width="100%",e.height="100%",e.zIndex="0",this.element_.className=EK+" ol-layers";const n=t.getViewport();n&&n.insertBefore(this.element_,n.firstChild||null),this.children_=[],this.renderedVisible_=!0}dispatchRenderEvent(t,e){const n=this.getMap();if(n.hasListener(t)){const r=new fQ(t,void 0,e);n.dispatchEvent(r)}}disposeInternal(){gV(this.fontChangeListenerKey_),this.element_.remove(),super.disposeInternal()}renderFrame(t){if(!t)return void(this.renderedVisible_&&(this.element_.style.display="none",this.renderedVisible_=!1));this.calculateMatrices2D(t),this.dispatchRenderEvent(VZ,t);const e=t.layerStatesArray.sort((t,e)=>t.zIndex-e.zIndex);e.some(t=>t.layer instanceof pQ&&t.layer.getDeclutter())&&(t.declutter={});const n=t.viewState;this.children_.length=0;const r=[];let i=null;for(let o=0,a=e.length;o0)&&(t.fillStyle=r,t.fillRect(0,0,s.width,s.height)),$K(n)&&n.width>0){const r=e.style.opacity||n.style.opacity;t.globalAlpha=""===r?1:Number(r);const i=n.style.transform;if(i)t.setTransform(...CG(i));else{const e=parseFloat(n.style.width)/n.width,r=parseFloat(n.style.height)/n.height;t.setTransform(e,0,0,r,0,0)}t.drawImage(n,0,0)}}t.globalAlpha=1,t.setTransform(1,0,0,1,0,0)}this.dispatchRenderEvent("postcompose",t),this.renderedVisible_||(this.element_.style.display="",this.renderedVisible_=!0),this.scheduleExpireIconCache(t)}declutter(t,e){if(t.declutter){for(let n=e.length-1;n>=0;--n){const r=e[n],i=r.layer;i.getDeclutter()&&i.renderDeclutter(t,r)}e.forEach(e=>e.layer.renderDeferred(t))}}}function vQ(t){t instanceof HZ?t.setMapInternal(null):t instanceof UZ&&t.getLayers().forEach(vQ)}function bQ(t,e){if(t instanceof HZ)t.setMapInternal(e);else if(t instanceof UZ){const n=t.getLayers().getArray();for(let t=0,r=n.length;tthis.updateSize())),this.controls=e.controls||(PV?new SV:GK()),this.interactions=e.interactions||(PV?new SV:EZ({onFocusOnly:!0})),this.overlays_=e.overlays,this.overlayIdIndex_={},this.renderer_=null,this.postRenderFunctions_=[],this.tileQueue_=new KV(this.getTilePriority.bind(this),this.handleTileChange_.bind(this)),this.addChangeListener(UV,this.handleLayerGroupChanged_),this.addChangeListener(VV,this.handleViewChanged_),this.addChangeListener($V,this.handleSizeChanged_),this.addChangeListener(qV,this.handleTargetChanged_),this.setProperties(e.values);const n=this;!t.view||t.view instanceof _K||t.view.then(function(t){n.setView(new _K(t))}),this.controls.addEventListener(Uq,t=>{t.element.setMap(this)}),this.controls.addEventListener($q,t=>{t.element.setMap(null)}),this.interactions.addEventListener(Uq,t=>{t.element.setMap(this)}),this.interactions.addEventListener($q,t=>{t.element.setMap(null)}),this.overlays_.addEventListener(Uq,t=>{this.addOverlayInternal_(t.element)}),this.overlays_.addEventListener($q,t=>{const e=t.element.getId();void 0!==e&&delete this.overlayIdIndex_[e.toString()],t.element.setMap(null)}),this.controls.forEach(t=>{t.setMap(this)}),this.interactions.forEach(t=>{t.setMap(this)}),this.overlays_.forEach(this.addOverlayInternal_.bind(this))}addControl(t){this.getControls().push(t)}addInteraction(t){this.getInteractions().push(t)}addLayer(t){this.getLayerGroup().getLayers().push(t)}handleLayerAdd_(t){bQ(t.layer,this)}addOverlay(t){this.getOverlays().push(t)}addOverlayInternal_(t){const e=t.getId();void 0!==e&&(this.overlayIdIndex_[e.toString()]=t),t.setMap(this)}disposeInternal(){this.controls.clear(),this.interactions.clear(),this.overlays_.clear(),this.resizeObserver_?.disconnect(),this.setTarget(null),super.disposeInternal()}forEachFeatureAtPixel(t,e,n){if(!this.frameState_||!this.renderer_)return;const r=this.getCoordinateFromPixelInternal(t),i=void 0!==(n=void 0!==n?n:{}).hitTolerance?n.hitTolerance:0,s=void 0!==n.layerFilter?n.layerFilter:iV,o=!1!==n.checkWrapped;return this.renderer_.forEachFeatureAtCoordinate(r,this.frameState_,i,o,e,null,s,null)}getFeaturesAtPixel(t,e){const n=[];return this.forEachFeatureAtPixel(t,function(t){n.push(t)},e),n}getAllLayers(){const t=[];return function e(n){n.forEach(function(n){n instanceof UZ?e(n.getLayers()):t.push(n)})}(this.getLayers()),t}hasFeatureAtPixel(t,e){if(!this.frameState_||!this.renderer_)return!1;const n=this.getCoordinateFromPixelInternal(t),r=void 0!==(e=void 0!==e?e:{}).layerFilter?e.layerFilter:iV,i=void 0!==e.hitTolerance?e.hitTolerance:0,s=!1!==e.checkWrapped;return this.renderer_.hasFeatureAtCoordinate(n,this.frameState_,i,s,r,null)}getEventCoordinate(t){return this.getCoordinateFromPixel(this.getEventPixel(t))}getEventCoordinateInternal(t){return this.getCoordinateFromPixelInternal(this.getEventPixel(t))}getEventPixel(t){const e=this.viewport_.getBoundingClientRect(),n=this.getSize(),r=e.width/n[0],i=e.height/n[1],s="changedTouches"in t?t.changedTouches[0]:t;return[(s.clientX-e.left)/r,(s.clientY-e.top)/i]}getTarget(){return this.get(qV)}getTargetElement(){return this.targetElement_}getCoordinateFromPixel(t){return lG(this.getCoordinateFromPixelInternal(t),this.getView().getProjection())}getCoordinateFromPixelInternal(t){const e=this.frameState_;return e?vG(e.pixelToCoordinateTransform,t.slice()):null}getControls(){return this.controls}getOverlays(){return this.overlays_}getOverlayById(t){const e=this.overlayIdIndex_[t.toString()];return void 0!==e?e:null}getInteractions(){return this.interactions}getLayerGroup(){return this.get(UV)}setLayers(t){const e=this.getLayerGroup();if(t instanceof SV)return void e.setLayers(t);const n=e.getLayers();n.clear(),n.extend(t)}getLayers(){return this.getLayerGroup().getLayers()}getLoadingOrNotReady(){const t=this.getLayerGroup().getLayerStatesArray();for(let e=0,n=t.length;e=0;n--){const r=e[n];if(r.getMap()===this&&r.getActive()&&this.getTargetElement()&&(!r.handleEvent(t)||t.propagationStopped))break}}}handlePostRender(){const t=this.frameState_,e=this.tileQueue_;if(!e.isEmpty()){let n=this.maxTilesLoading_,r=n;if(t){const e=t.viewHints;if(e[0]||e[1]){const e=Date.now()-t.time>8;n=e?0:8,r=e?0:2}}e.getTilesLoading(){this.postRenderTimeoutHandle_=void 0,this.handlePostRender()},0))}setLayerGroup(t){const e=this.getLayerGroup();e&&this.handleLayerRemove_(new jZ("removelayer",e)),this.set(UV,t)}setSize(t){this.set($V,t)}setTarget(t){this.set(qV,t)}setView(t){if(!t||t instanceof _K)return void this.set(VV,t);this.set(VV,new _K);const e=this;t.then(function(t){e.setView(new _K(t))})}updateSize(){const t=this.getTargetElement();let e;if(t){let n,r;if($K(t))n=t.width,r=t.height;else{const e=getComputedStyle(t);n=t.offsetWidth-parseFloat(e.borderLeftWidth)-parseFloat(e.paddingLeft)-parseFloat(e.paddingRight)-parseFloat(e.borderRightWidth),r=t.offsetHeight-parseFloat(e.borderTopWidth)-parseFloat(e.paddingTop)-parseFloat(e.paddingBottom)-parseFloat(e.borderBottomWidth)}isNaN(n)||isNaN(r)||(e=[Math.max(0,n),Math.max(0,r)],!PY(e)&&(t.offsetWidth||t.offsetHeight||t.getClientRects().length)&&tH("No map visible because the map container's width or height are 0."))}const n=this.getSize();!e||n&&rV(e,n)||(this.setSize(e),this.updateViewportSize_(e))}updateViewportSize_(t){const e=this.getView();e&&e.setViewportSize(t)}};const _Q="element",xQ="map",CQ="offset",SQ="position",kQ="positioning";class EQ extends _V{constructor(t){super(),this.on,this.once,this.un,this.options=t,this.id=t.id,this.insertFirst=void 0===t.insertFirst||t.insertFirst,this.stopEvent=void 0===t.stopEvent||t.stopEvent,this.element=document.createElement("div"),this.element.className=void 0!==t.className?t.className:"ol-overlay-container ol-selectable",this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.autoPan=!0===t.autoPan?{}:t.autoPan||void 0,this.rendered={transform_:"",visible:!0},this.mapPostrenderListenerKey=null,this.addChangeListener(_Q,this.handleElementChanged),this.addChangeListener(xQ,this.handleMapChanged),this.addChangeListener(CQ,this.handleOffsetChanged),this.addChangeListener(SQ,this.handlePositionChanged),this.addChangeListener(kQ,this.handlePositioningChanged),void 0!==t.element&&this.setElement(t.element),this.setOffset(void 0!==t.offset?t.offset:[0,0]),this.setPositioning(t.positioning||"top-left"),void 0!==t.position&&this.setPosition(t.position)}getElement(){return this.get(_Q)}getId(){return this.id}getMap(){return this.get(xQ)||null}getOffset(){return this.get(CQ)}getPosition(){return this.get(SQ)}getPositioning(){return this.get(kQ)}handleElementChanged(){BK(this.element);const t=this.getElement();t&&this.element.appendChild(t)}handleMapChanged(){this.mapPostrenderListenerKey&&(this.element?.remove(),gV(this.mapPostrenderListenerKey),this.mapPostrenderListenerKey=null);const t=this.getMap();if(t){this.mapPostrenderListenerKey=pV(t,NV,this.render,this),this.updatePixelPosition();const e=this.stopEvent?t.getOverlayContainerStopEvent():t.getOverlayContainer();this.insertFirst?e.insertBefore(this.element,e.childNodes[0]||null):e.appendChild(this.element),this.performAutoPan()}}render(){this.updatePixelPosition()}handleOffsetChanged(){this.updatePixelPosition()}handlePositionChanged(){this.updatePixelPosition(),this.performAutoPan()}handlePositioningChanged(){this.updatePixelPosition()}setElement(t){this.set(_Q,t)}setMap(t){this.set(xQ,t)}setOffset(t){this.set(CQ,t)}setPosition(t){this.set(SQ,t)}performAutoPan(){this.autoPan&&this.panIntoView(this.autoPan)}panIntoView(t){const e=this.getMap();if(!e||!e.getTargetElement()||!this.get(SQ))return;const n=this.getRect(e.getTargetElement(),e.getSize()),r=this.getElement(),i=this.getRect(r,[DK(r),NK(r)]),s=void 0===(t=t||{}).margin?20:t.margin;if(!fW(n,i)){const r=i[0]-n[0],o=n[2]-i[2],a=i[1]-n[1],l=n[3]-i[3],c=[0,0];if(r<0?c[0]=r-s:o<0&&(c[0]=Math.abs(o)+s),a<0?c[1]=a-s:l<0&&(c[1]=Math.abs(l)+s),0!==c[0]||0!==c[1]){const n=e.getView().getCenterInternal(),r=e.getPixelFromCoordinateInternal(n);if(!r)return;const i=[r[0]+c[0],r[1]+c[1]],s=t.animation||{};e.getView().animateInternal({center:e.getCoordinateFromPixelInternal(i),duration:s.duration,easing:s.easing})}}}getRect(t,e){const n=t.getBoundingClientRect(),r=n.left+window.pageXOffset,i=n.top+window.pageYOffset;return[r,i,r+e[0],i+e[1]]}setPositioning(t){this.set(kQ,t)}setVisible(t){this.rendered.visible!==t&&(this.element.style.display=t?"":"none",this.rendered.visible=t)}updatePixelPosition(){const t=this.getMap(),e=this.getPosition();if(!t||!t.isRendered()||!e)return void this.setVisible(!1);const n=t.getPixelFromCoordinate(e),r=t.getSize();this.updateRenderedPosition(n,r)}updateRenderedPosition(t,e){const n=this.element.style,r=this.getOffset(),i=this.getPositioning();this.setVisible(!0);let s="0%",o="0%";"bottom-right"==i||"center-right"==i||"top-right"==i?s="-100%":"bottom-center"!=i&&"center-center"!=i&&"top-center"!=i||(s="-50%"),"bottom-left"==i||"bottom-center"==i||"bottom-right"==i?o="-100%":"center-left"!=i&&"center-center"!=i&&"center-right"!=i||(o="-50%");const a=`translate(${s}, ${o}) translate(${t[0]+r[0]}px, ${t[1]+r[1]}px)`;this.rendered.transform_!=a&&(this.rendered.transform_=a,n.transform=a)}getOptions(){return this.options}}class TQ extends _V{constructor(t){if(super(),this.on,this.once,this.un,this.id_=void 0,this.geometryName_="geometry",this.style_=null,this.styleFunction_=void 0,this.geometryChangeKey_=null,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),t)if("function"==typeof t.getSimplifiedGeometry){const e=t;this.setGeometry(e)}else{const e=t;this.setProperties(e)}}clone(){const t=new TQ(this.hasProperties()?this.getProperties():null);t.setGeometryName(this.getGeometryName());const e=this.getGeometry();e&&t.setGeometry(e.clone());const n=this.getStyle();return n&&t.setStyle(n),t}getGeometry(){return this.get(this.geometryName_)}getId(){return this.id_}getGeometryName(){return this.geometryName_}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}handleGeometryChange_(){this.changed()}handleGeometryChanged_(){this.geometryChangeKey_&&(gV(this.geometryChangeKey_),this.geometryChangeKey_=null);const t=this.getGeometry();t&&(this.geometryChangeKey_=pV(t,Vq,this.handleGeometryChange_,this)),this.changed()}setGeometry(t){this.set(this.geometryName_,t)}setStyle(t){this.style_=t,this.styleFunction_=t?function(t){if("function"==typeof t)return t;let e;return Array.isArray(t)?e=t:(WV("function"==typeof t.getZIndex,"Expected an `ol/style/Style` or an array of `ol/style/Style.js`"),e=[t]),function(){return e}}(t):void 0,this.changed()}setId(t){this.id_=t,this.changed()}setGeometryName(t){this.removeChangeListener(this.geometryName_,this.handleGeometryChanged_),this.geometryName_=t,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),this.handleGeometryChanged_()}}function RQ(t,e,n,r,i,s,o){let a,l;const c=(n-e)/r;if(1===c)a=e;else if(2===c)a=e,l=i;else if(0!==c){let s=t[e],o=t[e+1],c=0;const u=[0];for(let i=e+r;i>1),i=+n(t[r],e),i<0?s=r+1:(o=r,a=!i);return a?s:~s}(u,h);d<0?(l=(h-u[-d-2])/(u[-d-1]-u[-d-2]),a=e+(-d-2)*r):a=e+d*r}o=o>1?o:2,s=s||new Array(o);for(let u=0;u>1;ia&&(this.instructions.push([4,a,c,t,n,$G,i]),this.hitDetectionInstructions.push([4,a,c,t,r||n,$G,i]));break;case"Point":l=t.getFlatCoordinates(),this.coordinates.push(l[0],l[1]),c=this.coordinates.length,this.instructions.push([4,a,c,t,n,void 0,i]),this.hitDetectionInstructions.push([4,a,c,t,r||n,void 0,i])}this.endGeometry(e)}beginGeometry(t,e,n){this.beginGeometryInstruction1_=[0,e,0,t,n],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[0,e,0,t,n],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const t=this.hitDetectionInstructions;let e;t.reverse();const n=t.length;let r,i,s=-1;for(e=0;ethis.maxLineWidth&&(this.maxLineWidth=e.lineWidth,this.bufferedMaxExtent_=null)}else e.strokeStyle=void 0,e.lineCap=void 0,e.lineDash=null,e.lineDashOffset=void 0,e.lineJoin=void 0,e.lineWidth=void 0,e.miterLimit=void 0;return e}setFillStrokeStyle(t,e){const n=this.state;this.fillStyleToState(t,n),this.strokeStyleToState(e,n)}createFill(t){const e=t.fillStyle,n=[10,e];return"string"!=typeof e&&n.push(t.fillPatternScale),n}applyStroke(t){this.instructions.push(this.createStroke(t))}createStroke(t){return[DQ,t.strokeStyle,t.lineWidth*this.pixelRatio,t.lineCap,t.lineJoin,t.miterLimit,t.lineDash?this.applyPixelRatio(t.lineDash):null,t.lineDashOffset*this.pixelRatio]}updateFillStyle(t,e){const n=t.fillStyle;"string"==typeof n&&t.currentFillStyle==n||(this.instructions.push(e.call(this,t)),t.currentFillStyle=n)}updateStrokeStyle(t,e){const n=t.strokeStyle,r=t.lineCap,i=t.lineDash,s=t.lineDashOffset,o=t.lineJoin,a=t.lineWidth,l=t.miterLimit;(t.currentStrokeStyle!=n||t.currentLineCap!=r||i!=t.currentLineDash&&!rV(t.currentLineDash,i)||t.currentLineDashOffset!=s||t.currentLineJoin!=o||t.currentLineWidth!=a||t.currentMiterLimit!=l)&&(e.call(this,t),t.currentStrokeStyle=n,t.currentLineCap=r,t.currentLineDash=i,t.currentLineDashOffset=s,t.currentLineJoin=o,t.currentLineWidth=a,t.currentMiterLimit=l)}endGeometry(t){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const e=[7,t];this.instructions.push(e),this.hitDetectionInstructions.push(e)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=hW(this.maxExtent),this.maxLineWidth>0)){const t=this.resolution*(this.maxLineWidth+1)/2;uW(this.bufferedMaxExtent_,t,this.bufferedMaxExtent_)}return this.bufferedMaxExtent_}}class qQ extends $Q{constructor(t,e,n,r){super(t,e,n,r)}drawFlatCoordinatess_(t,e,n,r){const i=this.state,s=void 0!==i.fillStyle,o=void 0!==i.strokeStyle,a=n.length;this.instructions.push(BQ),this.hitDetectionInstructions.push(BQ);for(let l=0;l=t){const e=(t-a+h)/h,d=nW(n,c,e),p=nW(r,u,e);l.push(d,p),s.push(l),l=[d,p],a==t&&(o+=i),a=0}else if(a0&&s.push(l),s}function WQ(t,e,n,r,i){let s,o,a,l,c,u,h,d,p,f,g=n,m=n,y=0,v=0,b=n;for(o=n;ot&&(v>y&&(y=v,g=b,m=o),v=0,b=o-i)),a=l,h=p,d=f),c=n,u=r}return v+=l,v>y?[b,o]:[g,m]}const HQ={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1},GQ={Circle:qQ,Default:$Q,Image:class extends $Q{constructor(t,e,n,r){super(t,e,n,r),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(t,e,n){if(!this.image_||this.maxExtent&&!pW(this.maxExtent,t.getFlatCoordinates()))return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=t.getStride(),s=this.coordinates.length,o=this.appendFlatPointCoordinates(r,i);this.instructions.push([6,s,o,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([6,s,o,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(e)}drawMultiPoint(t,e,n){if(!this.image_)return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=[];for(let a=0,l=r.length;a{const r=o[2*(t+n)]===c[n*u]&&o[2*(t+n)+1]===c[n*u+1];return r||--t,r})}this.saveTextStates_();const h=s.backgroundFill?this.createFill(this.fillStyleToState(s.backgroundFill)):null,d=s.backgroundStroke?this.createStroke(this.strokeStyleToState(s.backgroundStroke)):null;this.beginGeometry(t,e,n);let p=s.padding;if(p!=bJ&&(s.scale[0]<0||s.scale[1]<0)){let t=s.padding[0],e=s.padding[1],n=s.padding[2],r=s.padding[3];s.scale[0]<0&&(e=-e,r=-r),s.scale[1]<0&&(t=-t,n=-n),p=[t,e,n,r]}const f=this.pixelRatio;this.instructions.push([6,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,this.declutterMode_,this.declutterImageWithText_,p==bJ?bJ:p.map(function(t){return t*f}),h,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]);const g=1/f,m=h?h.slice(0):null;m&&(m[1]=dJ),this.hitDetectionInstructions.push([6,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[g,g],NaN,this.declutterMode_,this.declutterImageWithText_,p,m,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?dJ:this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]),this.endGeometry(e)}else{if(!jW(this.maxExtent,t.getExtent()))return;let r;if(c=t.getFlatCoordinates(),"LineString"==l)r=[c.length];else if("MultiLineString"==l)r=t.getEnds();else if("Polygon"==l)r=t.getEnds().slice(0,1);else if("MultiPolygon"==l){const e=t.getEndss();r=[];for(let t=0,n=e.length;tt[2]}else R=_>E;const M=Math.PI,L=[],I=C+r===e;let P;if(y=0,v=S,p=t[e=C],f=t[e+1],I){b(),P=Math.atan2(f-m,p-g),R&&(P+=P>0?-M:M);const t=(E+_)/2,e=(T+x)/2;return L[0]=[t,e,(k-s)/2,P,i],L}for(let A=0,O=(i=i.replace(/\n/g," ")).length;A0?-M:M),void 0!==P){let e=t-P;if(e+=e>M?-2*M:e<-M?2*M:0,Math.abs(e)>o)return null}P=t;const h=A;let d=0;for(;A{if("function"==typeof FK()[e])return this.push_(e),this.pushMethodArgs_},set:(t,e,n)=>(this.push_(e,n),!0)})}push_(...t){const e=this.instructions_,n=this.zIndex+this.offset_;e[n]||(e[n]=[]),e[n].push(...t)}pushMethodArgs_=(...t)=>(this.push_(t),this);pushFunction(t){this.push_(t)}getContext(){return this.context_}draw(t){this.instructions_.forEach(e=>{for(let n=0,r=e.length;n0&&t.push("\n",""),t.push(e,""),t}function o0(t,e,n){return n%2==0&&(t+=e),t}class a0{constructor(t,e,n,r,i){this.overlaps=n,this.pixelRatio=e,this.resolution=t,this.alignAndScaleFill_,this.instructions=r.instructions,this.coordinates=r.coordinates,this.coordinateCache_={},this.renderedTransform_=[1,0,0,1,0,0],this.hitDetectionInstructions=r.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=r.fillStates||{},this.strokeStates=r.strokeStates||{},this.textStates=r.textStates||{},this.widths_={},this.labels_={},this.zIndexContext_=i?new YQ:null}getZIndexContext(){return this.zIndexContext_}createLabel(t,e,n,r){const i=t+e+n+r;if(this.labels_[i])return this.labels_[i];const s=r?this.strokeStates[r]:null,o=n?this.fillStates[n]:null,a=this.textStates[e],l=this.pixelRatio,c=[a.scale[0]*l,a.scale[1]*l],u=a.justify?HQ[a.justify]:i0(Array.isArray(t)?t[0]:t,a.textAlign||yJ),h=r&&s.lineWidth?s.lineWidth:0,d=Array.isArray(t)?t:String(t).split("\n").reduce(s0,[]),{width:p,height:f,widths:g,heights:m,lineWidths:y}=function(t,e){const n=[],r=[],i=[];let s=0,o=0,a=0,l=0;for(let c=0,u=e.length;c<=u;c+=2){const h=e[c];if("\n"===h||c===u){s=Math.max(s,o),i.push(o),o=0,a+=l,l=0;continue}const d=e[c+1]||t.font,p=MJ(d,h);n.push(p),o+=p;const f=TJ(d);r.push(f),l=Math.max(l,f)}return{width:s,height:a,widths:n,heights:r,lineWidths:i}}(a,d),v=p+h,b=[],w=(v+2)*c[0],_=(f+h)*c[1],x={width:w<0?Math.floor(w):Math.ceil(w),height:_<0?Math.floor(_):Math.ceil(_),contextInstructions:b};1==c[0]&&1==c[1]||b.push("scale",c),r&&(b.push("strokeStyle",s.strokeStyle),b.push("lineWidth",h),b.push("lineCap",s.lineCap),b.push("lineJoin",s.lineJoin),b.push("miterLimit",s.miterLimit),b.push("setLineDash",[s.lineDash]),b.push("lineDashOffset",s.lineDashOffset)),n&&b.push("fillStyle",o.fillStyle),b.push("textBaseline","middle"),b.push("textAlign","center");const C=.5-u;let S=u*v+C*h;const k=[],E=[];let T,R=0,M=0,L=0,I=0;for(let P=0,A=d.length;Pt?t-l:i,b=s+c>e?e-c:s,w=p[3]+v*h[0]+p[1],_=p[0]+b*h[1]+p[2],x=m-p[3],C=y-p[0];let S;return(f||0!==u)&&(JQ[0]=x,e0[0]=x,JQ[1]=C,QQ[1]=C,QQ[0]=x+w,t0[0]=QQ[0],t0[1]=C+_,e0[1]=t0[1]),0!==u?(S=wG([1,0,0,1,0,0],n,r,1,1,u,-n,-r),vG(S,JQ),vG(S,QQ),vG(S,t0),vG(S,e0),yW(Math.min(JQ[0],QQ[0],t0[0],e0[0]),Math.min(JQ[1],QQ[1],t0[1],e0[1]),Math.max(JQ[0],QQ[0],t0[0],e0[0]),Math.max(JQ[1],QQ[1],t0[1],e0[1]),XQ)):yW(Math.min(x,x+w),Math.min(C,C+_),Math.max(x,x+w),Math.max(C,C+_),XQ),d&&(m=Math.round(m),y=Math.round(y)),{drawImageX:m,drawImageY:y,drawImageW:v,drawImageH:b,originX:l,originY:c,declutterBox:{minX:XQ[0],minY:XQ[1],maxX:XQ[2],maxY:XQ[3],value:g},canvasTransform:S,scale:h}}replayImageOrLabel_(t,e,n,r,i,s,o){const a=!(!s&&!o),l=r.declutterBox,c=o?o[2]*r.scale[0]/2:0;return l.minX-c<=e[0]&&l.maxX+c>=0&&l.minY-c<=e[1]&&l.maxY+c>=0&&(a&&this.replayTextBackground_(t,JQ,QQ,t0,e0,s,o),function(t,e,n,r,i,s,o,a,l,c,u){t.save(),1!==n&&(void 0===t.globalAlpha?t.globalAlpha=t=>t.globalAlpha*=n:t.globalAlpha*=n),e&&t.transform.apply(t,e),r.contextInstructions?(t.translate(l,c),t.scale(u[0],u[1]),function(t,e){const n=t.contextInstructions;for(let r=0,i=n.length;rO&&(this.fill_(t),R=0),M>O&&(t.stroke(),M=0),R||M||(t.beginPath(),v=NaN,b=NaN),++d;break;case 2:T=n[1];const r=c[T],u=c[T+1],h=c[T+2]-r,p=c[T+3]-u,j=Math.sqrt(h*h+p*p);t.moveTo(r+j,u),t.arc(r,u,j,0,2*Math.PI,!0),++d;break;case 3:t.closePath(),++d;break;case 4:T=n[1],f=n[2];const B=n[3],U=n[4],$=n[5];A.geometry=B,A.feature=F,d in L||(L[d]=[]);const q=L[d];$?$(c,T,f,2,q):(q[0]=c[T],q[1]=c[T+1],q.length=2),l&&(l.zIndex=n[6]),U(q,A),++d;break;case 6:T=n[1],f=n[2],x=n[3],g=n[4],m=n[5];let V=n[6];const W=n[7],H=n[8],G=n[9],K=n[10];let Z=n[11];const Y=n[12];let X=n[13];y=n[14]||"declutter";const J=n[15];if(!x&&n.length>=20){C=n[19],S=n[20],k=n[21],E=n[22];const t=this.drawLabelWithPointPlacement_(C,S,k,E);x=t.label,n[3]=x;const e=n[23];g=(t.anchorX-e)*this.pixelRatio,n[4]=g;const r=n[24];m=(t.anchorY-r)*this.pixelRatio,n[5]=m,V=x.height,n[6]=V,X=x.width,n[13]=X}let Q,tt,et,nt;n.length>25&&(Q=n[25]),n.length>17?(tt=n[16],et=n[17],nt=n[18]):(tt=bJ,et=null,nt=null),K&&P?Z+=I:K||P||(Z-=I);let rt=0;for(;T!c0.includes(t));class h0{constructor(t,e,n,r,i,s,o){this.maxExtent_=t,this.overlaps_=r,this.pixelRatio_=n,this.resolution_=e,this.renderBuffer_=s,this.executorsByZIndex_={},this.hitDetectionContext_=null,this.hitDetectionTransform_=[1,0,0,1,0,0],this.renderedContext_=null,this.deferredZIndexContexts_={},this.createExecutors_(i,o)}clip(t,e){const n=this.getClipCoords(e);t.beginPath(),t.moveTo(n[0],n[1]),t.lineTo(n[2],n[3]),t.lineTo(n[4],n[5]),t.lineTo(n[6],n[7]),t.clip()}createExecutors_(t,e){for(const n in t){let r=this.executorsByZIndex_[n];void 0===r&&(r={},this.executorsByZIndex_[n]=r);const i=t[n];for(const t in i){const n=i[t];r[t]=new a0(this.resolution_,this.pixelRatio_,this.overlaps_,n,e)}}}hasExecutors(t){for(const e in this.executorsByZIndex_){const n=this.executorsByZIndex_[e];for(let e=0,r=t.length;en)break;let a=r[o];a||(a=[],r[o]=a),a.push(4*((t+s)*e+(t+i))+3),s>0&&a.push(4*((t-s)*e+(t+i))+3),i>0&&(a.push(4*((t+s)*e+(t-i))+3),s>0&&a.push(4*((t-s)*e+(t-i))+3))}const i=[];for(let s=0,o=r.length;s0){if(!s||"none"===n||"Image"!==d&&"Text"!==d||s.includes(t)){const n=(h[l]-3)/4,s=r-n%o,a=r-(n/o|0),c=i(t,e,s*s+a*a);if(c)return c}c.clearRect(0,0,o,o);break}}const f=Object.keys(this.executorsByZIndex_).map(Number);let g,m,y,v,b;for(f.sort(Jq),g=f.length-1;g>=0;--g){const t=f[g].toString();for(y=this.executorsByZIndex_[t],m=l0.length-1;m>=0;--m)if(d=l0[m],v=y[d],void 0!==v&&(b=v.executeHitDetection(c,a,n,p,u),b))return b}}getClipCoords(t){const e=this.maxExtent_;if(!e)return null;const n=e[0],r=e[1],i=e[2],s=e[3],o=[n,r,n,s,i,s,i,r];return SG(o,0,8,2,t,o),o}isEmpty(){return uV(this.executorsByZIndex_)}execute(t,e,n,r,i,s,o){const a=Object.keys(this.executorsByZIndex_).map(Number);a.sort(o?Qq:Jq),s=s||l0;const l=l0.length;for(let c=0,u=a.length;cp.execute(t,e,n,r,i,o)):p.execute(h,e,n,r,i,o),d&&h.restore(),s){s.offset();const t=a[c]*l+l0.indexOf(u);this.deferredZIndexContexts_[t]||(this.deferredZIndexContexts_[t]=[]),this.deferredZIndexContexts_[t].push(s)}}}}this.renderedContext_=t}getDeferredZIndexContexts(){return this.deferredZIndexContexts_}getRenderedContext(){return this.renderedContext_}renderDeferred(){const t=this.deferredZIndexContexts_,e=Object.keys(t).map(Number).sort(Jq);for(let n=0,r=e.length;n{t.draw(this.renderedContext_),t.clear()}),t[e[n]].length=0}}const d0={};class p0 extends zQ{constructor(t,e,n,r,i,s,o){super(),this.context_=t,this.pixelRatio_=e,this.extent_=n,this.transform_=r,this.transformRotation_=r?rW(Math.atan2(r[1],r[0]),10):0,this.viewRotation_=i,this.squaredTolerance_=s,this.userTransform_=o,this.contextFillState_=null,this.contextStrokeState_=null,this.contextTextState_=null,this.fillState_=null,this.strokeState_=null,this.image_=null,this.imageAnchorX_=0,this.imageAnchorY_=0,this.imageHeight_=0,this.imageOpacity_=0,this.imageOriginX_=0,this.imageOriginY_=0,this.imageRotateWithView_=!1,this.imageRotation_=0,this.imageScale_=[0,0],this.imageWidth_=0,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=!1,this.textRotation_=0,this.textScale_=[0,0],this.textFillState_=null,this.textStrokeState_=null,this.textState_=null,this.pixelCoordinates_=[],this.tmpLocalTransform_=[1,0,0,1,0,0]}drawImages_(t,e,n,r){if(!this.image_)return;const i=SG(t,e,n,r,this.transform_,this.pixelCoordinates_),s=this.context_,o=this.tmpLocalTransform_,a=s.globalAlpha;1!=this.imageOpacity_&&(s.globalAlpha=a*this.imageOpacity_);let l=this.imageRotation_;0===this.transformRotation_&&(l-=this.viewRotation_),this.imageRotateWithView_&&(l+=this.viewRotation_);for(let c=0,u=i.length;ct*this.pixelRatio_),lineDashOffset:(i||0)*this.pixelRatio_,lineJoin:void 0!==s?s:gJ,lineWidth:(void 0!==o?o:1)*this.pixelRatio_,miterLimit:void 0!==a?a:10,strokeStyle:uJ(t||mJ)}}else this.strokeState_=null}setImageStyle(t){let e;if(!t||!(e=t.getSize()))return void(this.image_=null);const n=t.getPixelRatio(this.pixelRatio_),r=t.getAnchor(),i=t.getOrigin();this.image_=t.getImage(this.pixelRatio_),this.imageAnchorX_=r[0]*n,this.imageAnchorY_=r[1]*n,this.imageHeight_=e[1]*n,this.imageOpacity_=t.getOpacity(),this.imageOriginX_=i[0],this.imageOriginY_=i[1],this.imageRotateWithView_=t.getRotateWithView(),this.imageRotation_=t.getRotation();const s=t.getScaleArray();this.imageScale_=[s[0]*this.pixelRatio_/n,s[1]*this.pixelRatio_/n],this.imageWidth_=e[0]*n}setTextStyle(t){if(t){const e=t.getFill();if(e){const t=e.getColor();this.textFillState_={fillStyle:uJ(t||dJ)}}else this.textFillState_=null;const n=t.getStroke();if(n){const t=n.getColor(),e=n.getLineCap(),r=n.getLineDash(),i=n.getLineDashOffset(),s=n.getLineJoin(),o=n.getWidth(),a=n.getMiterLimit();this.textStrokeState_={lineCap:void 0!==e?e:pJ,lineDash:r||fJ,lineDashOffset:i||0,lineJoin:void 0!==s?s:gJ,lineWidth:void 0!==o?o:1,miterLimit:void 0!==a?a:10,strokeStyle:uJ(t||mJ)}}else this.textStrokeState_=null;const r=t.getFont(),i=t.getOffsetX(),s=t.getOffsetY(),o=t.getRotateWithView(),a=t.getRotation(),l=t.getScaleArray(),c=t.getText(),u=t.getTextAlign(),h=t.getTextBaseline();this.textState_={font:void 0!==r?r:hJ,textAlign:void 0!==u?u:yJ,textBaseline:void 0!==h?h:vJ},this.text_=void 0!==c?Array.isArray(c)?c.reduce((t,e,n)=>t+(n%2?" ":e),""):c:"",this.textOffsetX_=void 0!==i?this.pixelRatio_*i:0,this.textOffsetY_=void 0!==s?this.pixelRatio_*s:0,this.textRotateWithView_=void 0!==o&&o,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*l[0],this.pixelRatio_*l[1]]}else this.text_=""}}const f0=.5;function g0(t,e,n,r,i,s,o,a,l){const c=i,u=AK(t[0]*f0,t[1]*f0);u.imageSmoothingEnabled=!1;const h=u.canvas,d=new p0(u,f0,i,null,o,a,l?rG(null,l):null),p=n.length,f=Math.floor(16777215/p),g={};for(let y=1;y<=p;++y){const t=n[y-1],e=t.getStyleFunction()||r;if(!e)continue;let i=e(t,s);if(!i)continue;Array.isArray(i)||(i=[i]);const o=(y*f).toString(16).padStart(7,"#00000");for(let n=0,r=i.length;n0;return h&&Promise.all(l).then(()=>i(null)),function(t,e,n,r,i,s,o){const a=n.getGeometryFunction()(e);if(!a)return;const l=a.simplifyTransformed(r,i);n.getRenderer()?x0(t,l,n,e,o):(0,y0[l.getType()])(t,l,n,e,o,s)}(t,e,n,r,s,o,a),h}function x0(t,e,n,r,i){if("GeometryCollection"==e.getType()){const s=e.getGeometries();for(let e=0,o=s.length;ethis.maxStaleKeys&&(this.staleKeys_.length=this.maxStaleKeys)}getFeatures(t){return yV()}getData(t){return null}prepareFrame(t){return yV()}renderFrame(t,e){return yV()}forEachFeatureAtCoordinate(t,e,n,r,i){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(t){const e=t.target;2!==e.getState()&&3!==e.getState()||this.renderIfReadyAndVisible()}loadImage(t){let e=t.getState();return 2!=e&&3!=e&&t.addEventListener(Vq,this.boundHandleImageChange_),0==e&&(t.load(),e=t.getState()),2==e}renderIfReadyAndVisible(){const t=this.getLayer();t&&t.getVisible()&&"ready"===t.getSourceState()&&t.changed()}renderDeferred(t){}disposeInternal(){delete this.layer_,super.disposeInternal()}}const S0=[];let k0=null;class E0 extends C0{constructor(t){super(t),this.container=null,this.renderedResolution,this.tempTransform=[1,0,0,1,0,0],this.pixelTransform=[1,0,0,1,0,0],this.inversePixelTransform=[1,0,0,1,0,0],this.context=null,this.deferredContext_=null,this.containerReused=!1,this.frameState=null}getImageData(t,e,n){let r;k0||(k0=AK(1,1,void 0,{willReadFrequently:!0})),k0.clearRect(0,0,1,1);try{k0.drawImage(t,e,n,1,1,0,0,1,1),r=k0.getImageData(0,0,1,1).data}catch{return k0=null,null}return r}getBackground(t){let e=this.getLayer().getBackground();return"function"==typeof e&&(e=e(t.viewState.resolution)),e||void 0}useContainer(t,e,n){const r=this.getLayer().getClassName();let i,s;if(t&&t.className===r&&(!n||t&&t.style.backgroundColor&&rV(LY(t.style.backgroundColor),LY(n)))){const e=t.firstElementChild;$K(e)&&(s=e.getContext("2d"))}if(s&&function(t,e){const n=CG(t),r=CG(e);for(let i=0;i<6;++i)if(0!==Math.round((n[i]-r[i])*xG[i]))return!1;return!0}(s.canvas.style.transform,e)?(this.container=t,this.context=s,this.containerReused=!0):this.containerReused?(this.container=null,this.context=null,this.containerReused=!1):this.container&&(this.container.style.backgroundColor=null),!this.container){i=PV?UK():document.createElement("div"),i.className=r;let t=i.style;t.position="absolute",t.width="100%",t.height="100%",s=AK();const e=s.canvas;i.appendChild(e),t=e.style,t.position="absolute",t.left="0",t.transformOrigin="top left",this.container=i,this.context=s}this.containerReused||!n||this.container.style.backgroundColor||(this.container.style.backgroundColor=n)}clipUnrotated(t,e,n){const r=zW(n),i=DW(n),s=MW(n),o=RW(n);vG(e.coordinateToPixelTransform,r),vG(e.coordinateToPixelTransform,i),vG(e.coordinateToPixelTransform,s),vG(e.coordinateToPixelTransform,o);const a=this.inversePixelTransform;vG(a,r),vG(a,i),vG(a,s),vG(a,o),t.save(),t.beginPath(),t.moveTo(Math.round(r[0]),Math.round(r[1])),t.lineTo(Math.round(i[0]),Math.round(i[1])),t.lineTo(Math.round(s[0]),Math.round(s[1])),t.lineTo(Math.round(o[0]),Math.round(o[1])),t.clip()}prepareContainer(t,e){const n=t.extent,r=t.viewState.resolution,i=t.viewState.rotation,s=t.pixelRatio,o=Math.round(NW(n)/r*s),a=Math.round(OW(n)/r*s);wG(this.pixelTransform,t.size[0]/2,t.size[1]/2,1/s,1/s,i,-o/2,-a/2),_G(this.inversePixelTransform,this.pixelTransform);const l="matrix("+this.pixelTransform.join(", ")+")";if(this.useContainer(e,l,this.getBackground(t)),!this.containerReused){const t=this.context.canvas;t.width!=o||t.height!=a?(t.width=o,t.height=a):this.context.clearRect(0,0,o,a),l!==t.style.transform&&(t.style.transform=l)}}dispatchRenderEvent_(t,e,n){const r=this.getLayer();if(r.hasListener(t)){const i=new fQ(t,this.inversePixelTransform,n,e);r.dispatchEvent(i)}}preRender(t,e){this.frameState=e,e.declutter||this.dispatchRenderEvent_($Z,t,e)}postRender(t,e){e.declutter||this.dispatchRenderEvent_(qZ,t,e)}renderDeferredInternal(t){}getRenderContext(t){return t.declutter&&!this.deferredContext_&&(this.deferredContext_=new YQ),t.declutter?this.deferredContext_.getContext():this.context}renderDeferred(t){t.declutter&&(this.dispatchRenderEvent_($Z,this.context,t),t.declutter&&this.deferredContext_&&(this.deferredContext_.draw(this.context),this.deferredContext_.clear()),this.renderDeferredInternal(t),this.dispatchRenderEvent_(qZ,this.context,t))}getRenderTransform(t,e,n,r,i,s,o){const a=i/2,l=s/2,c=r/e,u=-c,h=-t[0]+o,d=-t[1];return wG(this.tempTransform,a,l,c,u,-n,h,d)}disposeInternal(){delete this.frameState,super.disposeInternal()}}class T0 extends E0{constructor(t){super(t),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.animatingOrInteracting_,this.hitDetectionImageData_=null,this.clipped_=!1,this.renderedFeatures_=null,this.renderedRevision_=-1,this.renderedResolution_=NaN,this.renderedExtent_=[1/0,1/0,-1/0,-1/0],this.wrappedRenderedExtent_=[1/0,1/0,-1/0,-1/0],this.renderedRotation_,this.renderedCenter_=null,this.renderedProjection_=null,this.renderedPixelRatio_=1,this.renderedRenderOrder_=null,this.renderedFrameDeclutter_,this.replayGroup_=null,this.replayGroupChanged=!0,this.clipping=!0,this.targetContext_=null,this.opacity_=1}renderWorlds(t,e,n){const r=e.extent,i=e.viewState,s=i.center,o=i.resolution,a=i.projection,l=i.rotation,c=a.getExtent(),u=this.getLayer().getSource(),h=this.getLayer().getDeclutter(),d=e.pixelRatio,p=e.viewHints,f=!(p[0]||p[1]),g=this.context,m=Math.round(NW(r)/o*d),y=Math.round(OW(r)/o*d),v=u.getWrapX()&&a.canWrapX(),b=v?NW(c):null,w=v?Math.ceil((r[2]-c[2])/b)+1:1;let _=v?Math.floor((r[0]-c[0])/b):0;do{let r=this.getRenderTransform(s,o,0,d,m,y,_*b);e.declutter&&(r=r.slice(0)),t.execute(g,[g.canvas.width,g.canvas.height],r,l,f,void 0===n?l0:n?c0:u0,n?h&&e.declutter[h]:void 0)}while(++_{if(this.frameState&&!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const t=this.frameState.size.slice(),e=this.renderedCenter_,n=this.renderedResolution_,r=this.renderedRotation_,i=this.renderedProjection_,s=this.wrappedRenderedExtent_,o=this.getLayer(),a=[],l=t[0]*f0,c=t[1]*f0;a.push(this.getRenderTransform(e,n,r,f0,l,c,0).slice());const u=o.getSource(),h=i.getExtent();if(u.getWrapX()&&i.canWrapX()&&!fW(h,s)){let t=s[0];const i=NW(h);let o,u=0;for(;th[2];)++u,o=i*u,a.push(this.getRenderTransform(e,n,r,f0,l,c,o).slice()),t-=i}this.hitDetectionImageData_=g0(t,a,this.renderedFeatures_,o.getStyleFunction(),s,n,r,b0(n,this.renderedPixelRatio_),null)}e(m0(t,this.renderedFeatures_,this.hitDetectionImageData_))})}forEachFeatureAtCoordinate(t,e,n,r,i){if(!this.replayGroup_)return;const s=e.viewState.resolution,o=e.viewState.rotation,a=this.getLayer(),l={},c=this.getLayer().getDeclutter();return this.replayGroup_.forEachFeatureAtCoordinate(t,s,o,n,function(t,e,n){const s=bV(t),o=l[s];if(o){if(!0!==o&&nt.value):null)}handleFontsChanged(){const t=this.getLayer();t.getVisible()&&this.replayGroup_&&t.changed()}handleStyleImageChange_(t){this.renderIfReadyAndVisible()}prepareFrame(t){const e=this.getLayer(),n=e.getSource();if(!n)return!1;const r=t.viewHints[0],i=t.viewHints[1],s=e.getUpdateWhileAnimating(),o=e.getUpdateWhileInteracting();if(this.ready&&!s&&r||!o&&i)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=t.extent,l=t.viewState,c=l.projection,u=l.resolution,h=t.pixelRatio,d=e.getRevision(),p=e.getRenderBuffer();let f=e.getRenderOrder();void 0===f&&(f=v0);const g=l.center.slice(),m=uW(a,p*u),y=m.slice(),v=[m.slice()],b=c.getExtent();if(n.getWrapX()&&c.canWrapX()&&!fW(b,t.extent)){const t=NW(b),e=Math.max(NW(m)/2,t);m[0]=b[0]-e,m[2]=b[2]+e,HW(g,c);const n=$W(v[0],c);n[0]b[0]&&n[2]>b[2]&&v.push([n[0]-t,n[1],n[2]-t,n[3]])}if(this.ready&&this.renderedResolution_==u&&this.renderedRevision_==d&&this.renderedRenderOrder_==f&&this.renderedFrameDeclutter_===!!t.declutter&&fW(this.wrappedRenderedExtent_,m))return rV(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=g,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const w=new KQ(w0(u,h),m,u,h);for(let R=0,M=v.length;R{let r;const i=t.getStyleFunction()||e.getStyleFunction();if(i&&(r=i(t,u)),r){const e=this.renderFeature(t,_,r,w,void 0,this.getLayer().getDeclutter(),n);x=x&&!e}},S=m,k=n.getFeaturesInExtent(S);f&&k.sort(f);for(let R=0,M=k.length;R=200&&a.status<300){const t=e.getType();try{let r;"text"==t||"json"==t?r=a.responseText:"xml"==t?r=a.responseXML||a.responseText:"arraybuffer"==t&&(r=a.response),r?s(e.readFeatures(r,{extent:n,featureProjection:i}),e.readProjection(r)):o()}catch{o()}}else o()},a.onerror=o,a.send()}function L0(t,e){return function(n,r,i,s,o){M0(t,e,n,r,i,t=>{this.addFeatures(t),void 0!==s&&s(t)},()=>{this.changed(),void 0!==o&&o()})}}function I0(){return[[-1/0,-1/0,1/0,1/0]]}function P0(t){return[t]}class A0 extends RG{constructor(t){super(),this.geometries_=t,this.changeEventsKeys_=[],this.listenGeometriesChange_()}unlistenGeometriesChange_(){this.changeEventsKeys_.forEach(gV),this.changeEventsKeys_.length=0}listenGeometriesChange_(){const t=this.geometries_;for(let e=0,n=t.length;et.clone())}const F0=[1,0,0,1,0,0];class z0{constructor(t,e,n,r,i,s){this.styleFunction,this.extent_,this.id_=s,this.type_=t,this.flatCoordinates_=e,this.flatInteriorPoints_=null,this.flatMidpoints_=null,this.ends_=n||null,this.properties_=i,this.squaredTolerance_,this.stride_=r,this.simplifiedGeometry_}get(t){return this.properties_[t]}getExtent(){return this.extent_||(this.extent_="Point"===this.type_?bW(this.flatCoordinates_):wW(this.flatCoordinates_,0,this.flatCoordinates_.length,2)),this.extent_}getFlatInteriorPoint(){if(!this.flatInteriorPoints_){const t=LW(this.getExtent());this.flatInteriorPoints_=eK(this.flatCoordinates_,0,this.ends_,2,t,0)}return this.flatInteriorPoints_}getFlatInteriorPoints(){if(!this.flatInteriorPoints_){const t=pK(this.flatCoordinates_,this.ends_),e=OQ(this.flatCoordinates_,0,t,2);this.flatInteriorPoints_=nK(this.flatCoordinates_,0,t,2,e)}return this.flatInteriorPoints_}getFlatMidpoint(){return this.flatMidpoints_||(this.flatMidpoints_=RQ(this.flatCoordinates_,0,this.flatCoordinates_.length,2,.5)),this.flatMidpoints_}getFlatMidpoints(){if(!this.flatMidpoints_){this.flatMidpoints_=[];const t=this.flatCoordinates_;let e=0;const n=this.ends_;for(let r=0,i=n.length;r{if(t===this.squaredTolerance_)return this.simplifiedGeometry_;this.simplifiedGeometry_=this.clone(),e&&this.simplifiedGeometry_.applyTransform(e);const n=this.simplifiedGeometry_.getFlatCoordinates();let r;switch(this.type_){case"LineString":n.length=WG(n,0,this.simplifiedGeometry_.flatCoordinates_.length,this.simplifiedGeometry_.stride_,t,n,0),r=[n.length];break;case"MultiLineString":r=[],n.length=HG(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,t,n,0,r);break;case"Polygon":r=[],n.length=ZG(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,Math.sqrt(t),n,0,r)}return r&&(this.simplifiedGeometry_=new z0(this.type_,n,r,2,this.properties_,this.id_)),this.squaredTolerance_=t,this.simplifiedGeometry_}),this}}z0.prototype.getFlatCoordinates=z0.prototype.getOrientedFlatCoordinates;class D0{constructor(t){this.rbush_=new XZ(t),this.items_={}}insert(t,e){const n={minX:t[0],minY:t[1],maxX:t[2],maxY:t[3],value:e};this.rbush_.insert(n),this.items_[bV(e)]=n}load(t,e){const n=new Array(e.length);for(let r=0,i=e.length;rt):null}const B0="addfeature",U0="removefeature";class $0 extends hV{constructor(t,e,n){super(t),this.feature=e,this.features=n}}class q0 extends N0{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:!0,projection:void 0,state:"ready",wrapX:void 0===t.wrapX||t.wrapX}),this.on,this.once,this.un,this.loader_=oV,this.format_=t.format||null,this.overlaps_=void 0===t.overlaps||t.overlaps,this.url_=t.url,void 0!==t.loader?this.loader_=t.loader:void 0!==this.url_&&(WV(this.format_,"`format` must be set when `url` is set"),this.loader_=L0(this.url_,this.format_)),this.strategy_=void 0!==t.strategy?t.strategy:I0;const e=void 0===t.useSpatialIndex||t.useSpatialIndex;let n,r;this.featuresRtree_=e?new D0:null,this.loadedExtentsRtree_=new D0,this.loadingExtentsCount_=0,this.nullGeometryFeatures_={},this.idIndex_={},this.uidIndex_={},this.featureChangeKeys_={},this.featuresCollection_=null,Array.isArray(t.features)?r=t.features:t.features&&(n=t.features,r=n.getArray()),e||void 0!==n||(n=new SV(r)),void 0!==r&&this.addFeaturesInternal(r),void 0!==n&&this.bindFeaturesCollection_(n)}addFeature(t){this.addFeatureInternal(t),this.changed()}addFeatureInternal(t){const e=bV(t);if(!this.addToIndex_(e,t))return void(this.featuresCollection_&&this.featuresCollection_.remove(t));this.setupChangeEvents_(e,t);const n=t.getGeometry();if(n){const e=n.getExtent();this.featuresRtree_&&this.featuresRtree_.insert(e,t)}else this.nullGeometryFeatures_[e]=t;this.dispatchEvent(new $0(B0,t))}setupChangeEvents_(t,e){e instanceof z0||(this.featureChangeKeys_[t]=[pV(e,Vq,this.handleFeatureChange_,this),pV(e,qq,this.handleFeatureChange_,this)])}addToIndex_(t,e){let n=!0;if(void 0!==e.getId()){const t=String(e.getId());if(t in this.idIndex_)if(e instanceof z0){const r=this.idIndex_[t];r instanceof z0?Array.isArray(r)?r.push(e):this.idIndex_[t]=[r,e]:n=!1}else n=!1;else this.idIndex_[t]=e}return n&&(WV(!(t in this.uidIndex_),"The passed `feature` was already added to the source"),this.uidIndex_[t]=e),n}addFeatures(t){this.addFeaturesInternal(t),this.changed()}addFeaturesInternal(t){const e=[],n=[],r=[];for(let i=0,s=t.length;i{e||(e=!0,this.addFeature(t.element),e=!1)}),t.addEventListener($q,t=>{e||(e=!0,this.removeFeature(t.element),e=!1)}),this.featuresCollection_=t}clear(t){if(t){for(const t in this.featureChangeKeys_)this.featureChangeKeys_[t].forEach(gV);this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){this.featuresRtree_.forEach(t=>{this.removeFeatureInternal(t)});for(const t in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[t])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const e=new $0("clear");this.dispatchEvent(e),this.changed()}forEachFeature(t){if(this.featuresRtree_)return this.featuresRtree_.forEach(t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureAtCoordinateDirect(t,e){const n=[t[0],t[1],t[0],t[1]];return this.forEachFeatureInExtent(n,function(n){const r=n.getGeometry();if(r instanceof z0||r.intersectsCoordinate(t))return e(n)})}forEachFeatureInExtent(t,e){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(t,e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureIntersectingExtent(t,e){return this.forEachFeatureInExtent(t,function(n){const r=n.getGeometry();if(r instanceof z0||r.intersectsExtent(t)){const t=e(n);if(t)return t}})}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let t;return this.featuresCollection_?t=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(t=this.featuresRtree_.getAll(),uV(this.nullGeometryFeatures_)||nV(t,Object.values(this.nullGeometryFeatures_))),t}getFeaturesAtCoordinate(t){const e=[];return this.forEachFeatureAtCoordinateDirect(t,function(t){e.push(t)}),e}getFeaturesInExtent(t,e){if(this.featuresRtree_){if(!(e&&e.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(t);const n=qW(t,e);return[].concat(...n.map(t=>this.featuresRtree_.getInExtent(t)))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(t,e){const n=t[0],r=t[1];let i=null;const s=[NaN,NaN];let o=1/0;const a=[-1/0,-1/0,1/0,1/0];return e=e||iV,this.featuresRtree_.forEachInExtent(a,function(t){if(e(t)){const e=t.getGeometry(),l=o;if(o=e instanceof z0?0:e.closestPointXY(n,r,s,o),o{--this.loadingExtentsCount_,this.dispatchEvent(new $0("featuresloadend",void 0,t))},()=>{--this.loadingExtentsCount_,this.dispatchEvent(new $0("featuresloaderror"))}),r.insert(t,{extent:t.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(t){const e=this.loadedExtentsRtree_,n=e.forEachInExtent(t,function(e){if(_W(e.extent,t))return e});n&&e.remove(n)}removeFeatures(t){let e=!1;for(let n=0,r=t.length;nG0({...t,geometry:e})).flat();const r="MultiPolygon"===n.type?"Polygon":n.type;if("GeometryCollection"===r||"Circle"===r)throw new Error("Unsupported geometry type: "+r);const i=n.layout.length;return W0(new z0(r,"Polygon"===r?function(t,e,n){return Array.isArray(e[0])?(uK(t,0,e,n)||dK(t=t.slice(),0,e,n),t):(cK(t,0,e,n)||hK(t=t.slice(),0,e,n),t)}(n.flatCoordinates,n.ends,i):n.flatCoordinates,n.ends?.flat(),i,t.properties||{},t.id).enableSimplifyTransformed(),!1,e)}function K0(t,e){if(!t)return null;if(Array.isArray(t)){const n=t.map(t=>K0(t,e));return new A0(n)}return W0(new(0,H0[t.type])(t.flatCoordinates,t.layout||"XY",t.ends),!1,e)}class Z0 extends V0{constructor(){super()}getType(){return"json"}readFeature(t,e){return this.readFeatureFromObject(Y0(t),this.getReadOptions(t,e))}readFeatures(t,e){return this.readFeaturesFromObject(Y0(t),this.getReadOptions(t,e))}readFeatureFromObject(t,e){return yV()}readFeaturesFromObject(t,e){return yV()}readGeometry(t,e){return this.readGeometryFromObject(Y0(t),this.getReadOptions(t,e))}readGeometryFromObject(t,e){return yV()}readProjection(t){return this.readProjectionFromObject(Y0(t))}readProjectionFromObject(t){return yV()}writeFeature(t,e){return JSON.stringify(this.writeFeatureObject(t,e))}writeFeatureObject(t,e){return yV()}writeFeatures(t,e){return JSON.stringify(this.writeFeaturesObject(t,e))}writeFeaturesObject(t,e){return yV()}writeGeometry(t,e){return JSON.stringify(this.writeGeometryObject(t,e))}writeGeometryObject(t,e){return yV()}}function Y0(t){return"string"==typeof t?JSON.parse(t)||null:null!==t?t:null}class X0 extends Z0{constructor(t){t=t||{},super(),this.dataProjection=YH(t.dataProjection?t.dataProjection:"EPSG:4326"),t.featureProjection&&(this.defaultFeatureProjection=YH(t.featureProjection)),t.featureClass&&(this.featureClass=t.featureClass),this.geometryName_=t.geometryName,this.extractGeometryName_=t.extractGeometryName,this.supportedMediaTypes=["application/geo+json","application/vnd.geo+json"]}readFeatureFromObject(t,e){let n=null;n="Feature"===t.type?t:{type:"Feature",geometry:t,properties:null};const r=J0(n.geometry);if(this.featureClass===z0)return G0({geometry:r,id:n.id,properties:n.properties},e);const i=new TQ;return this.geometryName_?i.setGeometryName(this.geometryName_):this.extractGeometryName_&&n.geometry_name&&i.setGeometryName(n.geometry_name),i.setGeometry(K0(r,e)),"id"in n&&i.setId(n.id),n.properties&&i.setProperties(n.properties,!0),i}readFeaturesFromObject(t,e){let n=null;if("FeatureCollection"===t.type){n=[];const r=t.features;for(let t=0,i=r.length;t{t in e&&(n[t]=e[t])}),n}function f1(t){t=t.slice();const e=Object.create(null);for(let n=0;n`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const O1=[y1,v1,b1,w1,_1,x1,E1,C1,P1(S1),T1,M1,R1,L1,I1];function F1(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!F1(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of O1)if(!F1(t,e))return null}return`Expected ${A1(t)} but found ${A1(e)} instead.`}function z1(t,e){return e.some(e=>e.kind===t.kind)}function D1(t,e){return e.some(e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t)}function N1(t,e){return"array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const j1=.96422,B1=.82521,U1=4/29,$1=6/29,q1=3*$1*$1,V1=$1*$1*$1,W1=Math.PI/180,H1=180/Math.PI;function G1(t){return(t%=360)<0&&(t+=360),t}function K1([t,e,n,r]){let i,s;const o=Y1((.2225045*(t=Z1(t))+.7168786*(e=Z1(e))+.0606169*(n=Z1(n)))/1);t===e&&e===n?i=s=o:(i=Y1((.4360747*t+.3850649*e+.1430804*n)/j1),s=Y1((.0139322*t+.0971045*e+.7141733*n)/B1));const a=116*o-16;return[a<0?0:a,500*(i-o),200*(o-s),r]}function Z1(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Y1(t){return t>V1?Math.pow(t,1/3):t/q1+U1}function X1([t,e,n,r]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,o=isNaN(n)?i:i-n/200;return i=1*Q1(i),s=j1*Q1(s),o=B1*Q1(o),[J1(3.1338561*s-1.6168667*i-.4906146*o),J1(-.9787684*s+1.9161415*i+.033454*o),J1(.0719453*s-.2289914*i+1.4052427*o),r]}function J1(t){return(t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function Q1(t){return t>$1?t*t*t:q1*(t-U1)}const t2=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function e2(t,e){return t2(t,e)?t[e]:void 0}function n2(t){return parseInt(t.padEnd(2,t),16)/255}function r2(t,e){return i2(e?t/100:t,0,1)}function i2(t,e,n){return Math.min(Math.max(e,t),n)}function s2(t){return!t.some(Number.isNaN)}const o2={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function a2(t,e,n){return t+n*(e-t)}function l2(t,e,n){return t.map((t,r)=>a2(t,e[r],n))}class c2{constructor(t,e,n,r=1,i=!0){this.r=t,this.g=e,this.b=n,this.a=r,i||(this.r*=r,this.g*=r,this.b*=r,r||this.overwriteGetter("rgb",[t,e,n,r]))}static parse(t){if(t instanceof c2)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return[0,0,0,0];const e=e2(o2,t);if(e){const[t,n,r]=e;return[t/255,n/255,r/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let n=1;return[n2(t.slice(n,n+=e)),n2(t.slice(n,n+=e)),n2(t.slice(n,n+=e)),n2(t.slice(n,n+e)||"ff")]}if(t.startsWith("rgb")){const e=/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/,n=t.match(e);if(n){const[t,e,r,i,s,o,a,l,c,u,h,d]=n,p=[i||" ",a||" ",u].join("");if(" "===p||" /"===p||",,"===p||",,,"===p){const t=[r,o,c].join(""),n="%%%"===t?100:""===t?255:0;if(n){const t=[i2(+e/n,0,1),i2(+s/n,0,1),i2(+l/n,0,1),h?r2(+h,d):1];if(s2(t))return t}}return}}const n=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(n){const[t,e,r,i,s,o,a,l,c]=n,u=[r||" ",s||" ",a].join("");if(" "===u||" /"===u||",,"===u||",,,"===u){const t=[+e,i2(+i,0,100),i2(+o,0,100),l?r2(+l,c):1];if(s2(t))return function([t,e,n,r]){function i(r){const i=(r+t/30)%12,s=e*Math.min(n,1-n);return n-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=G1(t),e/=100,n/=100,[i(0),i(8),i(4),r]}(t)}}}(t);return e?new c2(...e,!1):void 0}get rgb(){const{r:t,g:e,b:n,a:r}=this,i=r||1/0;return this.overwriteGetter("rgb",[t/i,e/i,n/i,r])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,n,r,i]=K1(t),s=Math.sqrt(n*n+r*r);return[Math.round(1e4*s)?G1(Math.atan2(r,n)*H1):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",K1(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,n,r]=this.rgb;return`rgba(${[t,e,n].map(t=>Math.round(255*t)).join(",")},${r})`}static interpolate(t,e,n,r="rgb"){switch(r){case"rgb":{const[r,i,s,o]=l2(t.rgb,e.rgb,n);return new c2(r,i,s,o,!1)}case"hcl":{const[r,i,s,o]=t.hcl,[a,l,c,u]=e.hcl;let h,d;if(isNaN(r)||isNaN(a))isNaN(r)?isNaN(a)?h=NaN:(h=a,1!==s&&0!==s||(d=l)):(h=r,1!==c&&0!==c||(d=i));else{let t=a-r;a>r&&t>180?t-=360:a180&&(t+=360),h=r+n*t}const[p,f,g,m]=function([t,e,n,r]){return t=isNaN(t)?0:t*W1,X1([n,Math.cos(t)*e,Math.sin(t)*e,r])}([h,null!=d?d:a2(i,l,n),a2(s,c,n),a2(o,u,n)]);return new c2(p,f,g,m,!1)}case"lab":{const[r,i,s,o]=X1(l2(t.lab,e.lab,n));return new c2(r,i,s,o,!1)}}}}c2.black=new c2(0,0,0,1),c2.white=new c2(1,1,1,1),c2.transparent=new c2(0,0,0,0),c2.red=new c2(1,0,0,1);class u2{constructor(t,e,n){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=n,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const h2=["bottom","center","top"];class d2{constructor(t,e,n,r,i,s){this.text=t,this.image=e,this.scale=n,this.fontStack=r,this.textColor=i,this.verticalAlign=s}}class p2{constructor(t){this.sections=t}static fromString(t){return new p2([new d2(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some(t=>0!==t.text.length||t.image&&0!==t.image.name.length)}static factory(t){return t instanceof p2?t:p2.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map(t=>t.text).join("")}}class f2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof f2)return t;if("number"==typeof t)return new f2([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]]}return new f2(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new f2(l2(t.values,e.values,n))}}class g2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof g2)return t;if("number"==typeof t)return new g2([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new g2(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new g2(l2(t.values,e.values,n))}}class m2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof m2)return t;if("string"==typeof t){const e=c2.parse(t);if(!e)return;return new m2([e])}if(!Array.isArray(t))return;const e=[];for(const n of t){if("string"!=typeof n)return;const t=c2.parse(n);if(!t)return;e.push(t)}return new m2(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n,r="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof n&&n>=0&&n<=255?void 0===r||"number"==typeof r&&r>=0&&r<=1?null:`Invalid rgba value [${[t,e,n,r].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof r?[t,e,n,r]:[t,e,n]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function C2(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof _2||t instanceof c2||t instanceof u2||t instanceof p2||t instanceof f2||t instanceof g2||t instanceof m2||t instanceof b2||t instanceof w2)return!0;if(Array.isArray(t)){for(const e of t)if(!C2(e))return!1;return!0}if("object"==typeof t){for(const e in t)if(!C2(t[e]))return!1;return!0}return!1}function S2(t){if(null===t)return y1;if("string"==typeof t)return b1;if("boolean"==typeof t)return w1;if("number"==typeof t)return v1;if(t instanceof c2)return _1;if(t instanceof _2)return x1;if(t instanceof u2)return k1;if(t instanceof p2)return E1;if(t instanceof f2)return T1;if(t instanceof g2)return M1;if(t instanceof m2)return R1;if(t instanceof b2)return I1;if(t instanceof w2)return L1;if(Array.isArray(t)){const e=t.length;let n;for(const r of t){const t=S2(r);if(n){if(n===t)continue;n=S1;break}n=t}return P1(n||S1,e)}return C1}function k2(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof c2||t instanceof _2||t instanceof p2||t instanceof f2||t instanceof g2||t instanceof m2||t instanceof b2||t instanceof w2?t.toString():JSON.stringify(t)}class E2{constructor(t,e){this.type=t,this.value=e}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!C2(t[1]))return e.error("invalid value");const n=t[1];let r=S2(n);const i=e.expectedType;return"array"!==r.kind||0!==r.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(r=i),new E2(r,n)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const T2={string:b1,number:v1,boolean:w1,object:C1};class R2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n,r=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const n=t[1];if("string"!=typeof n||!(n in T2)||"object"===n)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=T2[n],r++}else i=S1;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],r++}n=P1(i,s)}else{if(!T2[i])throw new Error(`Types doesn't contain name = ${i}`);n=T2[i]}const s=[];for(;rt.outputDefined())}}const M2={"to-boolean":w1,"to-color":_1,"to-number":v1,"to-string":b1};class L2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[0];if(!M2[n])throw new Error(`Can't parse ${n} as it is not part of the known types`);if(("to-boolean"===n||"to-string"===n)&&2!==t.length)return e.error("Expected one argument.");const r=M2[n],i=[];for(let s=1;s4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:x2(e[0],e[1],e[2],e[3]),!n))return new c2(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new y2(n||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const n of this.args){e=n.evaluate(t);const r=f2.parse(e);if(r)return r}throw new y2(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"numberArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=g2.parse(e);if(r)return r}throw new y2(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"colorArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=m2.parse(e);if(r)return r}throw new y2(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const n of this.args){e=n.evaluate(t);const r=b2.parse(e);if(r)return r}throw new y2(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const n of this.args){if(e=n.evaluate(t),null===e)return 0;const r=Number(e);if(!isNaN(r))return r}throw new y2(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return p2.fromString(k2(this.args[0].evaluate(t)));case"resolvedImage":return w2.fromString(k2(this.args[0].evaluate(t)));case"projectionDefinition":return this.args[0].evaluate(t);default:return k2(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every(t=>t.outputDefined())}}const I2=["Unknown","Point","LineString","Polygon"];class P2{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?I2[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=c2.parse(t),this._parseColorCache.set(t,e)),e}}class A2{constructor(t,e,n=[],r,i=new m1,s=[]){this.registry=t,this.path=n,this.key=n.map(t=>`[${t}]`).join(""),this.scope=i,this.errors=s,this.expectedType=r,this._isConstant=e}parse(t,e,n,r,i={}){return e?this.concat(e,n,r)._parse(t,i):this._parse(t,i)}_parse(t,e){function n(t,e,n){return"assert"===n?new R2(e,[t]):"coerce"===n?new L2(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const r=t[0];if("string"!=typeof r)return this.error(`Expression name must be a string, but found ${typeof r} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[r];if(i){let r=i.parse(t,this);if(!r)return null;if(this.expectedType){const t=this.expectedType,i=r.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))r=n(r,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else r=n(r,t,e.typeAnnotation||"assert")}if(!(r instanceof E2)&&"resolvedImage"!==r.type.kind&&this._isConstant(r)){const t=new P2;try{r=new E2(r.type,r.evaluate(t))}catch(ej){return this.error(ej.message),null}}return r}return this.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error(`Expected an array, but found ${typeof t} instead.`)}concat(t,e,n){const r="number"==typeof t?this.path.concat(t):this.path,i=n?this.scope.concat(n):this.scope;return new A2(this.registry,this._isConstant,r,e||null,i,this.errors)}error(t,...e){const n=`${this.key}${e.map(t=>`[${t}]`).join("")}`;this.errors.push(new g1(n,t))}checkSubtype(t,e){const n=F1(t,e);return n&&this.error(n),n}}class O2{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result)}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const n=[];for(let i=1;i=n.length)throw new y2(`Array index out of bounds: ${e} > ${n.length-1}.`);if(e!==Math.floor(e))throw new y2(`Array index must be an integer, but found ${e} instead.`);return n[e]}eachChild(t){t(this.index),t(this.input)}outputDefined(){return!1}}class D2{constructor(t,e){this.type=w1,this.needle=t,this.haystack=e}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,S1);return n&&r?z1(n.type,[w1,b1,v1,y1,S1])?new D2(n,r):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${A1(n.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!n)return!1;if(!D1(e,["boolean","string","number","null"]))throw new y2(`Expected first argument to be of type boolean, string, number or null, but found ${A1(S2(e))} instead.`);if(!D1(n,["string","array"]))throw new y2(`Expected second argument to be of type array or string, but found ${A1(S2(n))} instead.`);return n.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack)}outputDefined(){return!0}}class N2{constructor(t,e,n){this.type=v1,this.needle=t,this.haystack=e,this.fromIndex=n}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,S1);if(!n||!r)return null;if(!z1(n.type,[w1,b1,v1,y1,S1]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${A1(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,v1);return i?new N2(n,r,i):null}return new N2(n,r)}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!D1(e,["boolean","string","number","null"]))throw new y2(`Expected first argument to be of type boolean, string, number or null, but found ${A1(S2(e))} instead.`);let r;if(this.fromIndex&&(r=this.fromIndex.evaluate(t)),D1(n,["string"])){const t=n.indexOf(e,r);return-1===t?-1:[...n.slice(0,t)].length}if(D1(n,["array"]))return n.indexOf(e,r);throw new y2(`Expected second argument to be of type array or string, but found ${A1(S2(n))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex)}outputDefined(){return!1}}class j2{constructor(t,e,n,r,i,s){this.inputType=t,this.type=e,this.input=n,this.cases=r,this.outputs=i,this.otherwise=s}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let n,r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const i={},s=[];for(let l=2;lNumber.MAX_SAFE_INTEGER)return c.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return c.error("Numeric branch labels must be integer values.");if(n){if(c.checkSubtype(n,S2(t)))return null}else n=S2(t);if(void 0!==i[String(t)])return c.error("Branch labels must be unique.");i[String(t)]=s.length}const u=e.parse(a,l,r);if(!u)return null;r=r||u.type,s.push(u)}const o=e.parse(t[1],1,S1);if(!o)return null;const a=e.parse(t[t.length-1],t.length-1,r);return a?"value"!==o.type.kind&&e.concat(1).checkSubtype(n,o.type)?null:new j2(n,r,o,i,s,a):null}evaluate(t){const e=this.input.evaluate(t);return(S2(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)}outputDefined(){return this.outputs.every(t=>t.outputDefined())&&this.otherwise.outputDefined()}}class B2{constructor(t,e,n){this.type=t,this.branches=e,this.otherwise=n}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const r=[];for(let s=1;se.outputDefined())&&this.otherwise.outputDefined()}}class U2{constructor(t,e,n,r){this.type=t,this.input=e,this.beginIndex=n,this.endIndex=r}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,v1);if(!n||!r)return null;if(!z1(n.type,[P1(S1),b1,S1]))return e.error(`Expected first argument to be of type array or string, but found ${A1(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,v1);return i?new U2(n.type,n,r,i):null}return new U2(n.type,n,r)}evaluate(t){const e=this.input.evaluate(t),n=this.beginIndex.evaluate(t);let r;if(this.endIndex&&(r=this.endIndex.evaluate(t)),D1(e,["string"]))return[...e].slice(n,r).join("");if(D1(e,["array"]))return e.slice(n,r);throw new y2(`Expected first argument to be of type array or string, but found ${A1(S2(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex)}outputDefined(){return!1}}function $2(t,e){const n=t.length-1;let r,i,s=0,o=n,a=0;for(;s<=o;)if(a=Math.floor((s+o)/2),r=t[a],i=t[a+1],r<=e){if(a===n||ee))throw new y2("Input is not a number.");o=a-1}return 0}class q2{constructor(t,e,n){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[r,i]of n)this.labels.push(r),this.outputs.push(i)}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const n=e.parse(t[1],1,v1);if(!n)return null;const r=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let s=1;s=n)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const c=e.parse(o,l,i);if(!c)return null;i=i||c.type,r.push([n,c])}return new q2(i,n,r)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;return r>=e[i-1]?n[i-1].evaluate(t):n[$2(e,r)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every(t=>t.outputDefined())}}function V2(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W2,H2,G2=function(){if(H2)return W2;function t(t,e,n,r){this.cx=3*t,this.bx=3*(n-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=n,this.p2y=r}return H2=1,W2=t,t.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var n=t,r=0;r<8;r++){var i=this.sampleCurveX(n)-t;if(Math.abs(i)i?o=n:a=n,n=.5*(a-o)+o;return n},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},W2}(),K2=V2(G2);class Z2{constructor(t,e,n,r,i){this.type=t,this.operator=e,this.interpolation=n,this.input=r,this.labels=[],this.outputs=[];for(const[s,o]of i)this.labels.push(s),this.outputs.push(o)}static interpolationFactor(t,e,n,r){let i=0;if("exponential"===t.name)i=Y2(e,t.base,n,r);else if("linear"===t.name)i=Y2(e,1,n,r);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new K2(s[0],s[1],s[2],s[3]).solve(Y2(e,1,n,r))}return i}static parse(t,e){let[n,r,i,...s]=t;if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){const t=r[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:t}}else{if("cubic-bezier"!==r[0])return e.error(`Unknown interpolation type ${String(r[0])}`,1,0);{const t=r.slice(1);if(4!==t.length||t.some(t=>"number"!=typeof t||t<0||t>1))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:t}}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,v1),!i)return null;const o=[];let a=null;"interpolate-hcl"!==n&&"interpolate-lab"!==n||e.expectedType==R1?e.expectedType&&"value"!==e.expectedType.kind&&(a=e.expectedType):a=_1;for(let l=0;l=t)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',r);const c=e.parse(n,i,a);if(!c)return null;a=a||c.type,o.push([t,c])}return N1(a,v1)||N1(a,x1)||N1(a,_1)||N1(a,T1)||N1(a,M1)||N1(a,R1)||N1(a,I1)||N1(a,P1(v1))?new Z2(a,n,r,i,o):e.error(`Type ${A1(a)} is not interpolatable.`)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;if(r>=e[i-1])return n[i-1].evaluate(t);const s=$2(e,r),o=e[s],a=e[s+1],l=Z2.interpolationFactor(this.interpolation,r,o,a),c=n[s].evaluate(t),u=n[s+1].evaluate(t);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return a2(c,u,l);case"color":return c2.interpolate(c,u,l);case"padding":return f2.interpolate(c,u,l);case"colorArray":return m2.interpolate(c,u,l);case"numberArray":return g2.interpolate(c,u,l);case"variableAnchorOffsetCollection":return b2.interpolate(c,u,l);case"array":return l2(c,u,l);case"projectionDefinition":return _2.interpolate(c,u,l)}case"interpolate-hcl":switch(this.type.kind){case"color":return c2.interpolate(c,u,l,"hcl");case"colorArray":return m2.interpolate(c,u,l,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return c2.interpolate(c,u,l,"lab");case"colorArray":return m2.interpolate(c,u,l,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every(t=>t.outputDefined())}}function Y2(t,e,n,r){const i=r-n,s=t-n;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}class X2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n=null;const r=e.expectedType;r&&"value"!==r.kind&&(n=r);const i=[];for(const o of t.slice(1)){const t=e.parse(o,1+i.length,n,void 0,{typeAnnotation:"omit"});if(!t)return null;n=n||t.type,i.push(t)}if(!n)throw new Error("No output type");const s=r&&i.some(t=>F1(r,t.type));return new X2(s?S1:n,i)}evaluate(t){let e,n=null,r=0;for(const i of this.args)if(r++,n=i.evaluate(t),n&&n instanceof w2&&!n.available&&(e||(e=n.name),n=null,r===this.args.length&&(n=e)),null!==n)break;return n}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every(t=>t.outputDefined())}}function J2(t,e){return"=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function Q2(t,e,n,r){return 0===r.compare(e,n)}function t3(t,e,n){const r="=="!==t&&"!="!==t;return class i{constructor(t,e,n){this.type=w1,this.lhs=t,this.rhs=e,this.collator=n,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const n=t[0];let s=e.parse(t[1],1,S1);if(!s)return null;if(!J2(n,s.type))return e.concat(1).error(`"${n}" comparisons are not supported for type '${A1(s.type)}'.`);let o=e.parse(t[2],2,S1);if(!o)return null;if(!J2(n,o.type))return e.concat(2).error(`"${n}" comparisons are not supported for type '${A1(o.type)}'.`);if(s.type.kind!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error(`Cannot compare types '${A1(s.type)}' and '${A1(o.type)}'.`);r&&("value"===s.type.kind&&"value"!==o.type.kind?s=new R2(o.type,[s]):"value"!==s.type.kind&&"value"===o.type.kind&&(o=new R2(s.type,[o])));let a=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(a=e.parse(t[3],3,k1),!a)return null}return new i(s,o,a)}evaluate(i){const s=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(r&&this.hasUntypedArgument){const e=S2(s),n=S2(o);if(e.kind!==n.kind||"string"!==e.kind&&"number"!==e.kind)throw new y2(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${n.kind}) instead.`)}if(this.collator&&!r&&this.hasUntypedArgument){const t=S2(s),n=S2(o);if("string"!==t.kind||"string"!==n.kind)return e(i,s,o)}return this.collator?n(i,s,o,this.collator.evaluate(i)):e(i,s,o)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator)}outputDefined(){return!0}}}const e3=t3("==",function(t,e,n){return e===n},Q2),n3=t3("!=",function(t,e,n){return e!==n},function(t,e,n,r){return!Q2(0,e,n,r)}),r3=t3("<",function(t,e,n){return e",function(t,e,n){return e>n},function(t,e,n,r){return r.compare(e,n)>0}),s3=t3("<=",function(t,e,n){return e<=n},function(t,e,n,r){return r.compare(e,n)<=0}),o3=t3(">=",function(t,e,n){return e>=n},function(t,e,n,r){return r.compare(e,n)>=0});class a3{constructor(t,e,n){this.type=k1,this.locale=n,this.caseSensitive=t,this.diacriticSensitive=e}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const n=t[1];if("object"!=typeof n||Array.isArray(n))return e.error("Collator options argument must be an object.");const r=e.parse(void 0!==n["case-sensitive"]&&n["case-sensitive"],1,w1);if(!r)return null;const i=e.parse(void 0!==n["diacritic-sensitive"]&&n["diacritic-sensitive"],1,w1);if(!i)return null;let s=null;return n.locale&&(s=e.parse(n.locale,1,b1),!s)?null:new a3(r,i,s)}evaluate(t){return new u2(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale)}outputDefined(){return!1}}class l3{constructor(t,e,n,r,i){this.type=b1,this.number=t,this.locale=e,this.currency=n,this.minFractionDigits=r,this.maxFractionDigits=i}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,v1);if(!n)return null;const r=t[2];if("object"!=typeof r||Array.isArray(r))return e.error("NumberFormat options argument must be an object.");let i=null;if(r.locale&&(i=e.parse(r.locale,1,b1),!i))return null;let s=null;if(r.currency&&(s=e.parse(r.currency,1,b1),!s))return null;let o=null;if(r["min-fraction-digits"]&&(o=e.parse(r["min-fraction-digits"],1,v1),!o))return null;let a=null;return r["max-fraction-digits"]&&(a=e.parse(r["max-fraction-digits"],1,v1),!a)?null:new l3(n,i,s,o,a)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits)}outputDefined(){return!1}}class c3{constructor(t){this.type=E1,this.sections=t}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[1];if(!Array.isArray(n)&&"object"==typeof n)return e.error("First argument must be an image or text section.");const r=[];let i=!1;for(let s=1;s<=t.length-1;++s){const n=t[s];if(i&&"object"==typeof n&&!Array.isArray(n)){i=!1;let t=null;if(n["font-scale"]&&(t=e.parse(n["font-scale"],1,v1),!t))return null;let s=null;if(n["text-font"]&&(s=e.parse(n["text-font"],1,P1(b1)),!s))return null;let o=null;if(n["text-color"]&&(o=e.parse(n["text-color"],1,_1),!o))return null;let a=null;if(n["vertical-align"]){if("string"==typeof n["vertical-align"]&&!h2.includes(n["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${n["vertical-align"]}' instead.`);if(a=e.parse(n["vertical-align"],1,b1),!a)return null}const l=r[r.length-1];l.scale=t,l.font=s,l.textColor=o,l.verticalAlign=a}else{const n=e.parse(t[s],1,S1);if(!n)return null;const o=n.type.kind;if("string"!==o&&"value"!==o&&"null"!==o&&"resolvedImage"!==o)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,r.push({content:n,scale:null,font:null,textColor:null,verticalAlign:null})}}return new c3(r)}evaluate(t){return new p2(this.sections.map(e=>{const n=e.content.evaluate(t);return S2(n)===L1?new d2("",n,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new d2(k2(n),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)}))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign)}outputDefined(){return!1}}class u3{constructor(t){this.type=L1,this.input=t}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,b1);return n?new u3(n):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),n=w2.fromString(e);return n&&t.availableImages&&(n.available=t.availableImages.indexOf(e)>-1),n}eachChild(t){t(this.input)}outputDefined(){return!1}}class h3{constructor(t){this.type=v1,this.input=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=e.parse(t[1],1);return n?"array"!==n.type.kind&&"string"!==n.type.kind&&"value"!==n.type.kind?e.error(`Expected argument of type string or array, but found ${A1(n.type)} instead.`):new h3(n):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return[...e].length;if(Array.isArray(e))return e.length;throw new y2(`Expected value to be of type string or array, but found ${A1(S2(e))} instead.`)}eachChild(t){t(this.input)}outputDefined(){return!1}}const d3=8192;function p3(t,e){const n=(180+t[0])/360,r=(i=t[1],(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+i*Math.PI/360)))/360);var i;const s=Math.pow(2,e.z);return[Math.round(n*s*d3),Math.round(r*s*d3)]}function f3(t,e){const n=Math.pow(2,e.z);return[(i=(t[0]/d3+e.x)/n,360*i-180),(r=(t[1]/d3+e.y)/n,360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90)];var r,i}function g3(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1])}function m3(t,e){return!(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function y3(t,e,n){return e[1]>t[1]!=n[1]>t[1]&&t[0]<(n[0]-e[0])*(t[1]-e[1])/(n[1]-e[1])+e[0]}function v3(t,e,n){const r=t[0]-e[0],i=t[1]-e[1],s=t[0]-n[0],o=t[1]-n[1];return r*o-s*i===0&&r*s<=0&&i*o<=0}function b3(t,e,n,r){const i=[e[0]-t[0],e[1]-t[1]];return 0!==function(t,e){return t[0]*e[1]-t[1]*e[0]}([r[0]-n[0],r[1]-n[1]],i)&&!(!k3(t,e,n,r)||!k3(n,r,t,e))}function w3(t,e,n){for(const r of n)for(let n=0;n0&&h<0||u<0&&h>0}function E3(t,e,n){const r=[];for(let i=0;in[2]){const e=.5*r;let i=t[0]-n[0]>e?-r:n[0]-t[0]>e?r:0;0===i&&(i=t[0]-n[2]>e?-r:n[2]-t[0]>e?r:0),t[0]+=i}g3(e,t)}function M3(t,e,n,r){const i=Math.pow(2,r.z)*d3,s=[r.x*d3,r.y*d3],o=[];for(const a of t)for(const t of a){const r=[t.x+s[0],t.y+s[1]];R3(r,e,n,i),o.push(r)}return o}function L3(t,e,n,r){const i=Math.pow(2,r.z)*d3,s=[r.x*d3,r.y*d3],o=[];for(const a of t){const t=[];for(const n of a){const r=[n.x+s[0],n.y+s[1]];g3(e,r),t.push(r)}o.push(t)}if(e[2]-e[0]<=i/2){!function(t){t[0]=t[1]=1/0,t[2]=t[3]=-1/0}(e);for(const t of o)for(const r of t)R3(r,e,n,i)}return o}class I3{constructor(t,e){this.type=w1,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(C2(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const n of e.features){const{type:e,coordinates:r}=n.geometry;"Polygon"===e&&t.push(r),"MultiPolygon"===e&&t.push(...r)}if(t.length)return new I3(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new I3(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new I3(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=E3(e.coordinates,r,i),o=M3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!_3(t,s))return!1}if("MultiPolygon"===e.type){const s=T3(e.coordinates,r,i),o=M3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!x3(t,s))return!1}return!0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=E3(e.coordinates,r,i),o=L3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!C3(t,s))return!1}if("MultiPolygon"===e.type){const s=T3(e.coordinates,r,i),o=L3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!S3(t,s))return!1}return!0}(t,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}class P3{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(t){this.data.push(t),this._up(this.length++)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:n}=this,r=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(n(r,s)>=0)break;e[t]=s,t=i}e[t]=r}_down(t){const{data:e,compare:n}=this,r=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[r],t=r}e[t]=i}}function A3(t){let e=0;for(let n,r,i=0,s=t.length,o=s-1;i1?(l=t[a+1][0],c=t[a+1][1]):d>0&&(l+=u/this.kx*d,c+=h/this.ky*d)),u=this.wrap(e[0]-l)*this.kx,h=(e[1]-c)*this.ky;const p=u*u+h*h;p180;)t-=360;return t}}function N3(t,e){return e[0]-t[0]}function j3(t){return t[1]-t[0]+1}function B3(t,e){return t[1]>=t[0]&&t[1]t[1])return[null,null];const n=j3(t);if(e){if(2===n)return[t,null];const e=Math.floor(n/2);return[[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===n)return[t,null];const r=Math.floor(n/2)-1;return[[t[0],t[0]+r],[t[0]+r+1,t[1]]]}function $3(t,e){if(!B3(e,t.length))return[1/0,1/0,-1/0,-1/0];const n=[1/0,1/0,-1/0,-1/0];for(let r=e[0];r<=e[1];++r)g3(n,t[r]);return n}function q3(t){const e=[1/0,1/0,-1/0,-1/0];for(const n of t)for(const t of n)g3(e,t);return e}function V3(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function W3(t,e,n){if(!V3(t)||!V3(e))return NaN;let r=0,i=0;return t[2]e[2]&&(r=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=r)return r;if(m3(i,s)){if(J3(t,e))return 0}else if(J3(e,t))return 0;let o=1/0;for(const a of t)for(let t=0,r=a.length,i=r-1;t0;){const i=o.pop();if(i[0]>=s)continue;const l=i[1],c=e?50:100;if(j3(l)<=c){if(!B3(l,t.length))return NaN;if(e){const e=X3(t,l,n,r);if(isNaN(e)||0===e)return e;s=Math.min(s,e)}else for(let e=l[0];e<=l[1];++e){const i=Y3(t[e],n,r);if(s=Math.min(s,i),0===s)return 0}}else{const n=U3(l,e);t5(o,s,r,t,a,n[0]),t5(o,s,r,t,a,n[1])}}return s}function r5(t,e,n,r,i,s=1/0){let o=Math.min(s,i.distance(t[0],n[0]));if(0===o)return o;const a=new P3([[0,[0,t.length-1],[0,n.length-1]]],N3);for(;a.length>0;){const s=a.pop();if(s[0]>=o)continue;const l=s[1],c=s[2],u=e?50:100,h=r?50:100;if(j3(l)<=u&&j3(c)<=h){if(!B3(l,t.length)&&B3(c,n.length))return NaN;let s;if(e&&r)s=K3(t,l,n,c,i),o=Math.min(o,s);else if(e&&!r){const e=t.slice(l[0],l[1]+1);for(let t=c[0];t<=c[1];++t)if(s=H3(n[t],e,i),o=Math.min(o,s),0===o)return o}else if(!e&&r){const e=n.slice(c[0],c[1]+1);for(let n=l[0];n<=l[1];++n)if(s=H3(t[n],e,i),o=Math.min(o,s),0===o)return o}else s=Z3(t,l,n,c,i),o=Math.min(o,s)}else{const s=U3(l,e),u=U3(c,r);e5(a,o,i,t,n,s[0],u[0]),e5(a,o,i,t,n,s[0],u[1]),e5(a,o,i,t,n,s[1],u[0]),e5(a,o,i,t,n,s[1],u[1])}}return o}function i5(t){return"MultiPolygon"===t.type?t.coordinates.map(t=>({type:"Polygon",coordinates:t})):"MultiLineString"===t.type?t.coordinates.map(t=>({type:"LineString",coordinates:t})):"MultiPoint"===t.type?t.coordinates.map(t=>({type:"Point",coordinates:t})):[t]}class s5{constructor(t,e){this.type=v1,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(C2(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new s5(e,e.features.map(t=>i5(t.geometry)).flat());if("Feature"===e.type)return new s5(e,i5(e.geometry));if("type"in e&&"coordinates"in e)return new s5(e,i5(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map(e=>f3([e.x,e.y],t.canonical));if(0===n.length)return NaN;const i=new D3(r[0][1]);let s=1/0;for(const o of e){switch(o.type){case"Point":s=Math.min(s,r5(r,!1,[o.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,r5(r,!1,o.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,n5(r,!1,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map(e=>f3([e.x,e.y],t.canonical));if(0===n.length)return NaN;const i=new D3(r[0][1]);let s=1/0;for(const o of e){switch(o.type){case"Point":s=Math.min(s,r5(r,!0,[o.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,r5(r,!0,o.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,n5(r,!0,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const n=t.geometry();if(0===n.length||0===n[0].length)return NaN;const r=function(t){if(t.length<=1)return[t];const e=[];let n,r;for(const i of t){const t=A3(i);0!==t&&(i.area=Math.abs(t),void 0===r&&(r=t<0),r===t<0?(n&&e.push(n),n=[i]):n.push(i))}return n&&e.push(n),e}(n).map(e=>e.map(e=>e.map(e=>f3([e.x,e.y],t.canonical)))),i=new D3(r[0][0][0][1]);let s=1/0;for(const o of e)for(const t of r){switch(o.type){case"Point":s=Math.min(s,n5([o.coordinates],!1,t,i,s));break;case"LineString":s=Math.min(s,n5(o.coordinates,!0,t,i,s));break;case"Polygon":s=Math.min(s,Q3(t,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class o5{constructor(t){this.type=S1,this.key=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=t[1];return null==n?e.error("Global state property must be defined."):"string"!=typeof n?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new o5(n)}evaluate(t){var e;const n=null===(e=t.globals)||void 0===e?void 0:e.globalState;return n&&0!==Object.keys(n).length?e2(n,this.key):null}eachChild(){}outputDefined(){return!1}}const a5={"==":e3,"!=":n3,">":i3,"<":r3,">=":o3,"<=":s3,array:R2,at:z2,boolean:R2,case:B2,coalesce:X2,collator:a3,format:c3,image:u3,in:D2,"index-of":N2,interpolate:Z2,"interpolate-hcl":Z2,"interpolate-lab":Z2,length:h3,let:O2,literal:E2,match:j2,number:R2,"number-format":l3,object:R2,slice:U2,step:q2,string:R2,"to-boolean":L2,"to-color":L2,"to-number":L2,"to-string":L2,var:F2,within:I3,distance:s5,"global-state":o5};class l5{constructor(t,e,n,r){this.name=t,this.type=e,this._evaluate=n,this.args=r}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t)}outputDefined(){return!1}static parse(t,e){const n=t[0],r=l5.definitions[n];if(!r)return e.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(r)?r[0]:r.type,s=Array.isArray(r)?[[r[1],r[2]]]:r.overloads,o=s.filter(([e])=>!Array.isArray(e)||e.length===t.length-1);let a=null;for(const[l,c]of o){a=new A2(e.registry,p5,e.path,null,e.scope);const r=[];let s=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(A1).join(", ")})`:`(${A1(e.type)}...)`;var e}).join(" | "),r=[];for(let i=1;i{n=e?n&&p5(t):n&&t instanceof E2}),!!n&&f5(t)&&m5(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function f5(t){if(t instanceof l5){if("get"===t.name&&1===t.args.length)return!1;if("feature-state"===t.name)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}if(t instanceof I3)return!1;if(t instanceof s5)return!1;let e=!0;return t.eachChild(t=>{e&&!f5(t)&&(e=!1)}),e}function g5(t){if(t instanceof l5&&"feature-state"===t.name)return!1;let e=!0;return t.eachChild(t=>{e&&!g5(t)&&(e=!1)}),e}function m5(t,e){if(t instanceof l5&&e.indexOf(t.name)>=0)return!1;let n=!0;return t.eachChild(t=>{n&&!m5(t,e)&&(n=!1)}),n}function y5(t){return{result:"success",value:t}}function v5(t){return{result:"error",value:t}}function b5(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)&&S2(t)===C1}l5.register(a5,{error:[{kind:"error"},[b1],(t,[e])=>{throw new y2(e.evaluate(t))}],typeof:[b1,[S1],(t,[e])=>A1(S2(e.evaluate(t)))],"to-rgba":[P1(v1,4),[_1],(t,[e])=>{const[n,r,i,s]=e.evaluate(t).rgb;return[255*n,255*r,255*i,s]}],rgb:[_1,[v1,v1,v1],c5],rgba:[_1,[v1,v1,v1,v1],c5],has:{type:w1,overloads:[[[b1],(t,[e])=>u5(e.evaluate(t),t.properties())],[[b1,C1],(t,[e,n])=>u5(e.evaluate(t),n.evaluate(t))]]},get:{type:S1,overloads:[[[b1],(t,[e])=>h5(e.evaluate(t),t.properties())],[[b1,C1],(t,[e,n])=>h5(e.evaluate(t),n.evaluate(t))]]},"feature-state":[S1,[b1],(t,[e])=>h5(e.evaluate(t),t.featureState||{})],properties:[C1,[],t=>t.properties()],"geometry-type":[b1,[],t=>t.geometryType()],id:[S1,[],t=>t.id()],zoom:[v1,[],t=>t.globals.zoom],"heatmap-density":[v1,[],t=>t.globals.heatmapDensity||0],elevation:[v1,[],t=>t.globals.elevation||0],"line-progress":[v1,[],t=>t.globals.lineProgress||0],accumulated:[S1,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[v1,d5(v1),(t,e)=>{let n=0;for(const r of e)n+=r.evaluate(t);return n}],"*":[v1,d5(v1),(t,e)=>{let n=1;for(const r of e)n*=r.evaluate(t);return n}],"-":{type:v1,overloads:[[[v1,v1],(t,[e,n])=>e.evaluate(t)-n.evaluate(t)],[[v1],(t,[e])=>-e.evaluate(t)]]},"/":[v1,[v1,v1],(t,[e,n])=>e.evaluate(t)/n.evaluate(t)],"%":[v1,[v1,v1],(t,[e,n])=>e.evaluate(t)%n.evaluate(t)],ln2:[v1,[],()=>Math.LN2],pi:[v1,[],()=>Math.PI],e:[v1,[],()=>Math.E],"^":[v1,[v1,v1],(t,[e,n])=>Math.pow(e.evaluate(t),n.evaluate(t))],sqrt:[v1,[v1],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))],log2:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[v1,[v1],(t,[e])=>Math.sin(e.evaluate(t))],cos:[v1,[v1],(t,[e])=>Math.cos(e.evaluate(t))],tan:[v1,[v1],(t,[e])=>Math.tan(e.evaluate(t))],asin:[v1,[v1],(t,[e])=>Math.asin(e.evaluate(t))],acos:[v1,[v1],(t,[e])=>Math.acos(e.evaluate(t))],atan:[v1,[v1],(t,[e])=>Math.atan(e.evaluate(t))],min:[v1,d5(v1),(t,e)=>Math.min(...e.map(e=>e.evaluate(t)))],max:[v1,d5(v1),(t,e)=>Math.max(...e.map(e=>e.evaluate(t)))],abs:[v1,[v1],(t,[e])=>Math.abs(e.evaluate(t))],round:[v1,[v1],(t,[e])=>{const n=e.evaluate(t);return n<0?-Math.round(-n):Math.round(n)}],floor:[v1,[v1],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[v1,[v1],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[w1,[b1,S1],(t,[e,n])=>t.properties()[e.value]===n.value],"filter-id-==":[w1,[S1],(t,[e])=>t.id()===e.value],"filter-type-==":[w1,[b1],(t,[e])=>t.geometryType()===e.value],"filter-<":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r{const n=t.id(),r=e.value;return typeof n==typeof r&&n":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>i}],"filter-id->":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>r}],"filter-<=":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r<=i}],"filter-id-<=":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n<=r}],"filter->=":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>=i}],"filter-id->=":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>=r}],"filter-has":[w1,[S1],(t,[e])=>e.value in t.properties()],"filter-has-id":[w1,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[w1,[P1(b1)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[w1,[P1(S1)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[w1,[b1,P1(S1)],(t,[e,n])=>n.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[w1,[b1,P1(S1)],(t,[e,n])=>function(t,e,n,r){for(;n<=r;){const i=n+r>>1;if(e[i]===t)return!0;e[i]>t?r=i-1:n=i+1}return!1}(t.properties()[e.value],n.value,0,n.value.length-1)],all:{type:w1,overloads:[[[w1,w1],(t,[e,n])=>e.evaluate(t)&&n.evaluate(t)],[d5(w1),(t,e)=>{for(const n of e)if(!n.evaluate(t))return!1;return!0}]]},any:{type:w1,overloads:[[[w1,w1],(t,[e,n])=>e.evaluate(t)||n.evaluate(t)],[d5(w1),(t,e)=>{for(const n of e)if(n.evaluate(t))return!0;return!1}]]},"!":[w1,[w1],(t,[e])=>!e.evaluate(t)],"is-supported-script":[w1,[b1],(t,[e])=>{const n=t.globals&&t.globals.isSupportedScript;return!n||n(e.evaluate(t))}],upcase:[b1,[b1],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[b1,[b1],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[b1,d5(S1),(t,e)=>e.map(e=>k2(e.evaluate(t))).join("")],"resolved-locale":[b1,[k1],(t,[e])=>e.evaluate(t).resolvedLocale()]});class w5{constructor(t,e){this.expression=t,this._warningHistory={},this._evaluator=new P2,this._defaultValue=e?function(t){if("color"===t.type&&b5(t.default))return new c2(0,0,0,0);switch(t.type){case"color":return c2.parse(t.default)||null;case"padding":return f2.parse(t.default)||null;case"numberArray":return g2.parse(t.default)||null;case"colorArray":return m2.parse(t.default)||null;case"variableAnchorOffsetCollection":return b2.parse(t.default)||null;case"projectionDefinition":return _2.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=n,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,n,r,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=n||null,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new y2(`Expected value to be one of ${Object.keys(this._enumValues).map(t=>JSON.stringify(t)).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(ej){return this._warningHistory[ej.message]||(this._warningHistory[ej.message]=!0,"undefined"!=typeof console&&console.warn(ej.message)),this._defaultValue}}}function _5(t,e){const n=new A2(a5,p5,[],e?function(t){const e={color:_1,string:b1,number:v1,enum:b1,boolean:w1,formatted:E1,padding:T1,numberArray:M1,colorArray:R1,projectionDefinition:x1,resolvedImage:L1,variableAnchorOffsetCollection:I1};return"array"===t.type?P1(e[t.value]||S1,t.length):e[t.type]}(e):void 0),r=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return r?y5(new w5(r,e)):v5(n.errors)}class x5{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!g5(e.expression),this.globalStateRefs=E5(e.expression)}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._styleExpression.evaluate(t,e,n,r,i,s)}}class C5{constructor(t,e,n,r){this.kind=t,this.zoomStops=n,this._styleExpression=e,this.isStateDependent="camera"!==t&&!g5(e.expression),this.globalStateRefs=E5(e.expression),this.interpolationType=r}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._styleExpression.evaluate(t,e,n,r,i,s)}interpolationFactor(t,e,n){return this.interpolationType?Z2.interpolationFactor(this.interpolationType,t,e,n):0}}function S5(t,e){const n=_5(t,e);if("error"===n.result)return n;const r=n.value.expression,i=f5(r);if(!i&&"data-driven"!==(s=e)["property-type"]&&"cross-faded-data-driven"!==s["property-type"])return v5([new g1("","data expressions not supported")]);var s;const o=m5(r,["zoom"]);if(!o&&!function(t){return!!t.expression&&t.expression.parameters.indexOf("zoom")>-1}(e))return v5([new g1("","zoom expressions not supported")]);const a=k5(r);if(!a&&!o)return v5([new g1("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);if(a instanceof g1)return v5([a]);if(a instanceof Z2&&!function(t){return!!t.expression&&t.expression.interpolated}(e))return v5([new g1("",'"interpolate" expressions cannot be used with this property')]);if(!a)return y5(new x5(i?"constant":"source",n.value));const l=a instanceof Z2?a.interpolation:void 0;return y5(new C5(i?"camera":"composite",n.value,a.labels,l))}function k5(t){let e=null;if(t instanceof O2)e=k5(t.result);else if(t instanceof X2){for(const n of t.args)if(e=k5(n),e)break}else(t instanceof q2||t instanceof Z2)&&t.input instanceof l5&&"zoom"===t.input.name&&(e=t);return e instanceof g1||t.eachChild(t=>{const n=k5(t);n instanceof g1?e=n:!e&&n?e=new g1("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&n&&e!==n&&(e=new g1("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),e}function E5(t,e=new Set){return t instanceof o5&&e.add(t.key),t.eachChild(t=>{E5(t,e)}),e}function T5(t){if(!0===t||!1===t)return!0;if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!T5(e)&&"boolean"!=typeof e)return!1;return!0;default:return!0}}const R5={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function M5(t){if(null==t)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};T5(t)||(t=P5(t));const e=_5(t,R5);if("error"===e.result)throw new Error(e.value.map(t=>`${t.key}: ${t.message}`).join(", "));return{filter:(t,n,r)=>e.value.evaluate(t,n,{},r),needGeometry:I5(t),getGlobalStateRefs:()=>E5(e.value.expression)}}function L5(t,e){return te?1:0}function I5(t){if(!Array.isArray(t))return!1;if("within"===t[0]||"distance"===t[0])return!0;for(let e=1;e"===e||"<="===e||">="===e?A5(t[1],t[2],e):"any"===e?(n=t.slice(1),["any"].concat(n.map(P5))):"all"===e?["all"].concat(t.slice(1).map(P5)):"none"===e?["all"].concat(t.slice(1).map(P5).map(z5)):"in"===e?O5(t[1],t.slice(2)):"!in"===e?z5(O5(t[1],t.slice(2))):"has"===e?F5(t[1]):"!has"!==e||z5(F5(t[1]));var n}function A5(t,e,n){switch(t){case"$type":return[`filter-type-${n}`,e];case"$id":return[`filter-id-${n}`,e];default:return[`filter-${n}`,t,e]}}function O5(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(t=>typeof t!=typeof e[0])?["filter-in-large",t,["literal",e.sort(L5)]]:["filter-in-small",t,["literal",e]]}}function F5(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function z5(t){return["!",t]}function D5(t){return"object"==typeof t?["literal",t]:t}function N5(t){switch(t.colorSpace){case"hcl":return"interpolate-hcl";case"lab":return"interpolate-lab";default:return"interpolate"}}function j5(t,e){const n=D5((r=t.default,i=e.default,void 0!==r?r:void 0!==i?i:void 0));var r,i;return void 0===n&&"resolvedImage"===e.type?"":n}function B5(t,e,n){const r=q5(t,e),i=["get",t.property];if("categorical"===r&&"boolean"==typeof n[0][0]){const r=["case"];for(const t of n)r.push(["==",i,t[0]],t[1]);return r.push(j5(t,e)),r}if("categorical"===r){const r=["match",i];for(const t of n)$5(r,t[0],t[1],!1);return r.push(j5(t,e)),r}if("interval"===r){const e=["step",["number",i]];for(const t of n)$5(e,t[0],t[1],!0);return U5(e),void 0===t.default?e:["case",["==",["typeof",i],"number"],e,D5(t.default)]}if("exponential"===r){const e=void 0!==t.base?t.base:1,r=[N5(t),1===e?["linear"]:["exponential",e],["number",i]];for(const t of n)$5(r,t[0],t[1],!1);return void 0===t.default?r:["case",["==",["typeof",i],"number"],r,D5(t.default)]}throw new Error(`Unknown property function type ${r}`)}function U5(t){"step"===t[0]&&3===t.length&&(t.push(0),t.push(t[3]))}function $5(t,e,n,r){t.length>3&&e===t[t.length-2]||(r&&2===t.length||t.push(e),t.push(n))}function q5(t,e){return t.type?t.type:e.expression.interpolated?"exponential":"interval"}function V5(t){const e=["concat"],n=/{([^{}]+)}/g;let r=0;for(let i=n.exec(t);null!==i;i=n.exec(t)){const s=t.slice(r,n.lastIndex-i[0].length);r=n.lastIndex,s.length>0&&e.push(s),e.push(["get",i[1]])}if(1===e.length)return t;if(r":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};var H5={thin:100,hairline:100,"ultra-light":200,"extra-light":200,light:300,book:300,regular:400,normal:400,plain:400,roman:400,standard:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,heavy:900,black:900,"heavy-black":900,fat:900,poster:900,"ultra-black":950,"extra-black":950},G5=" ",K5=/(italic|oblique)$/i,Z5={};function Y5(t,e,n){var r=Z5[t];if(!r){Array.isArray(t)||(t=[t]);for(var i,s,o=400,a="normal",l=[],c=0,u=t.length;c1?h[h.length-2].toLowerCase():"";if(d==p||d==p.replace("-","")||f+"-"+d==p){o=i?o:H5[p],h.pop(),f&&p.startsWith(f)&&h.pop();break}}i||"number"!=typeof d||(o=d,i=!0);var g=h.join(G5).replace("Klokantech Noto Sans","Noto Sans").replace("DIN Pro","Barlow").replace("Arial Unicode MS","Arial");-1!==g.indexOf(G5)&&(g='"'+g+'"'),l.push(g)}r=Z5[t]=[a,o,l]}return r[0]+G5+r[1]+G5+e+"px"+(n?"/"+n:"")+G5+r[2]}class X5 extends iJ{constructor(t,e,n,r,i){super(t,e,n,void 0!==i?0:2),this.loader_=void 0!==i?i:null,this.canvas_=r,this.error_=null}getError(){return this.error_}handleLoad_(t){t?(this.error_=t,this.state=3):this.state=2,this.changed()}load(){0==this.state&&(this.state=1,this.changed(),this.loader_(this.handleLoad_.bind(this)))}getImage(){return this.canvas_}}class J5 extends dV{constructor(t,e,n){super(),n=n||{},this.tileCoord=t,this.state=e,this.key="",this.transition_=void 0===n.transition?250:n.transition,this.transitionStarts_={},this.interpolate=!!n.interpolate}changed(){this.dispatchEvent(Vq)}release(){this.setState(4)}getKey(){return this.key+"/"+this.tileCoord}getTileCoord(){return this.tileCoord}getState(){return this.state}setState(t){if(4!==this.state){if(3!==this.state&&this.state>t)throw new Error("Tile load sequence violation");this.state=t,this.changed()}}load(){yV()}getAlpha(t,e){if(!this.transition_)return 1;let n=this.transitionStarts_[t];if(n){if(-1===n)return 1}else n=e,this.transitionStarts_[t]=n;const r=e-n+1e3/60;return r>=this.transition_?1:GW(r/this.transition_)}inTransition(t){return!!this.transition_&&-1!==this.transitionStarts_[t]}endTransition(t){this.transition_&&(this.transitionStarts_[t]=-1)}disposeInternal(){this.release(),super.disposeInternal()}}class Q5 extends J5{constructor(t,e,n,r,i,s){super(t,e,s),this.crossOrigin_=r,this.src_=n,this.key=n,this.image_,PV?this.image_=new OffscreenCanvas(1,1):(this.image_=new Image,null!==r&&(this.image_.crossOrigin=r)),this.unlisten_=null,this.tileLoadFunction_=i}getImage(){return this.image_}setImage(t){this.image_=t,this.state=2,this.unlistenImage_(),this.changed()}getCrossOrigin(){return this.crossOrigin_}handleImageError_(){this.state=3,this.unlistenImage_(),this.image_=function(){const t=AK(1,1);return t.fillStyle="rgba(0,0,0,0)",t.fillRect(0,0,1,1),t.canvas}(),this.changed()}handleImageLoad_(){if(PV)this.state=2;else{const t=this.image_;t.naturalWidth&&t.naturalHeight?this.state=2:this.state=4}this.unlistenImage_(),this.changed()}load(){3==this.state&&(this.state=0,this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)),0==this.state&&(this.state=1,this.changed(),this.tileLoadFunction_(this,this.src_),this.unlisten_=function(t,e,n){const r=t;let i=!0,s=!1,o=!1;const a=[fV(r,"load",function(){o=!0,s||e()})];return r.src&&AV?(s=!0,r.decode().then(function(){i&&e()}).catch(function(){i&&(o?e():n())})):a.push(fV(r,"error",n)),function(){i=!1,a.forEach(gV)}}(this.image_,this.handleImageLoad_.bind(this),this.handleImageError_.bind(this)))}unlistenImage_(){this.unlisten_&&(this.unlisten_(),this.unlisten_=null)}disposeInternal(){this.unlistenImage_(),this.image_=null,super.disposeInternal()}}class t4{constructor(t,e,n,r){this.minX=t,this.maxX=e,this.minY=n,this.maxY=r}contains(t){return this.containsXY(t[1],t[2])}containsTileRange(t){return this.minX<=t.minX&&t.maxX<=this.maxX&&this.minY<=t.minY&&t.maxY<=this.maxY}containsXY(t,e){return this.minX<=t&&t<=this.maxX&&this.minY<=e&&e<=this.maxY}equals(t){return this.minX==t.minX&&this.minY==t.minY&&this.maxX==t.maxX&&this.maxY==t.maxY}extend(t){t.minXthis.maxX&&(this.maxX=t.maxX),t.minYthis.maxY&&(this.maxY=t.maxY)}getHeight(){return this.maxY-this.minY+1}getSize(){return[this.getWidth(),this.getHeight()]}getWidth(){return this.maxX-this.minX+1}intersects(t){return this.minX<=t.maxX&&this.maxX>=t.minX&&this.minY<=t.maxY&&this.maxY>=t.minY}}function e4(t,e,n,r,i){return void 0!==i?(i.minX=t,i.maxX=e,i.minY=n,i.maxY=r,i):new t4(t,e,n,r)}const n4=[];class r4 extends J5{constructor(t,e,n,r,i){super(t,e,{transition:0}),this.context_=null,this.executorGroups={},this.loadingSourceTiles=0,this.hitDetectionImageData={},this.replayState_={},this.sourceTiles=[],this.errorTileKeys={},this.wantedResolution,this.getSourceTiles=r.bind(void 0,this),this.removeSourceTiles_=i,this.wrappedTileCoord=n}getContext(){return this.context_||(this.context_=AK(1,1,n4)),this.context_}hasContext(){return!!this.context_}getImage(){return this.hasContext()?this.getContext().canvas:null}getReplayState(t){const e=bV(t);return e in this.replayState_||(this.replayState_[e]={dirty:!1,renderedRenderOrder:null,renderedResolution:NaN,renderedRevision:-1,renderedTileResolution:NaN,renderedTileRevision:-1,renderedTileZ:-1}),this.replayState_[e]}load(){this.getSourceTiles()}release(){this.context_&&(zK(this.context_),n4.push(this.context_.canvas),this.context_=null),this.removeSourceTiles_(this),this.sourceTiles.length=0,super.release()}}let i4=class extends J5{constructor(t,e,n,r,i,s){super(t,e,s),this.extent=null,this.format_=r,this.features_=null,this.loader_,this.projection=null,this.resolution,this.tileLoadFunction_=i,this.url_=n,this.key=n}getTileUrl(){return this.url_}getFormat(){return this.format_}getFeatures(){return this.features_}load(){0==this.state&&(this.setState(1),this.tileLoadFunction_(this,this.url_),this.loader_&&this.loader_(this.extent,this.resolution,this.projection))}onLoad(t,e){this.setFeatures(t)}onError(){this.setState(3)}setFeatures(t){this.features_=t,this.setState(2)}setLoader(t){this.loader_=t}};const s4="https://api.mapbox.com";function o4(t){return 0!==t.indexOf("mapbox://")?"":t.slice(9)}function a4(t,e,n){const r=o4(t);if(!r)return decodeURI(new URL(t,n).href);if(0!==r.indexOf("sprites/"))throw new Error(`unexpected sprites url: ${t}`);const i=r.slice(8);return`${s4}/styles/v1/${i}/sprite?access_token=${e}`}function l4(t,e){const n=o4(t);if(!n)return decodeURI(new URL(t,location.href).href);if(0!==n.indexOf("styles/"))throw new Error(`unexpected style url: ${t}`);const r=n.slice(7);return`${s4}/styles/v1/${r}?&access_token=${e}`}const c4=["a","b","c","d"];function u4(t,e,n,r){const i=new URL(t,r||location.href),s=o4(t);if(!s)return e?(i.searchParams.has(n)||i.searchParams.set(n,e),[decodeURI(i.href)]):[decodeURI(i.href)];if("mapbox.satellite"===s){const t=window.devicePixelRatio>=1.5?"@2x":"";return[`https://api.mapbox.com/v4/${s}/{z}/{x}/{y}${t}.webp?access_token=${e}`]}return c4.map(t=>`https://${t}.tiles.mapbox.com/v4/${s}/{z}/{x}/{y}.vector.pbf?access_token=${e}`)}const h4=Object.freeze({}),d4={},p4={};let f4=0;function g4(t){return t.id||(t.id=f4++),t.id}function m4(t){let e=d4[t.id];return e||(e={},d4[g4(t)]=e),e}function y4(t){return t*Math.PI/180}const v4=function(){const t=[];for(let e=78271.51696402048;t.length<=24;e/=2)t.push(e);return t}();function b4(t,e){if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,e);const n=document.createElement("canvas");return n.width=t,n.height=e,n}function w4(t,e){let n=0;const r=e.length;for(;ni).then(t=>t instanceof Response?(r&&(r.url=t.url),o(t)):(t instanceof Request||(t=new Request(t)),t.headers.get("Accept")||t.headers.set("Accept","application/json"),r&&(r.url=t.url),fetch(t).then(o).catch(s))).catch(s);return x4[e]=[i,a],a}function S4(t,e){if("string"!=typeof t)return Promise.resolve(t);if(!t.trim().startsWith("{"))return C4("Style",t=l4(t,e.accessToken),e);try{const e=JSON.parse(t);return Promise.resolve(e)}catch(v5){return Promise.reject(v5)}}const k4={};function E4(t,e,n={}){const r=[e,JSON.stringify(t)].toString();let i=k4[r];if(!i||n.transformRequest){let s;n.transformRequest&&(s=(t,e)=>{const r=n.transformRequest&&n.transformRequest(e,"Tiles")||e;if(t instanceof i4)t.setLoader((e,n,i)=>{const s=function(n){n.arrayBuffer().then(n=>{const r=t.getFormat().readFeatures(n,{extent:e,featureProjection:i});t.setFeatures(r)})};lV(()=>r).then(e=>{if(e instanceof Response)return s(e);fetch(e).then(s).catch(()=>t.setState(3))}).catch(()=>t.setState(3))});else{const e=t.getImage();lV(()=>r).then(n=>{if("string"==typeof n)return void(e.src=n);const r=t=>t.blob().then(t=>{const n=URL.createObjectURL(t);e.addEventListener("load",()=>URL.revokeObjectURL(n)),e.addEventListener("error",()=>URL.revokeObjectURL(n)),e.src=n});if(n instanceof Response)return r(n);fetch(n).then(r).catch(()=>t.setState(3))}).catch(()=>t.setState(3))}});const o=t.url;if(o&&!t.tiles){const r=u4(o,n.accessToken,n.accessTokenParam||"access_token",e||location.href);if(o.startsWith("mapbox://"))i=Promise.resolve({tileJson:Object.assign({},t,{url:void 0,tiles:r}),tileLoadFunction:s});else{const t={};i=C4("Source",r[0],n,t).then(function(e){return e.tiles=e.tiles.map(function(r){return"tms"===e.scheme&&(r=r.replace("{y}","{-y}")),u4(r,n.accessToken,n.accessTokenParam||"access_token",t.url)[0]}),Promise.resolve({tileJson:e,tileLoadFunction:s})})}}else t.tiles?(t=Object.assign({},t,{tiles:t.tiles.map(function(r){return"tms"===t.scheme&&(r=r.replace("{y}","{-y}")),u4(r,n.accessToken,n.accessTokenParam||"access_token",e||location.href)[0]})}),i=Promise.resolve({tileJson:Object.assign({},t),tileLoadFunction:s})):i=Promise.reject(new Error("source has no `tiles` nor `url`"));k4[r]=i}return i}function T4(t,e,n,r){const i=[2*n*e.pixelRatio+e.width,2*n*e.pixelRatio+e.height],s=b4(i[0],i[1]),o=s.getContext("2d");o.drawImage(t,e.x,e.y,e.width,e.height,n*e.pixelRatio,n*e.pixelRatio,e.width,e.height);const a=o.getImageData(0,0,i[0],i[1]);o.globalCompositeOperation="destination-over",o.fillStyle=`rgba(${255*r.r},${255*r.g},${255*r.b},${r.a})`;const l=a.data;for(let c=0,u=a.width;c0&&o.arc(c,t,n*e.pixelRatio,0,2*Math.PI);return o.fill(),s}function R4(t,e,n){const r=Math.max(0,Math.min(1,(n-t)/(e-t)));return r*r*(3-2*r)}function M4(t,e,n){const r=b4(e.width,e.height),i=r.getContext("2d");i.drawImage(t,e.x,e.y,e.width,e.height,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),o=s.data;for(let a=0,l=s.width;a0?(o[e+0]=Math.round(255*n.r*s),o[e+1]=Math.round(255*n.g*s),o[e+2]=Math.round(255*n.b*s),o[e+3]=Math.round(255*s)):o[e+3]=0}return i.putImageData(s,0,0),r}const L4=Array(256).join(" ");function I4(t,e){if(e>=.05){let n="";const r=t.split("\n"),i=L4.slice(0,Math.round(e/.1));for(let t=0,e=r.length;t0&&(n+="\n"),n+=r[t].split("").join(i);return n}return t}let P4;function A4(){return P4||(P4=b4(1,1).getContext("2d")),P4}function O4(t,e){return A4().measureText(t).width+(t.length-1)*e}const F4={};function z4(t,e,n,r){if(-1!==t.indexOf("\n")){const i=t.split("\n"),s=[];for(let t=0,o=i.length;t1){const t=A4();t.font=e;const i=t.measureText("M").width*n;let a="";const l=[];for(let e=0,n=o.length;e1;++e){const t=l[e];if(O4(t,r)<.35*i){const i=e>0?O4(l[e-1],r):1/0,s=e.7*i&&O4(s,r)<.6*i){const o=t.split(" "),a=o.pop();O4(a,r)<.2*i&&(l[e]=o.join(" "),l[e+1]=a+" "+s),n-=1}}s=l.join("\n")}else s=t;s=I4(s,r),F4[i]=s}return s}wJ.on("propertychange",()=>{for(const t in F4)delete F4[t]});const D4=["Arial","Courier New","Times New Roman","Verdana","sans-serif","serif","monospace","cursive","fantasy"],N4={},j4={Point:1,MultiPoint:1,LineString:2,MultiLineString:2,Polygon:3,MultiPolygon:3},B4={center:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]},U4={zoom:0,distanceFromCenter:0};let $4,q4;function V4(t,e,n,r,i,s){const o=t.id;i||(i={},console.warn("No functionCache provided to getValue()")),i[o]||(i[o]={});const a=i[o];if(!a[n]){let r=(t[e]||h4)[n];const i=W5[`${e}_${t.type}`][n];void 0===r&&(r=i.default);let s=(l=r,Array.isArray(l)&&l.length>0&&"string"==typeof l[0]&&l[0]in a5);if(!s&&b5(r)&&(r=function(t,e){let n=t.stops;if(!n)return function(t,e){const n=["get",t.property];if(void 0===t.default)return"string"===e.type?["string",n]:n;if("enum"===e.type)return["match",n,Object.keys(e.values),n,t.default];{const r=["color"===e.type?"to-color":e.type,n,D5(t.default)];return"array"===e.type&&r.splice(1,0,e.value,e.length||null),r}}(t,e);const r=n&&"object"==typeof n[0][0],i=r||void 0!==t.property,s=r||!i;return n=n.map(t=>!i&&e.tokens&&"string"==typeof t[1]?[t[0],V5(t[1])]:[t[0],D5(t[1])]),r?function(t,e,n){const r={},i={},s=[];for(let o=0;o`${t.key}: ${t.message}`).join(", "));return n.value}(r,i);a[n]=t.evaluate.bind(t)}else{const t=i.type;"color"!==t&&"colorArray"!==t||(r=c2.parse(r)),a[n]=function(){return r}}}var l;return a[n](U4,r,s)}function W4(t,e,n,r){return V4(t,"layout",`${n}-allow-overlap`,e,r)?V4(t,"layout",`${n}-ignore-placement`,e,r)?"none":"obstacle":"declutter"}function H4(t,e,n,r){if(r||console.warn("No filterCache provided to evaluateFilter()"),!(t in r))try{r[t]=M5(e).filter}catch(ej){console.warn("Filter will evaluate to false: "+ej.message),r[t]=function(){return!1}}return r[t](U4,n)}function G4(t,e){if(t){if(0===t.a||0===e)return;const n=t.a;return e=void 0===e?1:e,0===n?"transparent":"rgba("+Math.round(255*t.r/n)+","+Math.round(255*t.g/n)+","+Math.round(255*t.b/n)+","+n*e+")"}return t}l5.register(a5,{...l5.definitions,pitch:[{kind:"number"},[],()=>U4.pitch||90],"distance-from-center":[{kind:"number"},[],()=>U4.distanceFromCenter||0]});const K4=/\{[^{}}]*\}/g;function Z4(t,e){return t.replace(K4,function(t){return e[t.slice(1,-1)]||""})}function Y4(t,e){let n=t.split(":")[0];return n===t&&(n="default"),e[n]}const X4={},J4=4294967296,Q4=1/J4,t6="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class e6{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(t,e,n=this.length){for(;this.pos>3,i=this.pos;this.type=7&n,t(r,e,this),this.pos===i&&this.skip(n)}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*J4;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*J4;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let n,r;return r=e[this.pos++],n=127&r,r<128?n:(r=e[this.pos++],n|=(127&r)<<7,r<128?n:(r=e[this.pos++],n|=(127&r)<<14,r<128?n:(r=e[this.pos++],n|=(127&r)<<21,r<128?n:(r=e[this.pos],n|=(15&r)<<28,function(t,e,n){const r=n.buf;let i,s;if(s=r[n.pos++],i=(112&s)>>4,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<3,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<10,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<17,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<24,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(1&s)<<31,s<128)return n6(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(n,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&t6?t6.decode(this.buf.subarray(e,t)):function(t,e,n){let r="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+c>n)break;1===c?e<128&&(l=e):2===c?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===c?(s=t[i+1],o=t[i+2],128==(192&s)&&128==(192&o)&&(l=(15&e)<<12|(63&s)<<6|63&o,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===c&&(s=t[i+1],o=t[i+2],a=t[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(l=(15&e)<<18|(63&s)<<12|(63&o)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,c=1):l>65535&&(l-=65536,r+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),r+=String.fromCharCode(l),i+=c}return r}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const n=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else{if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8}}writeTag(t,e){this.writeVarint(t<<3|e)}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let n,r;if(t>=0?(n=t%4294967296|0,r=t/4294967296|0):(n=~(-t%4294967296),r=~(-t/4294967296),4294967295^n?n=n+1|0:(n=0,r=r+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,n){n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos]=127&t}(n,0,e),function(t,e){const n=(7&t)<<4;e.buf[e.pos++]|=n|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(r,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))}writeSVarint(t){this.writeVarint(t<0?2*-t-1:2*t)}writeBoolean(t){this.writeVarint(+t)}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,n){for(let r,i,s=0;s55295&&r<57344){if(!i){r>56319||s+1===e.length?(t[n++]=239,t[n++]=191,t[n++]=189):i=r;continue}if(r<56320){t[n++]=239,t[n++]=191,t[n++]=189,i=r;continue}r=i-55296<<10|r-56320|65536,i=null}else i&&(t[n++]=239,t[n++]=191,t[n++]=189,i=null);r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:(r<65536?t[n++]=r>>12|224:(t[n++]=r>>18|240,t[n++]=r>>12&63|128),t[n++]=r>>6&63|128),t[n++]=63&r|128)}return n}(this.buf,t,this.pos);const n=this.pos-e;n>=128&&r6(e,n,this),this.pos=e-1,this.writeVarint(n),this.pos+=n}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let n=0;n=128&&r6(n,r,this),this.pos=n-1,this.writeVarint(r),this.pos+=r}writeMessage(t,e,n){this.writeTag(t,2),this.writeRawMessage(e,n)}writePackedVarint(t,e){e.length&&this.writeMessage(t,i6,e)}writePackedSVarint(t,e){e.length&&this.writeMessage(t,s6,e)}writePackedBoolean(t,e){e.length&&this.writeMessage(t,l6,e)}writePackedFloat(t,e){e.length&&this.writeMessage(t,o6,e)}writePackedDouble(t,e){e.length&&this.writeMessage(t,a6,e)}writePackedFixed32(t,e){e.length&&this.writeMessage(t,c6,e)}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,u6,e)}writePackedFixed64(t,e){e.length&&this.writeMessage(t,h6,e)}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,d6,e)}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e)}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e)}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e)}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e)}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e)}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e)}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e)}writeStringField(t,e){this.writeTag(t,2),this.writeString(e)}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e)}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e)}writeBooleanField(t,e){this.writeVarintField(t,+e)}}function n6(t,e,n){return n?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function r6(t,e,n){const r=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));n.realloc(r);for(let i=n.pos-1;i>=t;i--)n.buf[i+r]=n.buf[i]}function i6(t,e){for(let n=0;n>3}if(o--,1===s||2===s)a+=t.readSVarint(),l+=t.readSVarint(),1===s&&c>u&&(r.push(c),u=c),n.push(a,l),c+=2;else{if(7!==s)throw new Error("Invalid command found in the PBF");c>u&&(n.push(n[u],n[u+1]),c+=2)}}c>u&&(r.push(c),u=c)}createFeature_(t,e,n){const r=e.type;if(0===r)return null;let i;const s=e.properties;let o;this.idProperty_?(o=s[this.idProperty_],delete s[this.idProperty_]):o=e.id,s[this.layerName_]=e.layer.name;const a=[],l=[];this.readRawGeometry_(t,e,a,l);const c=function(t,e){let n;return 1===t?n=1===e?"Point":"MultiPoint":2===t?n=1===e?"LineString":"MultiLineString":3===t&&(n="Polygon"),n}(r,l.length);if(this.featureClass===z0)i=new this.featureClass(c,a,l,2,s,o),i.transform(n.dataProjection);else{let t;if("Polygon"==c){const e=pK(a,l);t=e.length>1?new FQ(a,"XY",e):new fK(a,"XY",l)}else t="Point"===c?new XG(a,"XY"):"LineString"===c?new IQ(a,"XY"):"MultiPoint"===c?new AQ(a,"XY"):"MultiLineString"===c?new PQ(a,"XY",l):null;i=new(0,this.featureClass),this.geometryName_&&i.setGeometryName(this.geometryName_);const e=W0(t,!1,n);i.setGeometry(e),void 0!==o&&i.setId(o),i.setProperties(s,!0)}return i}getType(){return"arraybuffer"}readFeatures(t,e){const n=this.layers_,r=YH((e=this.adaptOptions(e)).dataProjection);r.setWorldExtent(e.extent),e.dataProjection=r;const i=new e6(t),s=i.readFields(f6,{}),o=[];for(const a in s){if(n&&!n.includes(a))continue;const t=s[a],l=t?[0,0,t.extent,t.extent]:null;r.setExtent(l);for(let n=0,r=t.length;n>3)?n.readString():2===t?n.readFloat():3===t?n.readDouble():4===t?n.readVarint64():5===t?n.readVarint():6===t?n.readSVarint():7===t?n.readBoolean():null;e.values.push(r)}}function m6(t,e,n){if(1==t)e.id=n.readVarint();else if(2==t){const t=n.readVarint()+n.pos;for(;n.pos=o.width)return null;const c=OW(s),u=Math.floor(o.height*((s[3]-r[1])/c));return u<0||u>=o.height?null:this.getImageData(o,l,u)}renderFrame(t,e){const n=this.image,r=n.getExtent(),i=n.getResolution(),[s,o]=Array.isArray(i)?i:[i,i],a=n.getPixelRatio(),l=t.layerStatesArray[t.layerIndex],c=t.pixelRatio,u=t.viewState,h=u.center,d=u.resolution,p=c*s/(d*a),f=c*o/(d*a);this.prepareContainer(t,e);const g=this.context.canvas.width,m=this.context.canvas.height,y=this.getRenderContext(t);let v=!1,b=!0;if(l.extent){const e=uG(l.extent,u.projection);b=jW(e,t.extent),v=b&&!fW(e,t.extent),v&&this.clipUnrotated(y,t,e)}const w=n.getImage(),_=wG(this.tempTransform,g/2,m/2,p,f,0,a*(r[0]-h[0])/s,a*(h[1]-r[3])/o);this.renderedResolution=o*c/a;const x=w.width*_[0],C=w.height*_[3];if(this.getLayer().getSource().getInterpolate()||(y.imageSmoothingEnabled=!1),this.preRender(y,t),b&&x>=.5&&C>=.5){const t=_[4],e=_[5],n=l.opacity;1!==n&&(y.save(),y.globalAlpha=n),y.drawImage(w,0,0,+w.width,+w.height,t,e,x,C),1!==n&&y.restore()}return this.postRender(this.context,t),v&&y.restore(),y.imageSmoothingEnabled=!0,this.container}}class b6 extends HZ{constructor(t){super(t=t||{})}}class w6 extends b6{constructor(t){super(t)}createRenderer(){return new v6(this)}getData(t){return super.getData(t)}}function _6(t){return t instanceof Image||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageBitmap?t:null}const x6=new Error("disposed"),C6=[256,256];class S6 extends J5{constructor(t){super(t.tileCoord,0,{transition:t.transition,interpolate:t.interpolate}),this.loader_=t.loader,this.data_=null,this.error_=null,this.size_=t.size||null,this.controller_=t.controller||null}getSize(){if(this.size_)return this.size_;const t=_6(this.data_);return t?[t.width,t.height]:C6}getData(){return this.data_}getError(){return this.error_}load(){if(0!==this.state&&3!==this.state)return;this.state=1,this.changed();const t=this;this.loader_().then(function(e){t.data_=e,t.state=2,t.changed()}).catch(function(e){t.error_=e,t.state=3,t.changed()})}disposeInternal(){this.controller_&&(this.controller_.abort(x6),this.controller_=null),super.disposeInternal()}}let k6;const E6=[];function T6(t,e,n,r,i){t.beginPath(),t.moveTo(0,0),t.lineTo(e,n),t.lineTo(r,i),t.closePath(),t.save(),t.clip(),t.fillRect(0,0,Math.max(e,r)+1,Math.max(n,i)),t.restore()}function R6(t,e){return Math.abs(t[4*e]-210)>2||Math.abs(t[4*e+3]-191.25)>2}function M6(t,e,n,r){const i=oG(n,e,t);let s=XH(e,r,n);const o=e.getMetersPerUnit();void 0!==o&&(s*=o);const a=t.getMetersPerUnit();void 0!==a&&(s/=a);const l=t.getExtent();if(!l||pW(l,i)){const e=XH(t,s,i)/s;isFinite(e)&&e>0&&(s/=e)}return s}function L6(t,e,n,r,i,s,o,a,l,c,u,h,d){const p=AK(Math.round(n*t),Math.round(n*e),E6);if(h||(p.imageSmoothingEnabled=!1),0===l.length)return p.canvas;function f(t){return Math.round(t*n)/n}p.scale(n,n),p.globalCompositeOperation="lighter";const g=[1/0,1/0,-1/0,-1/0];let m;l.forEach(function(t){xW(g,t.extent)});const y=n/r,v=(h?1:1+Math.pow(2,-24))/y;d&&1===l.length&&0===c||(m=AK(Math.round(NW(g)*y),Math.round(OW(g)*y),E6),h||(m.imageSmoothingEnabled=!1),l.forEach(function(t){if(t.image.width>0&&t.image.height>0){if(t.clipExtent){m.save();const e=(t.clipExtent[0]-g[0])*y,n=-(t.clipExtent[3]-g[3])*y,r=NW(t.clipExtent)*y,i=OW(t.clipExtent)*y;m.rect(h?e:Math.round(e),h?n:Math.round(n),h?r:Math.round(e+r)-Math.round(e),h?i:Math.round(n+i)-Math.round(n)),m.clip()}const e=(t.extent[0]-g[0])*y,n=-(t.extent[3]-g[3])*y,r=NW(t.extent)*y,i=OW(t.extent)*y;m.drawImage(t.image,c,c,t.image.width-2*c,t.image.height-2*c,h?e:Math.round(e),h?n:Math.round(n),h?r:Math.round(e+r)-Math.round(e),h?i:Math.round(n+i)-Math.round(n)),t.clipExtent&&m.restore()}}));const b=zW(o);return a.getTriangles().forEach(function(t){const e=t.source,n=t.target;let r=e[0][0],i=e[0][1],o=e[1][0],a=e[1][1],c=e[2][0],u=e[2][1];const d=f((n[0][0]-b[0])/s),y=f(-(n[0][1]-b[1])/s),w=f((n[1][0]-b[0])/s),_=f(-(n[1][1]-b[1])/s),x=f((n[2][0]-b[0])/s),C=f(-(n[2][1]-b[1])/s),S=r,k=i;r=0,i=0,o-=S,a-=k,c-=S,u-=k;const E=function(t){const e=t.length;for(let r=0;ri&&(i=e,n=o)}if(0===i)return null;const s=t[n];t[n]=t[r],t[r]=s;for(let o=r+1;o=0;r--){n[r]=t[r][e]/t[r][r];for(let i=r-1;i>=0;i--)t[i][e]-=t[i][r]*n[r]}return n}([[o,a,0,0,w-d],[c,u,0,0,x-d],[0,0,o,a,_-y],[0,0,c,u,C-y]]);if(!E)return;if(p.save(),p.beginPath(),function(){if(void 0===k6){const t=AK(6,6,E6);t.globalCompositeOperation="lighter",t.fillStyle="rgba(210, 0, 0, 0.75)",T6(t,4,5,4,0),T6(t,4,5,0,5);const e=t.getImageData(0,0,3,3).data;k6=R6(e,0)||R6(e,4)||R6(e,8),zK(t),E6.push(t.canvas)}return k6}()||!h){p.moveTo(w,_);const t=4,e=d-w,n=y-_;for(let r=0;rvG(o,oG(t,this.targetProj_,this.sourceProj_)),function(t,e,n,r){const i=t.length;n=void 0!==n?n:2,r=r??n,e=void 0!==e?e:new Array(i);for(let s=0;s=o?t[s+n]:i[n]}return e}):sG(this.targetProj_,this.sourceProj_);var c;this.transformInv_=function(t){const e=t[0]+"/"+t[1];return a[e]||(a[e]=l(t)),a[e]},this.maxSourceExtent_=r,this.errorThresholdSquared_=i*i,this.triangles_=[],this.wrapsXInSource_=!1,this.canWrapXInSource_=this.sourceProj_.canWrapX()&&!!r&&!!this.sourceProj_.getExtent()&&NW(r)>=NW(this.sourceProj_.getExtent()),this.sourceWorldWidth_=this.sourceProj_.getExtent()?NW(this.sourceProj_.getExtent()):null,this.targetWorldWidth_=this.targetProj_.getExtent()?NW(this.targetProj_.getExtent()):null;const u=zW(n),h=DW(n),d=MW(n),p=RW(n),f=this.transformInv_(u),g=this.transformInv_(h),m=this.transformInv_(d),y=this.transformInv_(p),v=10+(s?Math.max(0,Math.ceil(Math.log2(TW(n)/(s*s*256*256)))):0);if(this.addQuad_(u,h,d,p,f,g,m,y,v),this.wrapsXInSource_){let t=1/0;this.triangles_.forEach(function(e){t=Math.min(t,e.source[0][0],e.source[1][0],e.source[2][0])}),this.triangles_.forEach(e=>{if(Math.max(e.source[0][0],e.source[1][0],e.source[2][0])-t>this.sourceWorldWidth_/2){const n=[[e.source[0][0],e.source[0][1]],[e.source[1][0],e.source[1][1]],[e.source[2][0],e.source[2][1]]];n[0][0]-t>this.sourceWorldWidth_/2&&(n[0][0]-=this.sourceWorldWidth_),n[1][0]-t>this.sourceWorldWidth_/2&&(n[1][0]-=this.sourceWorldWidth_),n[2][0]-t>this.sourceWorldWidth_/2&&(n[2][0]-=this.sourceWorldWidth_);const r=Math.min(n[0][0],n[1][0],n[2][0]);Math.max(n[0][0],n[1][0],n[2][0])-r.5&&u<1;let p=!1;if(l>0&&(this.targetProj_.isGlobal()&&this.targetWorldWidth_&&(p=NW(cW([t,e,n,r]))/this.targetWorldWidth_>.25||p),!d&&this.sourceProj_.isGlobal()&&u&&(p=u>.25||p)),!p&&this.maxSourceExtent_&&isFinite(c[0])&&isFinite(c[1])&&isFinite(c[2])&&isFinite(c[3])&&!jW(c,this.maxSourceExtent_))return;let f=0;if(!(p||isFinite(i[0])&&isFinite(i[1])&&isFinite(s[0])&&isFinite(s[1])&&isFinite(o[0])&&isFinite(o[1])&&isFinite(a[0])&&isFinite(a[1])))if(l>0)p=!0;else if(f=(isFinite(i[0])&&isFinite(i[1])?0:8)+(isFinite(s[0])&&isFinite(s[1])?0:4)+(isFinite(o[0])&&isFinite(o[1])?0:2)+(isFinite(a[0])&&isFinite(a[1])?0:1),1!=f&&2!=f&&4!=f&&8!=f)return;if(l>0){if(!p){const e=[(t[0]+n[0])/2,(t[1]+n[1])/2],r=this.transformInv_(e);let s;s=d?(eW(i[0],h)+eW(o[0],h))/2-eW(r[0],h):(i[0]+o[0])/2-r[0];const a=(i[1]+o[1])/2-r[1];p=s*s+a*a>this.errorThresholdSquared_}if(p){if(Math.abs(t[0]-n[0])<=Math.abs(t[1]-n[1])){const c=[(e[0]+n[0])/2,(e[1]+n[1])/2],u=this.transformInv_(c),h=[(r[0]+t[0])/2,(r[1]+t[1])/2],d=this.transformInv_(h);this.addQuad_(t,e,c,h,i,s,u,d,l-1),this.addQuad_(h,c,n,r,d,u,o,a,l-1)}else{const c=[(t[0]+e[0])/2,(t[1]+e[1])/2],u=this.transformInv_(c),h=[(n[0]+r[0])/2,(n[1]+r[1])/2],d=this.transformInv_(h);this.addQuad_(t,c,h,r,i,u,d,a,l-1),this.addQuad_(c,e,n,h,u,s,o,d,l-1)}return}}if(d){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=!0}11&f||this.addTriangle_(t,n,r,i,o,a),14&f||this.addTriangle_(t,n,e,i,o,s),f&&(13&f||this.addTriangle_(e,r,t,s,a,i),7&f||this.addTriangle_(e,r,n,s,a,o))}calculateSourceExtent(){const t=[1/0,1/0,-1/0,-1/0];return this.triangles_.forEach(function(e){const n=e.source;CW(t,n[0]),CW(t,n[1]),CW(t,n[2])}),t}getTriangles(){return this.triangles_}}class P6 extends J5{constructor(t,e,n,r,i,s,o,a,l,c,u,h){super(i,0,h),this.renderEdges_=void 0!==u&&u,this.pixelRatio_=o,this.gutter_=a,this.canvas_=null,this.sourceTileGrid_=e,this.targetTileGrid_=r,this.wrappedTileCoord_=s||i,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0,this.clipExtent_=t.canWrapX()?t.getExtent():void 0;const d=r.getTileCoordExtent(this.wrappedTileCoord_),p=this.targetTileGrid_.getExtent();let f=this.sourceTileGrid_.getExtent();const g=p?FW(d,p):d;if(0===TW(g))return void(this.state=4);const m=t.getExtent();m&&(f=f?FW(f,m):m);const y=r.getResolution(this.wrappedTileCoord_[0]),v=function(t,e,n,r){const i=LW(n);let s=M6(t,e,i,r);return(!isFinite(s)||s<=0)&&EW(n,function(n){return s=M6(t,e,n,r),isFinite(s)&&s>0}),s}(t,n,g,y);if(!isFinite(v)||v<=0)return void(this.state=4);const b=void 0!==c?c:.5;if(this.triangulation_=new I6(t,n,g,f,v*b,y),0===this.triangulation_.getTriangles().length)return void(this.state=4);this.sourceZ_=e.getZForResolution(v);let w=this.triangulation_.calculateSourceExtent();if(f&&(t.canWrapX()?(w[1]=YV(w[1],f[1],f[3]),w[3]=YV(w[3],f[1],f[3])):w=FW(w,f)),TW(w)){let n=0,r=0;t.canWrapX()&&(n=NW(m),r=Math.floor((w[0]-m[0])/n)),qW(w.slice(),t,!0).forEach(t=>{const i=e.getTileRangeForExtentAndZ(t,this.sourceZ_);for(let e=i.minX;e<=i.maxX;e++)for(let t=i.minY;t<=i.maxY;t++){const i=l(this.sourceZ_,e,t,o);if(i){const t=r*n;this.sourceTiles_.push({tile:i,offset:t})}}++r}),0===this.sourceTiles_.length&&(this.state=4)}else this.state=4}getImage(){return this.canvas_}reproject_(){const t=[];if(this.sourceTiles_.forEach(e=>{const n=e.tile;if(n&&2==n.getState()){const r=this.sourceTileGrid_.getTileCoordExtent(n.tileCoord);r[0]+=e.offset,r[2]+=e.offset;const i=this.clipExtent_?.slice();i&&(i[0]+=e.offset,i[2]+=e.offset),t.push({extent:r,clipExtent:i,image:n.getImage()})}}),this.sourceTiles_.length=0,0===t.length)this.state=3;else{const e=this.wrappedTileCoord_[0],n=this.targetTileGrid_.getTileSize(e),r="number"==typeof n?n:n[0],i="number"==typeof n?n:n[1],s=this.targetTileGrid_.getResolution(e),o=this.sourceTileGrid_.getResolution(this.sourceZ_),a=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=L6(r,i,this.pixelRatio_,o,this.sourceTileGrid_.getExtent(),s,a,this.triangulation_,t,this.gutter_,this.renderEdges_,this.interpolate),this.state=2}this.changed()}load(){if(0==this.state){this.state=1,this.changed();let t=0;this.sourcesListenerKeys_=[],this.sourceTiles_.forEach(({tile:e})=>{const n=e.getState();if(0==n||1==n){t++;const n=pV(e,Vq,()=>{const r=e.getState();2!=r&&3!=r&&4!=r||(gV(n),t--,0===t&&(this.unlistenSources_(),this.reproject_()))});this.sourcesListenerKeys_.push(n)}}),0===t?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach(function({tile:t}){0==t.getState()&&t.load()})}}unlistenSources_(){this.sourcesListenerKeys_.forEach(gV),this.sourcesListenerKeys_=null}release(){this.canvas_&&(zK(this.canvas_.getContext("2d")),E6.push(this.canvas_),this.canvas_=null),super.release()}}class A6{constructor(t){this.highWaterMark=void 0!==t?t:2048,this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}deleteOldest(){const t=this.pop();t instanceof Xq&&t.dispose()}canExpireCache(){return this.highWaterMark>0&&this.getCount()>this.highWaterMark}expireCache(t){for(;this.canExpireCache();)this.deleteOldest()}clear(){for(;this.oldest_;)this.deleteOldest()}containsKey(t){return this.entries_.hasOwnProperty(t)}forEach(t){let e=this.oldest_;for(;e;)t(e.value_,e.key_,this),e=e.newer}get(t,e){const n=this.entries_[t];return WV(void 0!==n,"Tried to get a value for a key that does not exist in the cache"),n===this.newest_||(n===this.oldest_?(this.oldest_=this.oldest_.newer,this.oldest_.older=null):(n.newer.older=n.older,n.older.newer=n.newer),n.newer=null,n.older=this.newest_,this.newest_.newer=n,this.newest_=n),n.value_}remove(t){const e=this.entries_[t];return WV(void 0!==e,"Tried to get a value for a key that does not exist in the cache"),e===this.newest_?(this.newest_=e.older,this.newest_&&(this.newest_.newer=null)):e===this.oldest_?(this.oldest_=e.newer,this.oldest_&&(this.oldest_.older=null)):(e.newer.older=e.older,e.older.newer=e.newer),delete this.entries_[t],--this.count_,e.value_}getCount(){return this.count_}getKeys(){const t=new Array(this.count_);let e,n=0;for(e=this.newest_;e;e=e.older)t[n++]=e.key_;return t}getValues(){const t=new Array(this.count_);let e,n=0;for(e=this.newest_;e;e=e.older)t[n++]=e.value_;return t}peekLast(){return this.oldest_.value_}peekLastKey(){return this.oldest_.key_}peekFirstKey(){return this.newest_.key_}peek(t){return this.entries_[t]?.value_}pop(){const t=this.oldest_;return delete this.entries_[t.key_],t.newer&&(t.newer.older=null),this.oldest_=t.newer,this.oldest_||(this.newest_=null),--this.count_,t.value_}replace(t,e){this.get(t),this.entries_[t].value_=e}set(t,e){WV(!(t in this.entries_),"Tried to set a value for a key that is used already");const n={key_:t,newer:null,older:this.newest_,value_:e};this.newest_?this.newest_.newer=n:this.oldest_=n,this.newest_=n,this.entries_[t]=n,++this.count_}setSize(t){this.highWaterMark=t}}function O6(t,e,n,r){return void 0!==r?(r[0]=t,r[1]=e,r[2]=n,r):[t,e,n]}function F6(t,e,n,r,i){return`${bV(t)},${e},${function(t,e,n){return t+"/"+e+"/"+n}(n,r,i)}`}function z6(t,e,n){if(!(n in t))return t[n]=new Set([e]),!0;const r=t[n],i=r.has(e);return i||r.add(e),!i}function D6(t,e,n){const r=t[n];return!!r&&r.delete(e)}function N6(t,e){const n=t.layerStatesArray[t.layerIndex];n.extent&&(e=FW(e,uG(n.extent,t.viewState.projection)));const r=n.layer.getRenderSource();if(!r.getWrapX()){const n=r.getTileGridForProjection(t.viewState.projection).getExtent();n&&(e=FW(e,n))}return e}class j6 extends E0{constructor(t,e){super(t),e=e||{},this.extentChanged=!0,this.renderComplete=!1,this.renderedExtent_=null,this.renderedPixelRatio,this.renderedProjection=null,this.renderedTiles=[],this.renderedSourceKey_,this.renderedSourceRevision_,this.tempExtent=[1/0,1/0,-1/0,-1/0],this.tempTileRange_=new t4(0,0,0,0),this.tempTileCoord_=O6(0,0,0);const n=void 0!==e.cacheSize?e.cacheSize:512;this.tileCache_=new A6(n),this.sourceTileCache_=null,this.maxStaleKeys=.5*n}getTileCache(){return this.tileCache_}getSourceTileCache(){return this.sourceTileCache_||(this.sourceTileCache_=new A6(512)),this.sourceTileCache_}getOrCreateTile(t,e,n,r){const i=this.tileCache_,s=this.getLayer().getSource(),o=F6(s,s.getKey(),t,e,n);let a;if(i.containsKey(o))a=i.get(o);else{const l=r.viewState.projection,c=s.getProjection();if(a=s.getTile(t,e,n,r.pixelRatio,l,!c||nG(c,l)?void 0:this.getSourceTileCache()),!a)return null;i.set(o,a)}return a}getTile(t,e,n,r){return this.getOrCreateTile(t,e,n,r)||null}getData(t){const e=this.frameState;if(!e)return null;const n=this.getLayer(),r=vG(e.pixelToCoordinateTransform,t.slice()),i=n.getExtent();if(i&&!pW(i,r))return null;const s=e.viewState,o=n.getRenderSource(),a=o.getTileGridForProjection(s.projection),l=o.getTilePixelRatio(e.pixelRatio);for(let c=a.getZForResolution(s.resolution);c>=a.getMinZoom();--c){const t=a.getTileCoordForCoordAndZ(r,c),n=this.getTile(c,t[1],t[2],e);if(!n||2!==n.getState())continue;const i=a.getOrigin(c),u=AY(a.getTileSize(c)),h=a.getResolution(c);let d;if(n instanceof Q5||n instanceof P6)d=n.getImage();else{if(!(n instanceof S6))continue;if(d=_6(n.getData()),!d)continue}const p=Math.floor(l*((r[0]-i[0])/h-t[1]*u[0])),f=Math.floor(l*((i[1]-r[1])/h-t[2]*u[1])),g=Math.round(l*o.getGutterForProjection(s.projection));return this.getImageData(d,p+g,f+g)}return null}prepareFrame(t){this.renderedProjection?t.viewState.projection!==this.renderedProjection&&(this.tileCache_.clear(),this.renderedProjection=t.viewState.projection):this.renderedProjection=t.viewState.projection;const e=this.getLayer().getSource();if(!e)return!1;const n=e.getRevision();return this.renderedSourceRevision_?this.renderedSourceRevision_!==n&&(this.renderedSourceRevision_=n,this.renderedSourceKey_===e.getKey()&&(this.tileCache_.clear(),this.sourceTileCache_?.clear())):this.renderedSourceRevision_=n,!0}enqueueTilesForNextExtent(){return!0}enqueueTiles(t,e,n,r,i){const s=t.viewState,o=this.getLayer(),a=o.getRenderSource(),l=a.getTileGridForProjection(s.projection),c=bV(a);c in t.wantedTiles||(t.wantedTiles[c]={});const u=t.wantedTiles[c],h=o.getMapInternal(),d=Math.max(n-i,l.getMinZoom(),l.getZForResolution(Math.min(o.getMaxResolution(),h?h.getView().getResolutionForZoom(Math.max(o.getMinZoom(),0)):l.getResolution(0)),a.zDirection)),p=s.rotation,f=p?AW(s.center,s.resolution,p,t.size):void 0;for(let g=n;g>=d;--g){const n=l.getTileRangeForExtentAndZ(e,g,this.tempTileRange_),i=l.getResolution(g);for(let e=n.minX;e<=n.maxX;++e)for(let s=n.minY;s<=n.maxY;++s){if(p&&!l.tileCoordIntersectsViewport([g,e,s],f))continue;const n=this.getTile(g,e,s,t);if(!n)continue;if(!z6(r,n,g))continue;const o=n.getKey();if(u[o]=!0,0===n.getState()&&!t.tileQueue.isKeyQueued(o)){const r=O6(g,e,s,this.tempTileCoord_);t.tileQueue.enqueue([n,c,l.getTileCoordCenter(r),i])}}}}findStaleTile_(t,e){const n=this.tileCache_,r=t[0],i=t[1],s=t[2],o=this.getStaleKeys();for(let a=0;a0&&setTimeout(()=>{this.enqueueTiles(t,S,h-1,x,C-1)},0),!(h in x))return this.container;const k=bV(this),E=t.time;for(const A of x[h]){const e=A.getState();if(4===e)continue;const n=A.tileCoord;if(2===e&&1===A.getAlpha(k,E)){A.endTransition(k);continue}if(3!==e&&(this.renderComplete=!1),this.findStaleTile_(n,x)){D6(x,A,h),t.animate=!0;continue}if(this.findAltTiles_(u,n,h+1,x))continue;const r=u.getMinZoom();for(let t=h-1;t>=r&&!this.findAltTiles_(u,n,t,x);--t);}const T=d/s*a/g,R=this.getRenderContext(t);wG(this.tempTransform,m/2,y/2,T,T,0,-m/2,-y/2),n.extent&&this.clipUnrotated(R,t,v),c.getInterpolate()||(R.imageSmoothingEnabled=!1),this.preRender(R,t);const M=Object.keys(x).map(Number);let L;M.sort(Jq);const I=[],P=[];for(let A=M.length-1;A>=0;--A){const e=M[A],n=c.getTilePixelSize(e,a,i),r=u.getResolution(e)/d,s=n[0]*r*T,o=n[1]*r*T,l=u.getTileCoordForCoordAndZ(zW(_),e),h=u.getTileCoordExtent(l),p=vG(this.tempTransform,[g*(h[0]-_[0])/d,g*(_[3]-h[3])/d]),f=g*c.getGutterForProjection(i);for(const i of x[e]){if(2!==i.getState())continue;const n=i.tileCoord,r=l[1]-n[1],a=Math.round(p[0]-(r-1)*s),u=l[2]-n[2],h=Math.round(p[1]-(u-1)*o),d=Math.round(p[0]-r*s),g=Math.round(p[1]-u*o),m=a-d,y=h-g,v=1===M.length;let b=!1;L=[d,g,d+m,g,d+m,g+y,d,g+y];for(let t=0,i=I.length;t{const n=bV(c),r=e.wantedTiles[n],i=r?Object.keys(r).length:0;this.updateCacheSize(i),this.tileCache_.expireCache(),this.sourceTileCache_?.expireCache()};t.postRenderFunctions.push(e)}return this.container}updateCacheSize(t){this.tileCache_.highWaterMark=Math.max(this.tileCache_.highWaterMark,2*t)}drawTile(t,e,n,r,i,s,o,a){let l;if(t instanceof S6){if(l=_6(t.getData()),!l)throw new Error("Rendering array data is not yet supported")}else l=this.getTileImage(t);if(!l)return;const c=this.getRenderContext(e),u=bV(this),h=e.layerStatesArray[e.layerIndex],d=h.opacity*(a?t.getAlpha(u,e.time):1),p=d!==c.globalAlpha;p&&(c.save(),c.globalAlpha=d),c.drawImage(l,o,o,l.width-2*o,l.height-2*o,n,r,i,s),p&&c.restore(),d!==h.opacity?e.animate=!0:a&&t.endTransition(u)}getImage(){const t=this.context;return t?t.canvas:null}getTileImage(t){return t.getImage()}updateUsedTiles(t,e,n){const r=bV(e);r in t||(t[r]={}),t[r][n.getKey()]=!0}}const B6="preload",U6="useInterimTilesOnError";class $6 extends HZ{constructor(t){t=t||{};const e=Object.assign({},t),n=t.cacheSize;delete t.cacheSize,delete e.preload,delete e.useInterimTilesOnError,super(e),this.on,this.once,this.un,this.cacheSize_=n,this.setPreload(void 0!==t.preload?t.preload:0),this.setUseInterimTilesOnError(void 0===t.useInterimTilesOnError||t.useInterimTilesOnError)}getCacheSize(){return this.cacheSize_}getPreload(){return this.get(B6)}setPreload(t){this.set(B6,t)}getUseInterimTilesOnError(){return this.get(U6)}setUseInterimTilesOnError(t){this.set(U6,t)}getData(t){return super.getData(t)}}class q6 extends $6{constructor(t){super(t)}createRenderer(){return new j6(this,{cacheSize:this.getCacheSize()})}}const V6={image:["Polygon","Circle","LineString","Image","Text"],hybrid:["Polygon","LineString"],vector:[]},W6={hybrid:["Image","Text","Default"],vector:["Polygon","Circle","LineString","Image","Text","Default"]};class H6 extends j6{constructor(t,e){super(t,e),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.renderedLayerRevision_,this.renderedPixelToCoordinateTransform_=null,this.renderedRotation_,this.renderedOpacity_=1,this.tmpTransform_=[1,0,0,1,0,0],this.tileClipContexts_=null}enqueueTilesForNextExtent(){return"vector"!==this.getLayer().getRenderMode()}drawTile(t,e,n,r,i,s,o,a){this.updateExecutorGroup_(t,e.pixelRatio,e.viewState.projection),this.tileImageNeedsRender_(t)&&this.renderTileImage_(t,e),super.drawTile(t,e,n,r,i,s,o,a)}getTile(t,e,n,r){const i=this.getOrCreateTile(t,e,n,r);if(!i)return null;const s=r.viewState,o=s.resolution,a=r.viewHints,l=this.getLayer().getSource(),c=l.getTileGridForProjection(s.projection),u=!(a[0]||a[1]),h=c.getZForResolution(o,l.zDirection)===t;return u&&h?i.wantedResolution=o:i.wantedResolution||(i.wantedResolution=c.getResolution(t)),i}prepareFrame(t){const e=this.getLayer().getRevision();return this.renderedLayerRevision_!==e&&(this.renderedLayerRevision_=e,this.renderedTiles.length=0),super.prepareFrame(t)}updateExecutorGroup_(t,e,n){const r=this.getLayer(),i=r.getRevision(),s=r.getRenderOrder()||null,o=t.wantedResolution,a=t.getReplayState(r);if(!a.dirty&&a.renderedResolution===o&&a.renderedRevision==i&&a.renderedRenderOrder==s)return;const l=r.getSource(),c=!!r.getDeclutter(),u=l.getTileGrid(),h=l.getTileGridForProjection(n).getTileCoordExtent(t.wrappedTileCoord),d=l.getSourceTiles(e,n,t),p=bV(r);delete t.hitDetectionImageData[p],t.executorGroups[p]=[],a.dirty=!1;for(let f=0,g=d.length;ft.value):null;let m;t:for(let y=0,v=d.length;y{const n=this.getLayer(),r=n.getSource(),i=this.renderedProjection,s=i.getExtent(),o=this.renderedResolution,a=r.getTileGridForProjection(i),l=vG(this.renderedPixelToCoordinateTransform_,t.slice()),c=a.getTileCoordForCoordAndResolution(l,o).toString(),u=this.renderedTiles.find(t=>t.tileCoord.toString()===c&&2===t.getState());if(!u||u.loadingSourceTiles>0)return void e([]);r.getWrapX()&&i.canWrapX()&&!fW(s,a.getTileCoordExtent(u.tileCoord))&&HW(l,i);const h=bV(n),d=zW(a.getTileCoordExtent(u.wrappedTileCoord)),p=[(l[0]-d[0])/o,(d[1]-l[1])/o],f=u.getSourceTiles().reduce((t,e)=>t.concat(e.getFeatures()),[]);let g=u.hitDetectionImageData[h];if(!g){const t=AY(a.getTileSize(a.getZForResolution(o,r.zDirection))),e=this.renderedRotation_;g=g0(t,[this.getRenderTransform(a.getTileCoordCenter(u.wrappedTileCoord),o,0,f0,t[0]*f0,t[1]*f0,0)],f,n.getStyleFunction(),a.getTileCoordExtent(u.wrappedTileCoord),u.getReplayState(n).renderedResolution,e),u.hitDetectionImageData[h]=g}e(m0(p,f,g))})}getFeaturesInExtent(t){const e=[],n=this.getTileCache();if(0===n.getCount())return e;const r=this.getLayer().getSource().getTileGridForProjection(this.frameState.viewState.projection),i=r.getZForResolution(this.renderedResolution),s={};return n.forEach(n=>{if(n.tileCoord[0]!==i||2!==n.getState())return;const o=n.getSourceTiles();for(let i=0,a=o.length;i=0;--r)n[r].execute(this.context,o,this.getTileRenderTransform(e,t),t.viewState.rotation,s,c0,l)}n.globalAlpha=r}renderDeferredInternal(t){const e=this.renderedTiles,n=bV(this.getLayer()),r=e.reduce((t,e,r)=>(e.executorGroups[n].forEach(e=>t.push({executorGroup:e,index:r})),t),[]),i=r.map(({executorGroup:t})=>t.getDeferredZIndexContexts()),s={};for(let o=0,a=r.length;o{i.forEach((e,n)=>{e[t]&&(e[t].forEach(t=>{const{executorGroup:e,index:i}=r[n],s=e.getRenderedContext(),o=s.globalAlpha;s.globalAlpha=this.renderedOpacity_;const a=this.tileClipContexts_[i];a&&a.draw(s),t.draw(s),a&&s.restore(),s.globalAlpha=o,t.clear()}),e[t].length=0)})})}getTileRenderTransform(t,e){const n=e.pixelRatio,r=e.viewState,i=r.center,s=r.resolution,o=r.rotation,a=e.size,l=Math.round(a[0]*n),c=Math.round(a[1]*n),u=this.getLayer().getSource().getTileGridForProjection(e.viewState.projection),h=t.tileCoord,d=u.getTileCoordExtent(t.wrappedTileCoord),p=u.getTileCoordExtent(h,this.tempExtent)[0]-d[0];return mG(bG(this.inversePixelTransform.slice(),1/n,1/n),this.getRenderTransform(i,s,o,n,l,c,p))}postRender(t,e){const n=e.viewHints,r=!(n[0]||n[1]);this.renderedPixelToCoordinateTransform_=e.pixelToCoordinateTransform.slice(),this.renderedRotation_=e.viewState.rotation,this.renderedOpacity_=e.layerStatesArray[e.layerIndex].opacity;const i=this.getLayer(),s=i.getRenderMode(),o=t.globalAlpha;t.globalAlpha=this.renderedOpacity_;const a=i.getDeclutter(),l=a?W6[s].filter(t=>!c0.includes(t)):W6[s],c=e.viewState,u=c.rotation,h=i.getSource(),d=h.getTileGridForProjection(c.projection).getZForResolution(c.resolution,h.zDirection),p=this.renderedTiles,f=[],g=[],m=[],y=bV(i);let v=!0;for(let b=p.length-1;b>=0;--b){const n=p[b];v=v&&!n.getReplayState(i).dirty;const s=n.executorGroups[y].filter(t=>t.hasExecutors(l));if(0===s.length)continue;const o=this.getTileRenderTransform(n,e),c=n.tileCoord[0];let h=!1;const w=s[0].getClipCoords(o);let _,x=t;if(w){_=new YQ,x=_.getContext();for(let t=0,e=f.length;t{const t=this.sourceImage_.getState();2!=t&&3!=t||(this.unlistenSource_(),this.reproject_())}),this.sourceImage_.load())}}unlistenSource_(){gV(this.sourceListenerKey_),this.sourceListenerKey_=null}}class Y6 extends hV{constructor(t,e){super(t),this.image=e}}class X6 extends N0{constructor(t){super({attributions:t.attributions,projection:t.projection,state:t.state,interpolate:void 0===t.interpolate||t.interpolate}),this.on,this.once,this.un,this.loader=t.loader||null,this.resolutions_=void 0!==t.resolutions?t.resolutions:null,this.reprojectedImage_=null,this.reprojectedRevision_=0,this.image=null,this.wantedExtent_,this.wantedResolution_,this.static_=!!t.loader&&0===t.loader.length,this.wantedProjection_=null}getResolutions(){return this.resolutions_}setResolutions(t){this.resolutions_=t}findNearestResolution(t){const e=this.getResolutions();return e&&(t=e[tV(e,t,0)]),t}getImage(t,e,n,r){const i=this.getProjection();if(!i||!r||nG(i,r))return i&&(r=i),this.getImageInternal(t,e,n,r);if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&nG(this.reprojectedImage_.getProjection(),r)&&this.reprojectedImage_.getResolution()==e&&_W(this.reprojectedImage_.getExtent(),t))return this.reprojectedImage_;this.reprojectedImage_.dispose(),this.reprojectedImage_=null}return this.reprojectedImage_=new Z6(i,r,t,e,n,(t,e,n)=>this.getImageInternal(t,e,n,i),this.getInterpolate()),this.reprojectedRevision_=this.getRevision(),this.reprojectedImage_}getImageInternal(t,e,n,r){if(this.loader){const i=function(t,e,n){const r=e/n,i=LW(t),s=sW(NW(t)/r,4),o=sW(OW(t)/r,4);return PW(i,r,0,[s+2*sW(0*s/2,4),o+2*sW(0*o/2,4)])}(t,e,n),s=this.findNearestResolution(e);if(this.image&&(this.static_||this.wantedProjection_===r&&(this.wantedExtent_&&fW(this.wantedExtent_,i)||fW(this.image.getExtent(),i))&&(this.wantedResolution_&&K6(this.wantedResolution_)===s||K6(this.image.getResolution())===s)))return this.image;this.wantedProjection_=r,this.wantedExtent_=i,this.wantedResolution_=s,this.image=new iJ(i,s,n,this.loader),this.image.addEventListener(Vq,this.handleImageChange.bind(this))}return this.image}handleImageChange(t){const e=t.target;let n;switch(e.getState()){case 1:this.loading=!0,n="imageloadstart";break;case 2:this.loading=!1,n="imageloadend";break;case 3:this.loading=!1,n="imageloaderror";break;default:return}this.hasListener(n)&&this.dispatchEvent(new Y6(n,e))}}const J6=[0,0,0];class Q6{constructor(t){let e;if(this.minZoom=void 0!==t.minZoom?t.minZoom:0,this.resolutions_=t.resolutions,WV(function(t){const e=((t,e)=>e-t)||Jq;return t.every(function(n,r){if(0===r)return!0;const i=e(t[r-1],n);return!(i>0||0===i)})}(this.resolutions_),"`resolutions` must be sorted in descending order"),!t.origins)for(let r=0,i=this.resolutions_.length-1;r{const r=new t4(Math.min(0,t[0]),Math.max(t[0]-1,-1),Math.min(0,t[1]),Math.max(t[1]-1,-1));if(n){const t=this.getTileRangeForExtentAndZ(n,e);r.minX=Math.max(t.minX,r.minX),r.maxX=Math.min(t.maxX,r.maxX),r.minY=Math.max(t.minY,r.minY),r.maxY=Math.min(t.maxY,r.maxY)}return r}):n&&this.calculateTileRanges_(n)}forEachTileCoord(t,e,n){const r=this.getTileRangeForExtentAndZ(t,e);for(let i=r.minX,s=r.maxX;i<=s;++i)for(let t=r.minY,o=r.maxY;t<=o;++t)n([e,i,t])}forEachTileCoordParentTileRange(t,e,n,r){let i,s,o,a=null,l=t[0]-1;for(2===this.zoomFactor_?(s=t[1],o=t[2]):a=this.getTileCoordExtent(t,r);l>=this.minZoom;){if(void 0!==s&&void 0!==o?(s=Math.floor(s/2),o=Math.floor(o/2),i=e4(s,s,o,o,n)):i=this.getTileRangeForExtentAndZ(a,l,n),e(l,i))return!0;--l}return!1}getExtent(){return this.extent_}getMaxZoom(){return this.maxZoom}getMinZoom(){return this.minZoom}getOrigin(t){return this.origin_?this.origin_:this.origins_[t]}getResolution(t){return this.resolutions_[t]}getResolutions(){return this.resolutions_}getTileCoordChildTileRange(t,e,n){if(t[0]this.maxZoom||e0?r:Math.max(s/n[0],i/n[1]);const o=e+1,a=new Array(o);for(let l=0;ln||n>e.getMaxZoom())return!1;const s=e.getFullTileRange(n);return!s||s.containsXY(r,i)}(t,r)?t:null}clear(){}refresh(){this.clear(),super.refresh()}}class s8 extends hV{constructor(t,e){super(t),this.tile=e}}function o8(t){return function(e){const n=e.buffers,r=e.meta,i=e.imageOps,s=e.width,o=e.height,a=n.length,l=n[0].byteLength;if(i){const e=new Array(a);for(let t=0;tthis.maxQueueLength_;)this.queue_.shift().callback(null,null)}dispatch_(){if(this.running_||0===this.queue_.length)return;const t=this.queue_.shift();this.job_=t;const e=t.inputs[0].width,n=t.inputs[0].height,r=t.inputs.map(function(t){return t.data.buffer}),i=this.workers_.length;if(this.running_=i,1===i)return void this.workers_[0].postMessage({buffers:r,meta:t.meta,imageOps:this.imageOps_,width:e,height:n},r);const s=t.inputs[0].data.length,o=4*Math.ceil(s/4/i);for(let a=0;athis.getTileInternal(t,e,n,r,o,s),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_,this.tileOptions);return d.key=l,d}getTileInternal(t,e,n,r,i,s){const o=this.getKey(),a=F6(this,o,t,e,n);if(s&&s.containsKey(a))return s.get(a);const l=this.createTile_(t,e,n,r,i,o);return s?.set(a,l),l}setRenderReprojectionEdges(t){this.renderReprojectionEdges_!=t&&(this.renderReprojectionEdges_=t,this.changed())}setTileGridForProjection(t,e){const n=YH(t);if(n){const t=bV(n);t in this.tileGridForProjection||(this.tileGridForProjection[t]=e)}}}function x8(t,e){if(PV){const n=t.getCrossOrigin();let r="same-origin",i="same-origin";return"anonymous"===n||""===n?(r="cors",i="omit"):"use-credentials"===n&&(r="cors",i="include"),void fetch(e,{mode:r,credentials:i}).then(t=>{if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.blob()}).then(t=>createImageBitmap(t)).then(e=>{const n=t.getImage();n.width=e.width,n.height=e.height,n.getContext("2d").drawImage(e,0,0),e.close?.(),n.dispatchEvent(new Event("load"))}).catch(()=>{t.getImage().dispatchEvent(new Event("error"))})}t.getImage().src=e}class C8 extends _8{constructor(t){if(super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:YH("EPSG:3857"),reprojectionErrorThreshold:t.reprojectionErrorThreshold,state:"loading",tileLoadFunction:t.tileLoadFunction,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.tileJSON_=null,this.tileSize_=t.tileSize,t.url)if(t.jsonp)!function(t,e,n){const r=document.createElement("script"),i="olc_"+bV(e);function s(){delete window[i],r.parentNode.removeChild(r)}r.async=!0,r.src=t+(t.includes("?")?"&":"?")+"callback="+i;const o=setTimeout(function(){s(),n&&n()},1e4);window[i]=function(t){clearTimeout(o),s(),e(t)},document.head.appendChild(r)}(t.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const e=new XMLHttpRequest;e.addEventListener("load",this.onXHRLoad_.bind(this)),e.addEventListener("error",this.onXHRError_.bind(this)),e.open("GET",t.url),e.send()}else{if(!t.tileJSON)throw new Error("Either `url` or `tileJSON` options must be provided");this.handleTileJSONResponse(t.tileJSON)}}onXHRLoad_(t){const e=t.target;if(!e.status||e.status>=200&&e.status<300){let t;try{t=JSON.parse(e.responseText)}catch{return void this.handleTileJSONError()}this.handleTileJSONResponse(t)}else this.handleTileJSONError()}onXHRError_(t){this.handleTileJSONError()}getTileJSON(){return this.tileJSON_}handleTileJSONResponse(t){const e=YH("EPSG:4326"),n=this.getProjection();let r;if(void 0!==t.bounds){const i=rG(e,n);r=UW(t.bounds,i)}const i=r8(n),s=t.minzoom||0,o=e8({extent:i,maxZoom:t.maxzoom||22,minZoom:s,tileSize:this.tileSize_});if(this.tileGrid=o,this.tileUrlFunction=b8(t.tiles,o),t.attribution&&!this.getAttributions()){const e=void 0!==r?r:i;this.setAttributions(function(n){return jW(e,n.extent)?[t.attribution]:null})}this.tileJSON_=t,this.setState("ready")}handleTileJSONError(){this.setState("error")}}class S8 extends w8{constructor(t){const e=t.projection||"EPSG:3857",n=t.extent||r8(e),r=t.tileGrid||e8({extent:n,maxResolution:t.maxResolution,maxZoom:void 0!==t.maxZoom?t.maxZoom:22,minZoom:t.minZoom,tileSize:t.tileSize||512});super({attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,cacheSize:t.cacheSize,interpolate:!0,projection:e,state:t.state,tileGrid:r,tileLoadFunction:t.tileLoadFunction?t.tileLoadFunction:k8,tileUrlFunction:t.tileUrlFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:void 0===t.zDirection?1:t.zDirection}),this.format_=t.format?t.format:null,this.tileKeysBySourceTileUrl_={},this.sourceTiles_={},this.overlaps_=null==t.overlaps||t.overlaps,this.tileClass=t.tileClass?t.tileClass:i4,this.tileGrids_={}}getOverlaps(){return this.overlaps_}getSourceTiles(t,e,n){if(0===n.getState()){n.setState(1);const r=n.wrappedTileCoord,i=this.getTileGridForProjection(e);let s=i.getTileCoordExtent(r);const o=r[0],a=i.getResolution(o);uW(s,-a,s);const l=this.projection;e&&this.projection&&!nG(e,l)&&(s=aG(s,e,l));const c=this.tileGrid,u=c.getExtent();u&&FW(s,u,s);let h=a;e&&l&&!nG(e,l)&&(h=a/l.getMetersPerUnit()/e.getMetersPerUnit());const d=c.getZForResolution(h,this.zDirection);c.forEachTileCoord(s,d,r=>{const i=this.tileUrlFunction(r,t,e);this.sourceTiles_[i]||(this.sourceTiles_[i]=new this.tileClass(r,i?0:4,i,this.format_,this.tileLoadFunction));const s=this.sourceTiles_[i];n.sourceTiles.push(s),this.tileKeysBySourceTileUrl_[i]||(this.tileKeysBySourceTileUrl_[i]=[]),this.tileKeysBySourceTileUrl_[i].push(n.getKey());const o=s.getState();if(o<2){const t=e=>{this.handleTileChange(e);const r=s.getState();if(2===r||3===r){const e=s.getKey();e in n.errorTileKeys?2===s.getState()&&delete n.errorTileKeys[e]:n.loadingSourceTiles--,3===r?n.errorTileKeys[e]=!0:s.removeEventListener(Vq,t),0===n.loadingSourceTiles&&n.setState(uV(n.errorTileKeys)?2:3)}};s.addEventListener(Vq,t),n.loadingSourceTiles++}0===o&&(s.extent=c.getTileCoordExtent(r),s.projection=this.projection,s.resolution=c.getResolution(r[0]),s.load())}),n.loadingSourceTiles||n.setState(n.sourceTiles.some(t=>3===t.getState())?3:2)}return n.sourceTiles}removeSourceTiles(t){const e=t.getKey(),n=t.sourceTiles;for(let r=0,i=n.length;r{u=u&&!this.tileUrlFunction(t,r,l)})}const h=new r4(s,u?4:0,o,this.getSourceTiles.bind(this,r,i),this.removeSourceTiles.bind(this));return h.key=this.getKey(),h}getTileGridForProjection(t){const e=t.getCode();let n=this.tileGrids_[e];if(!n){const r=this.projection;if(null!==r&&!nG(r,t))return t8(t);const i=this.tileGrid,s=i.getResolutions().slice(),o=s.map(function(t,e){return i.getOrigin(e)}),a=s.map(function(t,e){return i.getTileSize(e)}),l=43;for(let t=s.length;td?h-A+d:d-A,P=Math.atan(Math.sqrt(L*L+I*I)),$=m*Math.cos(P)+g*Math.sin(P)*Math.cos(f-A),O=Math.cos(P),F=255*$,j=Math.min(Math.max(2*e.sunEl,0),1),B=1.875-1.75*e.opacity,U=.5!==e.opacity?d*((Math.pow(B,P)-1)/(Math.pow(B,d)-1)):P,D={r:(1-O)*b.r*j*255,g:(1-O)*b.g*j*255,b:(1-O)*b.b*j*255,a:(1-O)*b.a*j*255},z=Math.abs(((A+f)/Math.PI+.5)%2-1),N={r:(y.r*(1-z)+v.r*z)*F,g:(y.g*(1-z)+v.g*z)*F,b:(y.b*(1-z)+v.b*z)*F,a:(y.a*(1-z)+v.a*z)*F},T=4*(x*r+_),o[T]=D.r*(1-z)+N.r,o[T+1]=D.g*(1-z)+N.g,o[T+2]=D.b*(1-z)+N.b,o[T+3]=s[T+3]*e.opacity*j*Math.sin(U);return new ImageData(o,r,i)}function T8(t,e){const n=t[0],r=n.width,i=n.height,s=n.data,o=new Uint8ClampedArray(s.length),a=r-1,l=i-1,c=[0,0,0,0];let u,h,d;const p=(f=e.saturation)>0?1-1/(1.001-f):-f;var f;const g=(m=e.contrast)>0?1/(1-m):1+m;var m;const y=function(t){t*=Math.PI/180;const e=Math.sin(t),n=Math.cos(t);return[(2*n+1)/3,(-Math.sqrt(3)*e-n+1)/3,(Math.sqrt(3)*e-n+1)/3]}(e.hueRotate),v=y,b=[y[2],y[0],y[1]],w=[y[1],y[2],y[0]],_=e.brightnessLow,x=e.brightnessHigh;for(h=0;h<=l;++h)for(u=0;u<=a;++u){d=4*(h*r+u),c[0]=s[d],c[1]=s[d+1],c[2]=s[d+2],c[3]=s[d+3];const t=c[0],e=c[1],n=c[2],i=(t,e)=>{let n=0;for(let r=0;r{e.accessToken=t,e.accessTokenParam=n})),e}function L8(t,e){let n;return t.some(function(t){if(t.id==e)return n=t.source,!0}),n}function I8(t,e,n){const r=new C8({tileJSON:e,tileSize:t.tileSize||e.tileSize||512}),i=r.getTileJSON(),s=r.getTileGrid(),o=YH(n.projection||"EPSG:3857"),a=function(t,e){const n=t.bounds;if(n){const t=tG([n[0],n[1]],e),r=tG([n[2],n[3]],e);return[t[0],t[1],r[0],r[1]]}return YH(e).getExtent()}(i,o),l=o.getExtent(),c=i.minzoom||0,u=i.maxzoom||22,h={attributions:r.getAttributions(),projection:o,tileGrid:new Q6({origin:l?zW(l):s.getOrigin(0),extent:a||s.getExtent(),minZoom:c,resolutions:R8(o,e.tileSize).slice(0,u+1),tileSize:s.getTileSize(0)})};return Array.isArray(i.tiles)?h.urls=i.tiles:h.url=i.tiles,h}function P8(t,e,n){return new Promise(function(r,i){E4(t,e,n).then(function({tileJson:e,tileLoadFunction:i}){const s=I8(t,e,n);s.tileLoadFunction=i,s.format=new p6({layerName:"mvt:layer"});const o=new S8(s);o.set("mapbox-source",t),r(o)}).catch(i)})}function A8(t){return`{bbox-${(t?t.getCode():"EPSG:3857").toLowerCase().replace(/[^a-z0-9]/g,"-")}}`}function O8(t,e,n){const r=new q6;return function(t,e,n){return new Promise(function(r,i){E4(t,e,n).then(function({tileJson:e,tileLoadFunction:i}){const s=new C8({interpolate:void 0===n.interpolate||n.interpolate,transition:0,crossOrigin:"anonymous",tileJSON:e});s.tileGrid=I8(t,e,n).tileGrid,n.projection&&(s.projection=YH(n.projection));const o=s.getTileUrlFunction();i&&s.setTileLoadFunction(i),s.setTileUrlFunction(function(t,e,n){const r=A8(n);let i=o(t,e,n);if(-1!=i.indexOf(r)){const e=s.getTileGrid().getTileCoordExtent(t);i=i.replace(r,e.toString())}return i}),s.set("mapbox-source",t),r(s)}).catch(function(t){i(t)})})}(t,e,n).then(function(t){r.setSource(t)}).catch(function(){r.setSource(void 0)}),r}function F8(t,e,n){const r=n.projection?new X0({dataProjection:n.projection}):new X0,i=t.data,s={};if("string"==typeof i){const[s]=u4(i,n.accessToken,n.accessTokenParam||"access_token",e||location.href);if(/\{bbox-[0-9a-z-]+\}/.test(s)){const e=(t,e,n)=>{const r=A8(n);return s.replace(r,`${t.join(",")}`)},i=new q0({attributions:t.attribution,format:r,loader:(t,r,s,o,a)=>{C4("GeoJSON","function"==typeof e?e(t,r,s):e,n).then(t=>{const e=i.getFormat().readFeatures(t,{featureProjection:s});i.addFeatures(e),o(e)}).catch(()=>{i.removeLoadedExtent(t),a()})},strategy:P0});return i.set("mapbox-source",t),i}const o=new q0({attributions:t.attribution,format:r,url:s,loader:(t,e,r,i,a)=>{C4("GeoJSON",s,n).then(t=>{const e=o.getFormat().readFeatures(t,{featureProjection:r});o.addFeatures(e),i(e)}).catch(()=>{o.removeLoadedExtent(t),a()})}});return o}s.features=r.readFeatures(i,{featureProjection:"EPSG:3857"});const o=new q0(Object.assign({attributions:t.attribution,format:r},s));return o.set("mapbox-source",t),o}function z8(t,e,n,r){const i=m4(t),s=t.layers,o=n.type,a=n.source||L8(s,n.ref),l=t.sources[a];let c;if("background"==o)c=function(t,e,n){const r=PV?{style:{}}:document.createElement("div");return r.className="ol-mapbox-style-background",r.style.position="absolute",r.style.width="100%",r.style.height="100%",new HZ({source:new N0({}),render(i){const s=function(t,e,n,r){const i={id:t.id,type:t.type},s=t.layout||{},o=t.paint||{};let a;i.paint=o,U4.zoom=w4(e,n.resolutions||v4),U4.distanceFromCenter=0;const l=V4(i,"paint","background-color",h4,r);return void 0!==o["background-opacity"]&&(a=V4(i,"paint","background-opacity",h4,r)),"none"==s.visibility?void 0:G4(l,a)}(t,i.viewState.resolution,e,n);return r.style.backgroundColor=s,r}})}(n,r,i);else if("vector"==l.type)c=function(t,e,n){const r=new G6({declutter:!0,visible:!1});return P8(t,e,n).then(function(t){r.setSource(t)}).catch(function(){r.setSource(void 0)}),r}(l,e,r);else if("raster"==l.type){const t=["raster-saturation","raster-contrast","raster-brightness-max","raster-brightness-min","raster-hue-rotate"];Object.keys(n.paint||{}).find(e=>t.includes(e))?(c=function(t,e,n){const r=O8(t,e,n);return new w6({source:new u8({operationType:"image",operation:T8,sources:[r]})})}(l,e,r),c.getSource().on("beforeoperations",function(t){U4.zoom=w4(t.resolution,r.resolutions||v4),U4.distanceFromCenter=0;const e=t.data;e.saturation=V4(n,"paint","raster-saturation",h4,i),e.contrast=V4(n,"paint","raster-contrast",h4,i),e.brightnessHigh=V4(n,"paint","raster-brightness-max",h4,i),e.brightnessLow=V4(n,"paint","raster-brightness-min",h4,i),e.hueRotate=V4(n,"paint","raster-hue-rotate",h4,i)})):c=O8(l,e,r),c.setVisible(!n.layout||"none"!==n.layout.visibility),c.on("prerender",function(t,e,n){let r=null;return function(i){t.paint&&"raster-opacity"in t.paint&&i.frameState.viewState.zoom!==r&&(r=i.frameState.viewState.zoom,delete n[t.id],function(t,e,n,r){U4.zoom=n,U4.distanceFromCenter=0;const i=V4(t,"paint","raster-opacity",h4,r);e.setOpacity(i)}(t,e,r,n))}}(n,c,i))}else if("geojson"==l.type)c=function(t,e,n){return new R0({declutter:!0,source:F8(t,e,n),visible:!1})}(l,e,r);else if("raster-dem"==l.type&&"hillshade"==n.type){const t=function(t,e,n){const r=O8(t,e,n);return new w6({source:new u8({operationType:"image",operation:E8,sources:[r]})})}(l,e,r);c=t,t.getSource().on("beforeoperations",function(t){const e=t.data;e.resolution=XH(r.projection||"EPSG:3857",t.resolution,LW(t.extent),"m"),U4.zoom=w4(t.resolution,r.resolutions||v4),U4.distanceFromCenter=0,e.encoding=l.encoding,e.vert=5*V4(n,"paint","hillshade-exaggeration",h4,i),e.sunAz=V4(n,"paint","hillshade-illumination-direction",h4,i),e.sunEl=35,e.opacity=.3,e.highlightColor=V4(n,"paint","hillshade-highlight-color",h4,i),e.shadowColor=V4(n,"paint","hillshade-shadow-color",h4,i),e.accentColor=V4(n,"paint","hillshade-accent-color",h4,i)}),c.setVisible(!n.layout||"none"!==n.layout.visibility)}const u=a;return c&&c.set("mapbox-source",u),c}function D8(t,e,n,r,i,s={}){let o=24,a=0;const l=n.layers;for(let c=0,u=l.length;c0||n>0)&&t.setMaxResolution(Math.min(_4(Math.max(0,o-1e-12),v4),_4(Math.max(0,n-1e-12),e.getResolutions()))),a<24&&t.setMinResolution(_4(a,v4))}}else o>0&&t.setMaxResolution(_4(Math.max(0,o-1e-12),v4));u instanceof q0||u instanceof S8?function(t,e,n="",r={},i){let s,o,a,l,c=!0;return"string"==typeof n||Array.isArray(n)?l=n:(a=n,l=a.source||a.layers,r=a),"string"==typeof r?(s=r,a={}):(s=r.styleUrl,a=r),!1===a.updateSource&&(c=!1),i||(i=a.resolutions),s||"string"!=typeof e||e.trim().startsWith("{")||(s=e),s&&(s=s.startsWith("data:")?location.href:l4(s,a.accessToken),a=M8(s,a)),new Promise(function(n,r){S4(e,a).then(function(e){if(8!=e.version)return r(new Error("glStyle version 8 required."));if(!(t instanceof R0||t instanceof G6))return r(new Error("Can only apply to VectorLayer or VectorTileLayer"));const u=t instanceof G6?"vector":"geojson";if(l?o=Array.isArray(l)?e.layers.find(function(t){return t.id===l[0]}).source:l:(o=e.layers.find(function(t){return t.source&&e.sources[t.source].type===u}).source,l=o),!o)return r(new Error(`No ${u} source found in the glStyle.`));function h(){if(!c)return Promise.resolve();if(t instanceof G6)return P8(e.sources[o],s,a).then(function(e){const n=t.getSource();n?e!==n&&(n.setTileUrlFunction(e.getTileUrlFunction()),"function"==typeof n.setUrls&&"function"==typeof e.getUrls&&n.setUrls(e.getUrls()),n.format_||(n.format_=e.format_),n.getAttributions()||n.setAttributions(e.getAttributions()),n.getTileLoadFunction()===k8&&n.setTileLoadFunction(e.getTileLoadFunction()),nG(n.getProjection(),e.getProjection())&&(n.tileGrid=e.getTileGrid())):t.setSource(e);const r=t.getSource().getTileGrid();!isFinite(t.getMaxResolution())&&!isFinite(t.getMinZoom())&&r.getMinZoom()>0&&t.setMaxResolution(_4(Math.max(0,r.getMinZoom()-1e-12),r.getResolutions()))});const n=e.sources[o];let r=t.getSource();r&&r.get("mapbox-source")===n||(r=F8(n,s,a));const i=t.getSource();return i?r!==i&&(i.getAttributions()||i.setAttributions(r.getAttributions()),i.format_||(i.format_=r.getFormat()),i.url_=r.getUrl()):t.setSource(r),Promise.resolve()}let d,p;const f={},g={};function m(){if(p||e.sprite&&!f)p?(t.setStyle(p),h().then(n).catch(r)):r(new Error("Something went wrong trying to apply style."));else{if(a.projection&&!i){const t=YH(a.projection).getUnits();"m"!==t&&(i=v4.map(e=>e/eH[t]))}let s;const c=t.getSource();c instanceof S8&&c.format_ instanceof p6&&(s=c.format_.layerName_),p=function(t,e,n,r=v4,i,s,o,a){if("string"==typeof e&&(e=JSON.parse(e)),8!=e.version)throw new Error("glStyle version 8 required.");X4[function(t,e){return g4(t)+"."+bV(e)}(e,t)]=Array.from(arguments);const l={};("string"==typeof s||s instanceof Request||s instanceof Response||s instanceof Promise)&&(s={default:s});for(const _ in s){const e=s[_];lV(()=>e).then(async e=>{let n;if("undefined"!=typeof Image){const r=new Image;if("string"==typeof e)r.crossOrigin="anonymous",r.src=e;else{let t;e instanceof Request?t=await fetch(e):e instanceof Response&&(t=e);const i=await t.blob();n=URL.createObjectURL(i),r.src=n}r.addEventListener("load",function e(){r.removeEventListener("load",e),l[_]={image:r,size:[r.width,r.height]},t.changed(),n&&URL.revokeObjectURL(n)}),r.addEventListener("error",function t(){URL.revokeObjectURL(n),r.removeEventListener("error",t)})}else if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){const t=self;t.postMessage({action:"loadImage",src:e}),t.addEventListener("message",function(t){"imageLoaded"===t.data.action&&t.data.src===e&&(l[_]={image:t.data.image,size:[t.data.image.width,t.data.image.height]})})}})}const c=f1(e.layers),u={},h=[],d={},p={},f=m4(e),g=function(t){let e=p4[t.id];return e||(e={},p4[g4(t)]=e),e}(e);let m;for(let _=0,x=c.length;_=h.maxzoom)continue;const E=h.filter;if(!E||H4(x,E,T,g)){let r,c,g,w,_,x;const E=u.index;if(3==C&&("fill"==h.type||"fill-extrusion"==h.type))if(c=V4(h,"paint",h.type+"-opacity",T,f,R),h.type+"-pattern"in k){const t=V4(h,"paint",h.type+"-pattern",T,f,R);if(t){const e="string"==typeof t?Z4(t,m):t.toString(),n=Y4(e,l);if(i&&i[e]&&n){++M,x=b[M],x&&x.getFill()&&!x.getStroke()&&!x.getText()||(x=new NJ({fill:new OJ}),b[M]=x),g=x.getFill(),x.setZIndex(E);const t=e+"."+c;let r=p[t];if(!r){const s=i[e],o=b4(s.width,s.height),a=o.getContext("2d");a.globalAlpha=c,a.drawImage(n.image,s.x,s.y,s.width,s.height,0,0,s.width,s.height),r=a.createPattern(o,"repeat"),p[t]=r}g.setColor(r)}}}else r=G4(V4(h,"paint",h.type+"-color",T,f,R),c),h.type+"-outline-color"in k&&(_=G4(V4(h,"paint",h.type+"-outline-color",T,f,R),c)),_||(_=r),(r||_)&&(++M,x=b[M],(!x||r&&!x.getFill()||!r&&x.getFill()||_&&!x.getStroke()||!_&&x.getStroke()||x.getText())&&(x=new NJ({fill:r?new OJ:void 0,stroke:_?new DJ:void 0}),b[M]=x),r&&(g=x.getFill(),g.setColor(r)),_&&(w=x.getStroke(),w.setColor(_),w.setWidth(.5)),x.setZIndex(E));if(1!=C&&"line"==h.type){r="line-pattern"in k?void 0:G4(V4(h,"paint","line-color",T,f,R),V4(h,"paint","line-opacity",T,f,R));const t=V4(h,"paint","line-width",T,f,R);r&&t>0&&(++M,x=b[M],x&&x.getStroke()&&!x.getFill()&&!x.getText()||(x=new NJ({stroke:new DJ}),b[M]=x),w=x.getStroke(),w.setLineCap(V4(h,"layout","line-cap",T,f,R)),w.setLineJoin(V4(h,"layout","line-join",T,f,R)),w.setMiterLimit(V4(h,"layout","line-miter-limit",T,f,R)),w.setColor(r),w.setWidth(t),w.setLineDash(k["line-dasharray"]?V4(h,"paint","line-dasharray",T,f,R).map(function(e){return e*t}):null),x.setZIndex(E))}let L,I,P,A,O,F,z,D,N,j=!1,B=null,U=0;if((1==C||2==C)&&"icon-image"in S){const e=V4(h,"layout","icon-image",T,f,R);if(e){let r;L="string"==typeof e?Z4(e,m):e.toString();const o=a?a(t,L):void 0,c=Y4(L,l);if(i&&i[L]&&c||o){const t=V4(h,"layout","icon-rotation-alignment",T,f,R);if(2==C){const e=n.getGeometry();if(e.getFlatMidpoint||e.getFlatMidpoints){const n=e.getExtent();if(Math.sqrt(Math.max(Math.pow((n[2]-n[0])/s,2),Math.pow((n[3]-n[1])/s,2)))>150){const n="MultiLineString"===e.getType()?e.getFlatMidpoints():e.getFlatMidpoint();if(q4||($4=[NaN,NaN],q4=new z0("Point",$4,[],2,{},void 0)),r=q4,$4[0]=n[0],$4[1]=n[1],"line"===V4(h,"layout","symbol-placement",T,f,R)&&"map"===t){const t=e.getStride(),r=e.getFlatCoordinates();for(let e=0,i=r.length-t;e=l){U=Math.atan2(s-a,o-i);break}}}}}}if(2!==C||r){const e=V4(h,"layout","icon-size",T,f,R),n=void 0!==k["icon-color"]?V4(h,"paint","icon-color",T,f,R):null;if(!n||0!==n.a){const r=V4(h,"paint","icon-halo-color",T,f,R),s=V4(h,"paint","icon-halo-width",T,f,R);let a=`${L}.${e}.${s}.${r}`;if(null!==n&&(a+=`.${n}`),I=d[a],!I){const l=W4(h,T,"icon",f);let u;"icon-offset"in S&&(u=V4(h,"layout","icon-offset",T,f,R).slice(0),u[0]*=e,u[1]*=-e);let p=n?[255*n.r,255*n.g,255*n.b,n.a]:void 0;if(o){const n={color:p,rotateWithView:"map"===t,displacement:u,declutterMode:l,scale:e};"string"==typeof o?n.src=o:(n.img=o,n.imgSize=[o.width,o.height]),I=new zJ(n)}else{const o=i[L];let a,h,d;if(s)o.sdf?(a=T4(M4(c.image,o,n||[0,0,0,1]),{x:0,y:0,width:o.width,height:o.height,pixelRatio:o.pixelRatio},s,r),p=void 0):a=T4(c.image,o,s,r);else{if(o.sdf&&!c.unSDFed){const t=M4(c.image,{x:0,y:0,width:c.size[0],height:c.size[1]},{r:1,g:1,b:1});c.image=t,c.unSDFed=!0}a=c.image,h=[o.width,o.height],d=[o.x,o.y]}I=new zJ({color:p,img:a,imgSize:c.size,size:h,offset:d,rotateWithView:"map"===t,scale:e/o.pixelRatio,displacement:u,declutterMode:l})}d[a]=I}}I&&(++M,x=b[M],x&&x.getImage()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x),x.setGeometry(r),I.setRotation(U+y4(V4(h,"layout","icon-rotate",T,f,R))),I.setOpacity(V4(h,"paint","icon-opacity",T,f,R)),I.setAnchor(B4[V4(h,"layout","icon-anchor",T,f,R)]),x.setImage(I),B=x.getText(),x.setText(void 0),x.setZIndex(E),j=!0,P=!1)}else P=!0}}}if(1==C&&"circle"===h.type){++M,x=b[M],x&&x.getImage()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x);const t="circle-radius"in k?V4(h,"paint","circle-radius",T,f,R):5,e=G4(V4(h,"paint","circle-stroke-color",T,f,R),V4(h,"paint","circle-stroke-opacity",T,f,R)),n=V4(h,"paint","circle-translate",T,f,R),r=G4(V4(h,"paint","circle-color",T,f,R),V4(h,"paint","circle-opacity",T,f,R)),i=V4(h,"paint","circle-stroke-width",T,f,R),s=t+"."+e+"."+r+"."+i+"."+n[0]+"."+n[1];I=d[s],I||(I=new AJ({radius:t,displacement:[n[0],-n[1]],stroke:e&&i>0?new DJ({width:i,color:e}):void 0,fill:r?new OJ({color:r}):void 0,declutterMode:"none"}),d[s]=I),x.setImage(I),B=x.getText(),x.setText(void 0),x.setGeometry(void 0),x.setZIndex(E),j=!0}if("text-field"in S){z=Math.round(V4(h,"layout","text-size",T,f,R));const t=V4(h,"layout","text-font",T,f,R);F=V4(h,"layout","text-line-height",T,f,R),O=Y5(o?o(t,e.metadata?e.metadata["ol:webfonts"]:void 0):t,z,F),O.includes("sans-serif")||(O+=",sans-serif"),D=V4(h,"layout","text-letter-spacing",T,f,R),N=V4(h,"layout","text-max-width",T,f,R);const n=V4(h,"layout","text-field",T,f,R);A="object"==typeof n&&n.sections?1===n.sections.length?n.toString():n.sections.reduce((e,n)=>{const r=n.fontStack?n.fontStack.split(","):t,i=Y5(o?o(r):r,z*(n.scale||1),F);let s=n.text;if("\n"===s)return e.push("\n",""),e;if(2==C)return e.push(I4(s,D),i),e;s=z4(s,i,N,D).split("\n");for(let t=0,o=s.length;t0&&e.push("\n",""),e.push(s[t],i);return e},[]):Z4(n,m).trim(),c=V4(h,"paint","text-opacity",T,f,R)}if(A&&c&&!P){j||(++M,x=b[M],x&&x.getText()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x),x.setImage(void 0),x.setGeometry(void 0));const t=W4(h,T,"text",f);x.getText()||x.setText(B),B=x.getText(),(!B||"getDeclutterMode"in B&&B.getDeclutterMode()!==t)&&(B=new $J({padding:[2,2,2,2],declutterMode:t}),x.setText(B));const e=V4(h,"layout","text-transform",T,f,R);"uppercase"==e?A=Array.isArray(A)?A.map((t,e)=>e%2?t:t.toUpperCase()):A.toUpperCase():"lowercase"==e&&(A=Array.isArray(A)?A.map((t,e)=>e%2?t:t.toLowerCase()):A.toLowerCase());const n=Array.isArray(A)?A:2==C?I4(A,D):z4(A,O,N,D);if(B.setText(n),B.setFont(O),B.setRotation(y4(V4(h,"layout","text-rotate",T,f,R))),"function"==typeof B.setKeepUpright){const t=V4(h,"layout","text-keep-upright",T,f,R);B.setKeepUpright(t)}const r=V4(h,"layout","text-anchor",T,f,R),i=j||1==C?"point":V4(h,"layout","symbol-placement",T,f,R);let s;if("line-center"===i?(B.setPlacement("line"),s="center"):B.setPlacement(i),"line"===i&&"function"==typeof B.setRepeat){const t=V4(h,"layout","symbol-spacing",T,f,R);B.setRepeat(2*t)}B.setOverflow("point"===i);let o=V4(h,"paint","text-halo-width",T,f,R);const a=V4(h,"layout","text-offset",T,f,R),l=V4(h,"paint","text-translate",T,f,R);let u=0,d=0;if("point"==i){s="center",-1!==r.indexOf("left")?(s="left",d=o):-1!==r.indexOf("right")&&(s="right",d=-o);const t=V4(h,"layout","text-rotation-alignment",T,f,R);B.setRotateWithView("map"==t)}else B.setMaxAngle(y4(V4(h,"layout","text-max-angle",T,f,R))*A.length/n.length),B.setRotateWithView(!1);B.setTextAlign(s);let p="middle";0==r.indexOf("bottom")?(p="bottom",u=-o-.5*(F-1)*z):0==r.indexOf("top")&&(p="top",u=o+.5*(F-1)*z),B.setTextBaseline(p);const g=V4(h,"layout","text-justify",T,f,R);B.setJustify("auto"===g?void 0:g),B.setOffsetX(a[0]*z+d+l[0]),B.setOffsetY(a[1]*z+u+l[1]),v.setColor(G4(V4(h,"paint","text-color",T,f,R),c)),B.setFill(v);const m=G4(V4(h,"paint","text-halo-color",T,f,R),c);if(m&&o>0){y.setColor(m),o*=2;const t=.5*z;y.setWidth(o<=t?o:t),B.setStroke(y)}else B.setStroke(void 0);const w=V4(h,"layout","text-padding",T,f,R),_=B.getPadding();w!==_[0]&&(_[0]=w,_[1]=w,_[2]=w,_[3]=w),x.setZIndex(E)}}}return M>-1?(b.length=M+1,b):void 0};return t.setStyle(w),t.set("mapbox-layers",h),t.set("mapbox-source",m),t.set("mapbox-featurestate",t.get("mapbox-featurestate")||{}),w}(t,e,l,i,f,g,(t,e=a.webfonts)=>function(t,e="https://cdn.jsdelivr.net/npm/@fontsource/{font-family}/{fontweight}{-fontstyle}.css"){if(PV)return t;let n;for(let r=0,i=t.length;r{await document.fonts.ready;for(let t=0,r=n.length;tt.family.replace(/^['"]|['"]$/g,"").toLowerCase()===i.toLowerCase()&&t.weight==s&&t.style===o)){const t=e.replace("{font-family}",i.replace(/ /g,"-").toLowerCase()).replace("{Font+Family}",i.replace(/ /g,"+")).replace("{fontweight}",s).replace("{-fontstyle}",o.replace("normal","").replace(/(.+)/,"-$1")).replace("{fontstyle}",o);if(!document.querySelector('link[href="'+t+'"]')){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}}}})(),t):t}(t,e),a.getImage,s),t.getStyle()?h().then(n).catch(r):r(new Error(`Nothing to show for source [${o}]`))}}if(e.sprite){const t=function(t,e,n){if("string"==typeof t)return[{id:"default",url:a4(t,e,n)}];for(const r of t)r.url=a4(r.url,e,n);return t}(e.sprite,a.accessToken,s||location.href);d=PV?1:window.devicePixelRatio>=1.5?.5:1;const n=.5==d?"@2x":"";Promise.all(t.map(function(t){const e=new URL(t.url);let i=e.origin+e.pathname+n+".json"+e.search;return new Promise(function(t,n){C4("Sprite",i,a).then(t).catch(function(){i=e.origin+e.pathname+".json"+e.search,C4("Sprite",i,a).then(t).catch(n)})}).then(function(i){let s;if(void 0===i&&r(new Error("No sprites found.")),s=e.origin+e.pathname+n+".png"+e.search,a.transformRequest){const t=a.transformRequest(s,"SpriteImage")||s;(t instanceof Request||t instanceof Promise)&&(s=t)}g[t.id]=s;for(const e in i){const n="default"==t.id?e:`${t.id}:${e}`;f[n]=i[e]}}).catch(function(t){r(new Error(`Sprites cannot be loaded: ${i}: ${t.message}`))})})).then(m).catch(r)}else m()}).catch(r)})}(t,n,e,Object.assign({styleUrl:r},s)).then(function(){!function(t,e){function n(){const n=e.get("mapbox-style");if(!n)return;const r=f1(n.layers),i=t.get("mapbox-layers"),s=r.filter(function(t){return i.includes(t.id)}).some(function(t){return!t.layout||!t.layout.visibility||"visible"===t.layout.visibility});t.get("visible")!==s&&t.setVisible(s)}t.on("change",n),n()}(t,i),l()}).catch(c):l()}else c(new Error("Error accessing data for source "+t.get("mapbox-source")))};t.set("mapbox-layers",e);const h=i.getLayers();-1===h.getArray().indexOf(t)&&h.push(t),t.getSource()?u():t.once("change:source",u)})}class N8 extends LB{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");mapInstance;bookmarkSource;searchResultsSource;selectedShapeSource;searchOverlay;searchOverlayElement;selectedPinOverlay;selectedPinElement;crosshairElement;crosshairOverlay;ignoreNextMapClick=!1;setupMap=UB(t=>{if(this.mapInstance)return;const e=new UZ;this.selectedShapeSource=new q0;const n=new R0({source:this.selectedShapeSource,style:new NJ({stroke:new DJ({color:"#3388ff",width:4}),fill:new OJ({color:"rgba(51, 136, 255, 0.1)"})}),zIndex:5});this.bookmarkSource=new q0;const r=new R0({source:this.bookmarkSource,style:t=>{const e=t.get("originalPlace");let n=getComputedStyle(document.documentElement).getPropertyValue("--default-list-color").trim()||"#000000";if(e&&e._listIds&&e._listIds.length>0){const t=e._listIds[0],r=this.storage.lists.find(e=>e.id===t);r&&r.color&&(n=r.color)}return[new NJ({image:new AJ({radius:10,fill:new OJ({color:"rgba(0, 0, 0, 0.2)"}),displacement:[0,-2]})}),new NJ({image:new AJ({radius:9,fill:new OJ({color:n}),stroke:new DJ({color:"#fff",width:2})})})]},zIndex:10});this.searchResultsSource=new q0;const i=new Map,s=new R0({source:this.searchResultsSource,style:t=>{const e=t.get("originalPlace"),n=this.mapUi.selectedPlace;if(n){const t=e.osmId&&n.osmId&&e.osmId===n.osmId,r=e.id&&n.id&&e.id===n.id,i=e.lat===n.lat&&e.lon===n.lon;if(t||r||i)return new NJ({})}const r=Gj(e.osmTags||e),s=r||"default";if(!i.has(s)){const t=getComputedStyle(document.documentElement).getPropertyValue("--marker-color-primary").trim()||"#ea4335";let e=``;if(r){const n=qj(r);if(n){let r=n.trim();const i=r.indexOf("",i)+1,o=r.lastIndexOf("");-1!==i&&-1!==o&&(r=r.substring(s,o)),e=`\n \n \n ${r}\n \n `}}const n=`\n \n \n \n \n \n \n \n ${e}\n \n `;i.set(s,"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(n.trim()))}return new NJ({image:new zJ({src:i.get(s),anchor:[.5,.65],scale:1})})},zIndex:11});let o=[14.21683569,27.060114248],a=2.661,l=!1;try{const t=localStorage.getItem("marco:map-view");if(t){const e=JSON.parse(t);e.center&&Array.isArray(e.center)&&2===e.center.length&&"number"==typeof e.zoom&&(o=e.center,a=e.zoom,l=!0)}}catch(ej){console.warn("Failed to restore map view:",ej)}const c=new _K({center:tG(o),zoom:a,projection:"EPSG:3857"});this.mapInstance=new wQ({target:t,layers:[e,n,s,r],view:c,controls:GK({zoom:!0,rotate:!0,attribution:!0}),interactions:EZ({dragPan:!1})});const u=eG(c.getCenter());this.mapUi.updateCenter(u[1],u[0]),function(t,e,n={}){let r,i;if(PV){if(!(t instanceof wQ||t instanceof UZ))throw new Error("ol-mapbox-style in a web worker requires a Map or a LayerGroup as first argument");i=t}else i="string"==typeof t||t instanceof HTMLElement?new wQ({target:t}):t;{const t=e.startsWith("data:")?location.href:l4(e,n.accessToken);n=M8(t,n),r=new Promise(function(r,s){S4(e,n).then(function(e){(function(t,e,n,r){const i=[];let s=null;if(e instanceof wQ){if(s=e.getView(),!s.isDef()&&!s.getRotation()&&!s.getResolutions()){const t=r.projection?YH(r.projection):s.getProjection();s=new _K(Object.assign(s.getProperties(),{maxResolution:v4[0]/eH[t.getUnits()],projection:r.projection||s.getProjection()})),e.setView(s)}"center"in t&&!s.getCenter()&&s.setCenter(tG(t.center,s.getProjection())),"zoom"in t&&void 0===s.getZoom()&&s.setResolution(v4[0]/eH[s.getProjection().getUnits()]/Math.pow(2,t.zoom)),s.getCenter()&&void 0!==s.getZoom()||s.fit(s.getProjection().getExtent(),{nearest:!0,size:e.getSize()})}e.set("mapbox-style",t),e.set("mapbox-metadata",{styleUrl:n,options:r});const o=t.layers;let a,l,c,u=[];for(let h=0,d=o.length;h';const d=document.createElement("div");d.className="selected-pin-shadow",this.selectedPinElement.appendChild(h),this.selectedPinElement.appendChild(d),this.selectedPinOverlay=new EQ({element:this.selectedPinElement,positioning:"bottom-center",stopEvent:!1}),this.mapInstance.addOverlay(this.selectedPinOverlay),this.crosshairElement=document.createElement("div"),this.crosshairElement.className="map-crosshair",this.crosshairElement.innerHTML='\n \n \n \n \n ',t.appendChild(this.crosshairElement),this.locationOverlayElement=document.createElement("div"),this.locationOverlayElement.className="search-pulse blue",this.locationOverlay=new EQ({element:this.locationOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.locationOverlay),t.addEventListener("pointerdown",()=>{this.mapUi.searchBoxHasFocus&&(this.ignoreNextMapClick=!0)},!0);const p=new h1({trackingOptions:{enableHighAccuracy:!0},projection:c.getProjection()}),f=new TQ;f.setStyle(new NJ({image:new AJ({radius:6,fill:new OJ({color:"#3399CC"}),stroke:new DJ({color:"#fff",width:2})})}));const g=new q0({features:[f]}),m=new R0({source:g,zIndex:15});p.on("change:position",function(){const t=p.getPosition();f.setGeometry(t?new XG(t):null)});const y=document.createElement("div");y.className="ol-control ol-locate";const v=document.createElement("button");let b,w;v.style.display="flex",v.style.alignItems="center",v.style.justifyContent="center",v.innerHTML=`${qj("navigation")}`,v.title="Locate Me",y.appendChild(v);const _=()=>{b&&(clearTimeout(b),b=null);try{w&&(p.un("change:position",x),w=null)}catch{}this.locationOverlayElement&&this.locationOverlayElement.classList.remove("active")},x=()=>{const t=p.getPosition(),e=p.getAccuracyGeometry(),n=p.getAccuracy();if(console.debug("Geolocation change:",{coordinates:t,accuracy:n}),!t)return;const r=this.mapInstance.getSize(),i=this.mapInstance.getView();let s=null;if(this.locationOverlayElement){const e=i.getResolution(),r=2*(n||50)/XH(i.getProjection(),e,t);this.locationOverlayElement.style.width=`${r}px`,this.locationOverlayElement.style.height=`${r}px`,this.locationOverlay.setPosition(t)}if(n&&n<=20&&_(),e){const t=e.getExtent();s=3.162*i.getResolutionForExtent(t,r)}else n&&(s=6.325*n/Math.min(r[0],r[1])/XH(i.getProjection(),1,t));let o={center:t,duration:1e3};if(s){const t=i.getResolutionForZoom(17);o.resolution=Math.max(s,t)}else o.zoom=16;this.mapInstance.getView().animate(o)},C=()=>{console.debug("Getting current geolocation..."),_(),p.setTracking(!0);const t=p.getPosition();this.locationOverlayElement&&this.locationOverlayElement.classList.add("active"),t&&x(),w=p.on("change:position",x),b=setTimeout(()=>{_()},1e4)};v.addEventListener("click",C);const S=new qK({element:y});this.mapInstance.addLayer(m),this.mapInstance.addControl(S),l||"index"!==this.router.currentRouteName||C(),this.mapInstance.on("singleclick",this.handleMapClick),this.mapInstance.on("moveend",this.handleMapMove),this.mapInstance.on("pointermove",t=>{const e=this.mapInstance.getEventPixel(t.originalEvent),n=this.mapInstance.hasFeatureAtPixel(e,{hitTolerance:10});this.mapInstance.getTarget().style.cursor=n?"pointer":""}),this.storage.rs.on("ready",()=>{this.handleMapMove()})});updateInteractions=UB(()=>{if(!this.mapInstance)return;this.mapInstance.getInteractions().getArray().slice().forEach(t=>{t instanceof hZ&&this.mapInstance.removeInteraction(t)});const t=!!this.settings.mapKinetic&&new KK(-.005,.05,100);this.settings.mapKinetic&&window.innerWidth<=768&&(t.minVelocity_=.25),this.mapInstance.addInteraction(new hZ({kinetic:t}))});updateSearchResults=UB(()=>{if(!this.searchResultsSource)return;this.searchResultsSource.clear();const t=this.mapUi.searchResults;if(!t||0===t.length)return;const e=[];t.forEach(t=>{if(t.lat&&t.lon){const n=new TQ({geometry:new XG(tG([t.lon,t.lat])),name:t.title,id:t.id,isSearchResult:!0,originalPlace:t});e.push(n)}}),e.length>0&&this.searchResultsSource.addFeatures(e)});updateSelectedPin=UB(()=>{const t=this.mapUi.selectedPlace,e=this.mapUi.selectionOptions||{};if(this.searchResultsSource&&this.searchResultsSource.changed(),this.selectedPinOverlay&&this.selectedPinElement)if(this.selectedShapeSource&&this.selectedShapeSource.clear(),t&&t.lat&&t.lon){const n=tG([t.lon,t.lat]);if(this.selectedPinOverlay.setPosition(n),this.selectedPinElement.classList.remove("active"),this.selectedPinElement.offsetWidth,this.selectedPinElement.classList.add("active"),t.geojson&&this.selectedShapeSource)try{const e=(new X0).readFeature(t.geojson,{featureProjection:"EPSG:3857"});this.selectedShapeSource.addFeature(e)}catch(ej){console.warn("Failed to render selected place shape:",ej)}e.preventZoom?this.handlePinVisibility(n,{maintainZoom:!0}):t.bbox?this.zoomToBbox(t.bbox):this.handlePinVisibility(n)}else this.selectedPinElement.classList.remove("active"),this.selectedPinOverlay.setPosition(void 0)});zoomToBbox(t){if(!this.mapInstance||!t)return;const e=this.mapInstance.getView(),n=this.mapInstance.getSize(),r=[...tG([t.minLon,t.minLat]),...tG([t.maxLon,t.maxLat])];let i=[.15*n[1],.15*n[0],.15*n[1],.15*n[0]];if(n[0]<=768){const t=.5*n[1],e=.15*t,r=.5*n[1]+.15*t;i[0]=e,i[2]=r}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),e=parseInt(t,10)||360,r=n[0]-e;i[3]=e+.15*r,i[1]=.15*r}const s=e.getZoom();e.fit(r,{padding:i,duration:1e3,easing:t=>t*(2-t),maxZoom:Math.max(s,18)})}handlePinVisibility(t,e={}){if(!this.mapInstance)return;const n=this.mapInstance.getView().getZoom();if(!e.maintainZoom&&n<16)return void this.animateToSmartCenter(t,16);const r=this.mapInstance.getPixelFromCoordinate(t),i=this.mapInstance.getSize();if(!r||r[0]<0||r[0]>i[0]||r[1]<0||r[1]>i[1]){const n=e.maintainZoom?null:16;this.animateToSmartCenter(t,n)}else this.panIfObscured(t)}animateToSmartCenter(t,e=null){if(!this.mapInstance)return;const n=this.mapInstance.getSize(),r=this.mapInstance.getView();let i=r.getResolution();null!==e&&(i=r.getResolutionForZoom(e));let s=t;if(n[0]<=768){const e=.25*n[1]*i;s=[t[0],t[1]-e]}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),n=(parseInt(e,10)||360)/2*i;s=[t[0]-n,t[1]]}const o={center:s,duration:1e3,easing:t=>t*(2-t)};null!==e&&(o.zoom=e),r.animate(o)}panIfObscured(t){if(!this.mapInstance)return;const e=this.mapInstance.getSize(),n=this.mapInstance.getPixelFromCoordinate(t);if(!n)return;const r=this.mapInstance.getView(),i=r.getCenter(),s=r.getResolution();let o=n[0],a=n[1],l=!1;if(e[0]<=768){const t=e[1],r=t/2;n[1]>r&&(a=.25*t,l=!0)}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),r=parseInt(t,10)||360;n[0]t*(2-t)})}}updateBookmarks=UB(()=>{const t=this.storage.placesInView;this.loadBookmarks(t)});async loadBookmarks(t=[]){try{if(!this.bookmarkSource)return;t&&0!==t.length||(t=this.storage.placesInView),this.bookmarkSource.clear(),t&&Array.isArray(t)&&t.forEach(t=>{if(t.lat&&t.lon){const e=new TQ({geometry:new XG(tG([t.lon,t.lat])),name:t.title,id:t.id,isBookmark:!0,originalPlace:t});this.bookmarkSource.addFeature(e)}})}catch(ej){console.error("Failed to load bookmarks:",ej)}}syncPulse=UB(()=>{this.searchOverlayElement&&(this.mapUi.isSearching?this.searchOverlayElement.classList.add("active"):this.searchOverlayElement.classList.remove("active"))});syncCreationMode=UB(()=>{if(this.crosshairElement&&this.mapInstance)if(this.mapUi.isCreating){this.crosshairElement.classList.add("visible");const t=this.mapUi.creationCoordinates;if(t&&t.lat&&t.lon){const e=tG([t.lon,t.lat]);this.animateToCrosshair(e)}}else this.crosshairElement.classList.remove("visible")});animateToCrosshair(t){if(!this.mapInstance||!this.crosshairElement)return;const e=this.mapInstance.getTargetElement().getBoundingClientRect(),n=this.crosshairElement.getBoundingClientRect(),r=n.left+n.width/2-e.left,i=n.top+n.height/2-e.top,s=this.mapInstance.getSize(),o=r-s[0]/2,a=i-s[1]/2,l=this.mapInstance.getView(),c=l.getResolution(),u=o*c,h=-a*c,d=t[0]-u,p=t[1]-h,f=l.getCenter();Math.sqrt(Math.pow(f[0]-d,2)+Math.pow(f[1]-p,2))>5*c&&l.animate({center:[d,p],duration:800,easing:t=>t*(2-t)})}handleMapMove=async()=>{if(!this.mapInstance||this.isDestroying||this.isDestroyed)return;const t=eG(this.mapInstance.getView().getCenter());if(this.mapUi.updateCenter(t[1],t[0]),this.mapUi.isCreating){const t=this.mapInstance.getTargetElement().getBoundingClientRect(),e=this.crosshairElement.getBoundingClientRect(),n=e.left+e.width/2-t.left,r=e.top+e.height/2-t.top,i=eG(this.mapInstance.getCoordinateFromPixel([n,r])),s=parseFloat(i[1].toFixed(6)),o=parseFloat(i[0].toFixed(6));this.mapUi.updateCreationCoordinates(s,o),this.router.replaceWith("place.new",{queryParams:{lat:s,lon:o}})}const e=this.mapInstance.getSize(),n=this.mapInstance.getView().calculateExtent(e),[r,i]=eG([n[0],n[1]]),[s,o]=eG([n[2],n[3]]),a={minLat:i,minLon:r,maxLat:o,maxLon:s};this.mapUi.updateBounds(a),await this.storage.loadPlacesInBounds(a),this.nostrData.loadPlacesInBounds(a),this.loadBookmarks(this.storage.placesInView);try{const t=this.mapInstance.getView(),e={center:eG(t.getCenter()),zoom:t.getZoom()};localStorage.setItem("marco:map-view",JSON.stringify(e))}catch(ej){console.warn("Failed to save map view:",ej)}};handleMapClick=async t=>{if(this.ignoreNextMapClick)return void(this.ignoreNextMapClick=!1);const e=this.mapInstance.getFeaturesAtPixel(t.pixel,{hitTolerance:10});let n=null,r=null,i=null;if(e&&e.length>0){console.debug(`Found ${e.length} features in map layer:`);for(const n of e)console.debug(n);const t=e.find(t=>t.get("isBookmark")),s=e.find(t=>t.get("isSearchResult"));t?n=t.get("originalPlace"):s&&(r=s.get("originalPlace"));const o=e[0].getProperties();o.name&&(i=o.name)}const s=t=>{("search"===this.router.currentRouteName||this.mapUi.currentSearch&&this.mapUi.searchResults.length>0)&&(this.mapUi.returnToSearch=!0),this.mapUi.preventNextZoom=!0,this.router.transitionTo("place",t)};if(this.args.isSidebarOpen){const t=n||r;return t?(console.debug("Clicked feature while sidebar open (switching):",t),void s(t)):void(this.args.onOutsideClick&&this.args.onOutsideClick())}if(n)return console.debug("Clicked bookmark:",n),void s(n);if(r)return console.debug("Clicked search result:",r),void s(r);if(this.mapInstance.getView().getZoom()<16)return;const o=eG(t.coordinate),[a,l]=o,c=i?30:50;if(this.searchOverlayElement){const e=this.mapInstance.getView(),n=2*c/XH(e.getProjection(),e.getResolution(),t.coordinate);this.searchOverlayElement.style.width=`${n}px`,this.searchOverlayElement.style.height=`${n}px`,this.searchOverlay.setPosition(t.coordinate)}this.mapUi.startSearch();const u={lat:l.toFixed(6),lon:a.toFixed(6),q:null,category:null,selected:i||null};this.router.transitionTo("search",{queryParams:u})};static{Xr(em({id:null,block:'[[[11,0],[16,0,[29,["map-container ",[52,[30,1],"sidebar-open"]]]],[4,[30,0,["setupMap"]],null,null],[4,[30,0,["updateInteractions"]],null,null],[4,[30,0,["updateBookmarks"]],null,null],[4,[30,0,["updateSearchResults"]],null,null],[4,[30,0,["updateSelectedPin"]],null,null],[4,[30,0,["syncPulse"]],null,null],[4,[30,0,["syncCreationMode"]],null,null],[12],[13]],["@isSidebarOpen"],["if"]]',moduleName:"/home/basti/src/marco/app/components/map.gjs",isStrictMode:!0}),this)}}class j8 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"osmAuth",[$f])}#Gt=void fF(this,"osmAuth");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isNostrConnectModalOpen",[Is],function(){return!1})}#qt=void fF(this,"isNostrConnectModalOpen");connectRS(){this.args.onClose(),this.args.storage.showConnectWidget()}static{pF(this.prototype,"connectRS",[Pu])}disconnectRS(){this.args.storage.disconnect()}static{pF(this.prototype,"disconnectRS",[Pu])}connectOsm(){this.args.onClose(),this.osmAuth.login()}static{pF(this.prototype,"connectOsm",[Pu])}disconnectOsm(){this.osmAuth.logout()}static{pF(this.prototype,"disconnectOsm",[Pu])}openNostrConnectModal(){this.isNostrConnectModalOpen=!0}static{pF(this.prototype,"openNostrConnectModal",[Pu])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{pF(this.prototype,"closeNostrConnectModal",[Pu])}disconnectNostr(){this.nostrAuth.disconnect()}static{pF(this.prototype,"disconnectNostr",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"user-menu-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"account-list"],[12],[1,"\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["remotestorage",18]],null],[1,"\\n "],[10,1],[12],[1,"RemoteStorage"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectRS"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectRS"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[10,"strong"],[12],[1,[30,1,["userAddress"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",18]],null],[1,"\\n "],[10,1],[12],[1,"OpenStreetMap"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectOsm"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectOsm"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[10,"strong"],[12],[1,[30,0,["osmAuth","userDisplayName"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",18]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectNostr"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["openNostrConnectModal"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[10,"strong"],[15,"title",[30,0,["nostrAuth","pubkey"]]],[12],[1,"\\n "],[1,[30,0,["nostrData","userDisplayName"]]],[1,"\\n "],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,2],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,3],null,[["@onConnect"],[[30,0,["closeNostrConnectModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],["@storage"],["if"]]',moduleName:"/home/basti/src/marco/app/components/user-menu.gjs",scope:()=>[DB,Sb,Eq,kq],isStrictMode:!0}),this)}}du.Promise;class B8 extends MU{_deferable(){return KU.defer()}}class U8 extends B8{constructor(t){super(),this.ms=t}onYield(t){let e=_a(()=>t.next(),this.ms);return()=>ka(e)}}class $8 extends LB{static{dF(this.prototype,"photon",[$f])}#Ht=void fF(this,"photon");static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"map",[$f])}#Kt=void fF(this,"map");static{dF(this.prototype,"_internalQuery",[Is],function(){return""})}#Zt=void fF(this,"_internalQuery");static{dF(this.prototype,"results",[Is],function(){return[]})}#Yt=void fF(this,"results");static{dF(this.prototype,"isFocused",[Is],function(){return!1})}#Xt=void fF(this,"isFocused");static{dF(this.prototype,"isLoading",[Is],function(){return!1})}#Jt=void fF(this,"isLoading");get query(){return this.args.query??this._internalQuery}set query(t){this._internalQuery=t}get showPopover(){return this.isFocused&&this.results.length>0}handleInput(t){const e=t.target.value;this.query=e,this.args.onQueryChange&&this.args.onQueryChange(e),e.length<2?this.results=[]:this.searchTask.perform(e)}static{pF(this.prototype,"handleInput",[Pu])}searchTask=i$(()=>({context:this,generator:function*(t){yield new U8(300);const e="string"==typeof t?t:this.query;if(!(e.length<2)){this.isLoading=!0;try{let t,n;this.mapUi.currentCenter&&({lat:t,lon:n}=this.mapUi.currentCenter);const r=e.toLowerCase(),i=PN.filter(t=>t.label.toLowerCase().includes(r)).map(t=>({source:"category",title:t.label,id:t.id,icon:"search"})),s=yield this.photon.search(e,t,n);this.results=[...i,...s]}catch(ej){console.error("Search failed",ej),this.results=[]}finally{this.isLoading=!1}}}}),{restartable:!0},"searchTask");handleFocus(){this.isFocused=!0,this.mapUi.setSearchBoxFocus(!0),this.query.length>=2&&0===this.results.length&&this.searchTask.perform()}static{pF(this.prototype,"handleFocus",[Pu])}handleBlur(){setTimeout(()=>{this.isFocused=!1,this.mapUi.setSearchBoxFocus(!1)},300)}static{pF(this.prototype,"handleBlur",[Pu])}handleSubmit(t){if(t.preventDefault(),!this.query)return;let e={q:this.query,selected:null,category:null};if(this.mapUi.currentCenter){const{lat:t,lon:n}=this.mapUi.currentCenter;e.lat=parseFloat(t).toFixed(4),e.lon=parseFloat(n).toFixed(4)}this.router.transitionTo("search",{queryParams:e}),this.isFocused=!1}static{pF(this.prototype,"handleSubmit",[Pu])}selectResult(t){if("category"===t.source){this.query=t.title,this.args.onQueryChange&&this.args.onQueryChange(t.title),this.results=[];let e=null,n=null;return this.mapUi.currentCenter&&(({lat:e,lon:n}=this.mapUi.currentCenter),e=e?.toString(),n=n?.toString()),void this.router.transitionTo("search",{queryParams:{q:t.title,category:t.id,selected:null,lat:e,lon:n}})}if(this.query=t.title,this.args.onQueryChange&&this.args.onQueryChange(t.title),this.results=[],t.osmId){const e=`osm:${t.osmType}:${t.osmId}`;this.router.transitionTo("place",e)}else this.router.transitionTo("search",{queryParams:{q:t.title,lat:t.lat,lon:t.lon,selected:null,category:null}})}static{pF(this.prototype,"selectResult",[Pu])}clear(){this.searchTask.cancelAll(),this.mapUi.stopLoading(),this.osm.cancelAll(),this.photon.cancelAll(),this.query="",this.results=[],this.args.onQueryChange&&this.args.onQueryChange(""),this.router.transitionTo("index")}static{pF(this.prototype,"clear",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"search-box"],[12],[1,"\\n "],[11,"form"],[24,0,"search-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"menu-btn-integrated"],[24,"aria-label","Menu"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["menu",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"input"],[24,0,"search-input"],[24,"placeholder","Search places..."],[24,"aria-label","Search places"],[16,2,[30,0,["query"]]],[24,"autocomplete","off"],[24,4,"search"],[4,[32,0],["input",[30,0,["handleInput"]]],null],[4,[32,0],["focus",[30,0,["handleFocus"]]],null],[4,[32,0],["blur",[30,0,["handleBlur"]]],null],[12],[13],[1,"\\n\\n "],[10,"button"],[14,0,"search-submit-btn"],[14,"aria-label","Search"],[14,4,"submit"],[12],[1,"\\n"],[41,[28,[32,2],[[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"text"],null],[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"category"],null]],null],[[[1," "],[8,[32,1],null,[["@name","@size"],["loading-ring",20]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#5f6368"]],null],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["query"]],[[[1," "],[11,"button"],[24,0,"search-clear-btn"],[24,"aria-label","Clear"],[24,4,"button"],[4,[32,0],["click",[30,0,["clear"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["showPopover"]],[[[1," "],[10,0],[14,0,"search-results-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"search-results-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,0,["results"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"search-result-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,4],[[30,0,["selectResult"]],[30,2]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"result-icon"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],[[52,[30,2,["icon"]],[30,2,["icon"]],"map-pin"],16,"#666"]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"result-info"],[12],[1,"\\n "],[10,1],[14,0,"result-title"],[12],[1,[30,2,["title"]]],[13],[1,"\\n"],[41,[28,[32,3],[[30,2,["source"]],"osm"],null],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[28,[32,5],[[30,2,["type"]]],null]],[13],[1,"\\n"]],[]],[[[41,[30,2,["description"]],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[30,2,["description"]]],[13],[1,"\\n"]],[]],null]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13]],["@onToggleMenu","result"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/search-box.gjs",scope:()=>[Sb,DB,FB,zB,AB,Lq],isStrictMode:!0}),this)}}class q8 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");get categories(){return PN}searchCategory(t){this.args.onSelect&&this.args.onSelect(t);let e={category:t.id,q:null};if(this.mapUi.currentCenter){const{lat:t,lon:n}=this.mapUi.currentCenter;e.lat=parseFloat(t).toFixed(4),e.lon=parseFloat(n).toFixed(4)}this.router.transitionTo("search",{queryParams:e})}static{pF(this.prototype,"searchCategory",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"category-chips-scroll"],[12],[1,"\\n "],[10,0],[14,0,"category-chips-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["categories"]]],null]],null],null,[[[1," "],[11,"button"],[24,0,"category-chip"],[16,"aria-label",[30,1,["label"]]],[16,"disabled",[28,[32,0],[[28,[32,1],[[30,0,["mapUi","loadingState","type"]],"category"],null],[28,[32,1],[[30,0,["mapUi","loadingState","value"]],[30,1,["id"]]],null]],null]],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,0,["searchCategory"]],[30,1]],null]],null],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size"],[[30,1,["icon"]],16]],null],[1,"\\n "],[10,1],[12],[1,[30,1,["label"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[1]],null],[1," "],[13],[1,"\\n"],[13]],["category"],["each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/category-chips.gjs",scope:()=>[a$,zB,Sb,AB,DB],isStrictMode:!0}),this)}}const V8=UB((t,[e])=>{let n=null;return async function(){if(e)try{const r=await caches.open("nostr-image-cache-v1"),i=await r.match(e);if(i){const e=await i.blob();return n=URL.createObjectURL(e),void(t.src=n)}const s=await fetch(e,{mode:"cors",credentials:"omit"});if(s.ok){const i=s.clone();await r.put(e,i);const o=await s.blob();n=URL.createObjectURL(o),t.src=n}else t.src=e}catch(v5){console.warn(`Failed to cache image ${e}, falling back to standard src`,v5),t.src=e}else t.src=""}(),()=>{n&&(URL.revokeObjectURL(n),n=null)}});class W8 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isUserMenuOpen",[Is],function(){return!1})}#Qt=void fF(this,"isUserMenuOpen");static{dF(this.prototype,"searchQuery",[Is],function(){return""})}#te=void fF(this,"searchQuery");get hasQuery(){return!!this.searchQuery}toggleUserMenu(){this.isUserMenuOpen=!this.isUserMenuOpen}static{pF(this.prototype,"toggleUserMenu",[Pu])}closeUserMenu(){this.isUserMenuOpen=!1}static{pF(this.prototype,"closeUserMenu",[Pu])}handleQueryChange(t){this.searchQuery=t}static{pF(this.prototype,"handleQueryChange",[Pu])}handleChipSelect(t){this.searchQuery=t.label}static{pF(this.prototype,"handleChipSelect",[Pu])}static{Xr(em({id:null,block:'[[[10,"header"],[14,0,"app-header"],[12],[1,"\\n "],[10,0],[14,0,"header-left"],[12],[1,"\\n "],[8,[32,0],null,[["@query","@onToggleMenu","@onQueryChange"],[[30,0,["searchQuery"]],[30,1],[30,0,["handleQueryChange"]]]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["settings","showQuickSearchButtons"]],[[[1," "],[10,0],[15,0,[29,["header-center ",[52,[30,0,["hasQuery"]],"searching"]]]],[12],[1,"\\n "],[8,[32,1],null,[["@onSelect"],[[30,0,["handleChipSelect"]]]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,0],[14,0,"header-right"],[12],[1,"\\n "],[10,0],[14,0,"user-menu-container"],[12],[1,"\\n "],[11,"button"],[24,0,"user-btn btn-press"],[24,"aria-label","User Menu"],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleUserMenu"]]],null],[12],[1,"\\n"],[41,[28,[32,3],[[30,0,["nostrAuth","isConnected"]],[30,0,["nostrData","profile","picture"]]],null],[[[1," "],[11,"img"],[24,0,"user-avatar"],[24,"alt","User Avatar"],[4,[32,4],[[30,0,["nostrData","profile","picture"]]],null],[12],[13],[1,"\\n"]],[]],[[[1," "],[10,0],[14,0,"user-avatar-placeholder"],[12],[1,"\\n "],[8,[32,5],null,[["@name","@size","@color"],["user",20,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isUserMenuOpen"]],[[[1," "],[8,[32,6],null,[["@storage","@onClose"],[[30,0,["storage"]],[30,0,["closeUserMenu"]]]],null],[1,"\\n "],[11,0],[24,0,"menu-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["closeUserMenu"]]],null],[12],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onToggleMenu"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-header.gjs",scope:()=>[$8,q8,Sb,a$,V8,DB,j8],isStrictMode:!0}),this)}}const H8=Ny,G8=Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[1,"\\n "],[10,1],[14,0,"app-logo-icon"],[12],[1,"\\n "],[1,[28,[32,0],[[32,1]],null]],[1,"\\n "],[13],[1,"\\n Marco\\n "],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,2],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"ul"],[14,0,"app-menu"],[12],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"settings"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["settings",20]],null],[1,"\\n "],[10,1],[12],[1,"Settings"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"about"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["info",20]],null],[1,"\\n "],[10,1],[12],[1,"About"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onClose","@onNavigate"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/home.gjs",scope:()=>[zw,'\n \x3c!-- Background --\x3e\n \n\n \x3c!-- Subtle map grid (kept well outside safe zone) --\x3e\n \n \n \n \n\n \n \n \n \n\n \x3c!-- Location pin (exact app shape, larger, centered, safe-zone compliant) --\x3e\n \x3c!-- Safe zone target: ~680px diameter --\x3e\n \n \n \n \n\n',Sb,DB,AB],isStrictMode:!0}),H8());class K8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",20]],null],[1,"\\n "],[10,1],[12],[1,"Map & UI"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","show-quick-search"],[12],[1,"Quick search buttons visible"],[13],[1,"\\n "],[11,"select"],[24,1,"show-quick-search"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"showQuickSearchButtons"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","showQuickSearchButtons"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","showQuickSearchButtons"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","map-kinetic"],[12],[1,"Map Inertia (Kinetic Panning)"],[13],[1,"\\n "],[11,"select"],[24,1,"map-kinetic"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"mapKinetic"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","mapKinetic"]],"selected"]],[12],[1,"\\n On\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","mapKinetic"]]],"selected"]],[12],[1,"\\n Off\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange"],["if","unless"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/map-ui.gjs",scope:()=>[DB,Sb,AB],isStrictMode:!0}),this)}}class Z8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["server",20]],null],[1,"\\n "],[10,1],[12],[1,"API Providers"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","overpass-api"],[12],[1,"Overpass API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"overpass-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"overpassApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","overpassApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,2,["url"]]],[15,"selected",[52,[28,[32,3],[[30,2,["url"]],[30,0,["settings","overpassApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,2,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","photon-api"],[12],[1,"Photon API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"photon-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"photonApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","photonApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,3,["url"]]],[15,"selected",[52,[28,[32,3],[[30,3,["url"]],[30,0,["settings","photonApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,3,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","api","api"],["each","-track-array","if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/apis.gjs",scope:()=>[DB,Sb,AB,zB],isStrictMode:!0}),this)}}const Y8=t=>t?t.replace(/^wss?:\/\//,""):"";class X8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"newReadRelay",[Is],function(){return""})}#ee=void fF(this,"newReadRelay");static{dF(this.prototype,"newWriteRelay",[Is],function(){return""})}#ne=void fF(this,"newWriteRelay");updateNewReadRelay(t){this.newReadRelay=t.target.value}static{pF(this.prototype,"updateNewReadRelay",[Pu])}updateNewWriteRelay(t){this.newWriteRelay=t.target.value}static{pF(this.prototype,"updateNewWriteRelay",[Pu])}addReadRelay(){const t=AD(this.newReadRelay);if(!t)return;const e=this.settings.nostrReadRelays||this.nostrData.defaultReadRelays,n=new Set([...e,t]);this.settings.update("nostrReadRelays",Array.from(n)),this.newReadRelay=""}static{pF(this.prototype,"addReadRelay",[Pu])}removeReadRelay(t){const e=(this.settings.nostrReadRelays||this.nostrData.defaultReadRelays).filter(e=>e!==t);this.settings.update("nostrReadRelays",e)}static{pF(this.prototype,"removeReadRelay",[Pu])}handleReadRelayKeydown(t){"Enter"===t.key&&this.addReadRelay()}static{pF(this.prototype,"handleReadRelayKeydown",[Pu])}handleWriteRelayKeydown(t){"Enter"===t.key&&this.addWriteRelay()}static{pF(this.prototype,"handleWriteRelayKeydown",[Pu])}resetReadRelays(){this.settings.update("nostrReadRelays",null)}static{pF(this.prototype,"resetReadRelays",[Pu])}addWriteRelay(){const t=AD(this.newWriteRelay);if(!t)return;const e=this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays,n=new Set([...e,t]);this.settings.update("nostrWriteRelays",Array.from(n)),this.newWriteRelay=""}static{pF(this.prototype,"addWriteRelay",[Pu])}removeWriteRelay(t){const e=(this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays).filter(e=>e!==t);this.settings.update("nostrWriteRelays",e)}static{pF(this.prototype,"removeWriteRelay",[Pu])}resetWriteRelays(){this.settings.update("nostrWriteRelays",null)}static{pF(this.prototype,"resetWriteRelays",[Pu])}static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",20]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","nostr-photo-fallback-uploads"],[12],[1,"Upload photos to fallback\\n servers"],[13],[1,"\\n "],[11,"select"],[24,1,"nostr-photo-fallback-uploads"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"nostrPhotoFallbackUploads"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","nostrPhotoFallbackUploads"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","nostrPhotoFallbackUploads"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-read-relay"],[12],[1,"Read Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeReadRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,2]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeReadRelay"]],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-read-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newReadRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewReadRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleReadRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addReadRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrReadRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetReadRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-write-relay"],[12],[1,"Write Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeWriteRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,3]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeWriteRelay"]],[30,3]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-write-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newWriteRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewWriteRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleWriteRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addWriteRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrWriteRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetWriteRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","relay","relay"],["if","unless","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/nostr.gjs",scope:()=>[DB,Sb,AB,Y8],isStrictMode:!0}),this)}}class J8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");updateSetting(t,e){let n=e.target.value;"true"===n&&(n=!0),"false"===n&&(n=!1),this.settings.update(t,n)}static{pF(this.prototype,"updateSetting",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"Settings"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"settings-section"],[12],[1,"\\n "],[8,[32,2],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,3],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,4],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings.gjs",scope:()=>[Sb,DB,K8,Z8,X8],isStrictMode:!0}),this)}}const Q8=Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"About"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"about-section"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Marco"],[13],[1,"\\n (as in\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/Marco_Polo"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"Marco Polo"],[13],[1,") is an unhosted maps application that respects your\\n privacy and choices.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n Connect your own\\n "],[10,3],[14,6,"https://remotestorage.io/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"remote storage"],[13],[1,"\\n to sync place bookmarks across apps and devices.\\n "],[13],[1,"\\n\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["gift",20]],null],[1,"\\n "],[10,1],[12],[1,"Open Source"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,"table"],[12],[1,"\\n "],[10,"thead"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"th"],[12],[1,"Source"],[13],[1,"\\n "],[10,"th"],[12],[1,"License"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tbody"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://gitea.kosmos.org/raucao/marco"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Marco App\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/GNU_Affero_General_Public_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","GNU Affero General Public License"],[12],[1,"AGPL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://openstreetmap.org/copyright"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Map Data\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://opendatacommons.org/licenses/odbl/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","Open Data Commons Open Database License"],[12],[1,"ODbL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/feathericons/feather"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Feather Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/MIT_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","MIT License"],[12],[1,"MIT"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://pinhead.ink/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Pinhead Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/waysidemapping/pinhead?tab=readme-ov-file#where-the-icons-are-from"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Various\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["heart",20,"#e5533d"]],null],[1,"\\n "],[10,1],[12],[1,"Contribute"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most impactful:"],[13],[1,"\\n Add and improve data for points of interest in\\n "],[10,3],[14,6,"https://www.openstreetmap.org"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"OpenStreetMap"],[13],[1,".\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most appreciated:"],[13],[1,"\\n Use this app as much as you can and\\n "],[10,3],[14,6,"https://community.remotestorage.io/t/marco-an-unhosted-maps-app/941"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"submit feedback"],[13],[1,"\\n about your experience, problems, feature wishes, etc.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most supportive:"],[13],[1,"\\n Tell others about this app, on social media, in blog posts,\\n educational videos, etc.\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/about.gjs",scope:()=>[Sb,DB],isStrictMode:!0}),H8());class t7 extends LB{static{dF(this.prototype,"currentView",[Is],function(){return"menu"})}#re=void fF(this,"currentView");setView(t){this.currentView=t}static{pF(this.prototype,"setView",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar app-menu-pane"],[12],[1,"\\n"],[41,[28,[32,0],[[30,0,["currentView"]],"menu"],null],[[[1," "],[8,[32,1],null,[["@onNavigate","@onClose"],[[30,0,["setView"]],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"settings"],null],[[[1," "],[8,[32,2],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"about"],null],[[[1," "],[8,[32,4],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n "]],[]],null]],[]]]],[]]],[13]],["@onClose"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/index.gjs",scope:()=>[zB,G8,J8,AB,Q8],isStrictMode:!0}),this)}}class e7 extends LB{static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");static{Xr(em({id:null,block:'[[[41,[30,0,["toast","isVisible"]],[[[1," "],[10,0],[14,0,"toast-notification"],[12],[1,"\\n "],[1,[30,0,["toast","message"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/toast.gjs",isStrictMode:!0}),this)}}class n7 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"isAppMenuOpen",[Is],function(){return!1})}#ie=void fF(this,"isAppMenuOpen");get isSidebarOpen(){return"place"===this.router.currentRouteName||"place.new"===this.router.currentRouteName||"search"===this.router.currentRouteName}constructor(){super(...arguments),console.debug("Application component constructed"),this.storage}toggleAppMenu(){this.isAppMenuOpen=!this.isAppMenuOpen}static{pF(this.prototype,"toggleAppMenu",[Pu])}closeAppMenu(){this.isAppMenuOpen=!1}static{pF(this.prototype,"closeAppMenu",[Pu])}handleOutsideClick(){this.isAppMenuOpen?this.closeAppMenu():("search"===this.router.currentRouteName||"place"===this.router.currentRouteName)&&this.router.transitionTo("index")}static{pF(this.prototype,"handleOutsideClick",[Pu])}refreshBookmarks(){this.storage.notifyChange()}static{pF(this.prototype,"refreshBookmarks",[Pu])}static{Xr(em({id:null,block:'[[[1,[28,[32,0],["Marco"],null]],[1,"\\n\\n"],[8,[32,1],null,[["@onToggleMenu"],[[30,0,["toggleAppMenu"]]]],null],[1,"\\n\\n"],[10,0],[14,1,"rs-widget-container"],[15,0,[52,[30,0,["storage","isWidgetOpen"]],"visible"]],[12],[13],[1,"\\n\\n"],[41,[30,0,["storage","isWidgetOpen"]],[[[1," "],[11,0],[24,0,"rs-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["storage","closeWidget"]]],null],[12],[13],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,3],null,[["@isSidebarOpen","@onOutsideClick"],[[28,[32,4],[[30,0,["isSidebarOpen"]],[30,0,["isAppMenuOpen"]]],null],[30,0,["handleOutsideClick"]]]],null],[1,"\\n\\n"],[41,[30,0,["isAppMenuOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeAppMenu"]]]],null],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,6],null,null,null],[1,"\\n\\n"],[46,[28,[31,2],null,null],null,null,null]],[],["if","component","-outlet"]]',moduleName:"/home/basti/src/marco/app/templates/application.gjs",scope:()=>[Bq,W8,Sb,N8,FB,t7,e7],isStrictMode:!0}),this)}}const r7=Object.freeze(Object.defineProperty({__proto__:null,default:n7},Symbol.toStringTag,{value:"Module"}));class i7 extends kp{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage")}const s7=Object.freeze(Object.defineProperty({__proto__:null,default:i7},Symbol.toStringTag,{value:"Module"}));class o7 extends kp{static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");activate(){this.mapUi.clearSearchResults()}}const a7=Object.freeze(Object.defineProperty({__proto__:null,default:o7},Symbol.toStringTag,{value:"Module"}));class l7 extends kp{static{dF(this.prototype,"osmAuth",[$f])}#Gt=void fF(this,"osmAuth");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");async model(){try{await this.osmAuth.handleCallback()}catch(ej){console.error("Failed to handle OSM OAuth callback",ej)}finally{this.router.transitionTo("index")}}}const c7=Object.freeze(Object.defineProperty({__proto__:null,default:l7},Symbol.toStringTag,{value:"Module"}));class u7 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"localPlace",[Is],function(){return null})}#se=void fF(this,"localPlace");constructor(){super(...arguments),this.localPlace=this.args.model}get place(){const t=this.args.model,e=t.osmId||t.id;return this.storage.findPlaceById(e)||(!this.localPlace||this.localPlace.osmId!==e&&this.localPlace.id!==e?t.createdAt?{...t,id:void 0,createdAt:void 0,geohash:void 0}:t:this.localPlace)}handleUpdate(t){console.debug("Updating local place state:",t),this.localPlace=t,this.storage.notifyChange()}static{pF(this.prototype,"handleUpdate",[Pu])}refreshMap(){this.storage.notifyChange()}static{pF(this.prototype,"refreshMap",[Pu])}navigateBack(t){null===t?this.mapUi.returnToSearch&&this.mapUi.currentSearch?this.router.transitionTo("search",{queryParams:this.mapUi.currentSearch}):this.router.transitionTo("index"):this.router.transitionTo("place",t)}static{pF(this.prototype,"navigateBack",[Pu])}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[8,[32,0],null,[["@selectedPlace","@onClose","@onSelect","@onBookmarkChange","@onUpdate"],[[30,0,["place"]],[30,0,["close"]],[30,0,["navigateBack"]],[30,0,["refreshMap"]],[30,0,["handleUpdate"]]]],null]],[],[]]',moduleName:"/home/basti/src/marco/app/templates/place.gjs",scope:()=>[Iq],isStrictMode:!0}),this)}}const h7=Object.freeze(Object.defineProperty({__proto__:null,default:u7},Symbol.toStringTag,{value:"Module"}));class d7 extends kp{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");async model(t){const e=t.place_id;let n,r,i=!1;(e.startsWith("osm:node:")||e.startsWith("osm:way:")||e.startsWith("osm:relation:"))&&(i=!0,[,n,r]=e.split(":"),console.debug(`Fetching explicit OSM ${n}:`,r));let s=null;i&&(s=this.loadOsmPlace(r,n)),await this.waitForSync();let o=i?r:e,a=this.storage.findPlaceById(o);return a&&i&&a.osmType!==n&&(a=null),a?(console.debug("Found in bookmarks:",a.title),a):i?(console.debug(`Not in bookmarks, using explicitly fetched OSM ${n}:`,r),await s):(console.warn("Not in bookmarks:",e),null)}async waitForSync(){if(this.storage.initialSyncDone)return;console.debug("Waiting for initial storage sync...");const t=Date.now();for(;!this.storage.initialSyncDone;){if(Date.now()-t>5e3){console.warn("Timed out waiting for initial sync");break}await new Promise(t=>setTimeout(t,100))}}async afterModel(t){if(t&&t.osmId&&t.osmType&&"node"!==t.osmType&&!t.geojson){console.debug("Model missing geometry, fetching full OSM details...");const e=await this.loadOsmPlace(t.osmId,t.osmType);e&&(Object.assign(t,e),console.debug("Enriched model with full OSM details",t))}if(t){const e={preventZoom:this.mapUi.preventNextZoom};this.mapUi.selectPlace(t,e),this.mapUi.preventNextZoom=!1}this.mapUi.stopSearch()}deactivate(){this.mapUi.clearSelection(),this.mapUi.returnToSearch=!1}async loadOsmPlace(t,e=null){try{const n=await this.osm.fetchOsmObject(t,e);if(n)return console.debug("Found OSM POI:",n),n}catch(ej){console.error("Failed to fetch POI",ej)}return null}setupController(t,e){super.setupController(t,e),this.checkUpdates(e)}async checkUpdates(t){if(t&&t.id&&t.osmId&&t.osmType){const e=await this.storage.refreshPlace(t);e&&this.mapUi.selectPlace(e,{preventZoom:!0})}}serialize(t){return t.osmId&&t.osmType?{place_id:`osm:${t.osmType}:${t.osmId}`}:t.id?{place_id:t.id}:{place_id:t.osmId}}}const p7=Object.freeze(Object.defineProperty({__proto__:null,default:d7},Symbol.toStringTag,{value:"Module"}));class f7 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");get initialPlace(){return{title:"",description:""}}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}async savePlace(t){try{const e=this.mapUi.creationCoordinates||{lat:this.args.model.lat,lon:this.args.model.lon},n=parseFloat(e.lat.toFixed(6)),r=parseFloat(e.lon.toFixed(6)),i={title:t.title||"Untitled Place",description:t.description,lat:n,lon:r,tags:[],osmTags:{}},s=await this.storage.storePlace(i);console.debug("Created private place:",s.title),this.router.replaceWith("place",s)}catch(ej){console.error("Failed to create place:",ej),alert("Failed to create place: "+ej.message)}}static{pF(this.prototype,"savePlace",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[8,[32,0],null,[["@name","@size","@color"],["plus-circle",20,"#ea4335"]],null],[1,"\\n New Place"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,1],["click",[30,0,["close"]]],null],[12],[8,[32,0],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,2],[14,0,"helper-text"],[12],[1,"\\n Drag the map to position the crosshair.\\n "],[13],[1,"\\n\\n "],[8,[32,2],null,[["@place","@onSave","@onCancel"],[[30,0,["initialPlace"]],[30,0,["savePlace"]],[30,0,["close"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],[],[]]',moduleName:"/home/basti/src/marco/app/templates/place/new.gjs",scope:()=>[DB,Sb,NB],isStrictMode:!0}),this)}}const g7=Object.freeze(Object.defineProperty({__proto__:null,default:f7},Symbol.toStringTag,{value:"Module"}));class m7 extends kp{static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0}};model(t){return{lat:parseFloat(t.lat),lon:parseFloat(t.lon)}}setupController(t,e){super.setupController(t,e),e.lat&&e.lon&&this.mapUi.updateCreationCoordinates(e.lat,e.lon),this.mapUi.startCreating()}deactivate(){this.mapUi.stopCreating()}}const y7=Object.freeze(Object.defineProperty({__proto__:null,default:m7},Symbol.toStringTag,{value:"Module"})),v7=Object.assign({},px,{"marco/app":t,"marco/config/environment":vx,"marco/deprecation-workflow":wx,"marco/router":Tx,"marco/services/blossom":vF,"marco/services/image-processor":wF,"marco/services/map-ui":xF,"marco/services/nostr-auth":Rz,"marco/services/nostr-data":VD,"marco/services/nostr-relay":rN,"marco/services/osm-auth":kN,"marco/services/osm":zN,"marco/services/photon":NN,"marco/services/settings":UN,"marco/services/storage":zj,"marco/services/toast":Nj,"marco/utils/device":wz,"marco/utils/format-text":TN,"marco/utils/geo":Bj,"marco/utils/geohash-coverage":jD,"marco/utils/icons":Wj,"marco/utils/nostr":FD,"marco/utils/osm-icons":Kj,"marco/utils/osm":IN,"marco/utils/place-mapping":Yj,"marco/utils/poi-categories":ON,"marco/utils/social-links":Jj,"marco/workers/image-processor":cB,"marco/services/page-title":xB,"marco/templates/search":Aq,"marco/controllers/search":Oq,"marco/routes/search":zq,"marco/templates/application":r7,"marco/routes/application":s7,"marco/routes/index":a7,"marco/routes/oauth/osm-callback":c7,"marco/templates/place":h7,"marco/routes/place":p7,"marco/templates/place/new":g7,"marco/routes/place/new":y7},{});class b7{constructor(t,e,n){this.limit=t,this.func=e,this.store=n,this.size=0,this.misses=0,this.hits=0,this.store=n||new Map}get(t){let e=this.store.get(t);return this.store.has(t)?(this.hits++,this.store.get(t)):(this.misses++,e=this.set(t,this.func(t)),e)}set(t,e){return this.limit>this.size&&(this.size++,this.store.set(t,e)),e}purge(){this.store.clear(),this.size=0,this.hits=0,this.misses=0}}const w7=/[ _]/g,_7=new b7(1e3,t=>{return(e=t,L7.get(e)).replace(w7,"-");var e}),x7=/^(\-|_)+(.)?/,C7=/(.)(\-|\_|\.|\s)+(.)?/g,S7=/(^|\/|\.)([a-z])/g,k7=new b7(1e3,t=>{const e=(t,e,n)=>n?`_${n.toUpperCase()}`:"",n=(t,e,n,r)=>e+(r?r.toUpperCase():""),r=t.split("/");for(let i=0;it.toUpperCase())}),E7=/([a-z\d])([A-Z]+)/g,T7=/\-|\s+/g,R7=new b7(1e3,t=>t.replace(E7,"$1_$2").replace(T7,"_").toLowerCase()),M7=/([a-z\d])([A-Z])/g,L7=new b7(1e3,t=>t.replace(M7,"$1_$2").toLowerCase());class I7{constructor(t){this._entries=t||globalThis.requirejs.entries}moduleNames(){return Object.keys(this._entries)}has(t){return t in this._entries}get(...t){return globalThis.require(...t)}}class P7{static moduleBasedResolver=!0;moduleBasedResolver=!0;_deprecatedPodModulePrefix=!1;_normalizeCache=Object.create(null);static create(t){return new this(t)}moduleNameLookupPatterns=[this.podBasedModuleName,this.podBasedComponentsInSubdir,this.mainModuleName,this.defaultModuleName,this.nestedColocationComponentModuleName];static withModules(t){return class extends(this){static explicitModules=t}}constructor(t){if(Object.assign(this,t),!this._moduleRegistry){let t=this.constructor.explicitModules;t?this._moduleRegistry={moduleNames:()=>Object.keys(t),has:e=>Boolean(t[e]),get:e=>t[e],addModules(e){t=Object.assign({},t,e)}}:(void 0===globalThis.requirejs.entries&&(globalThis.requirejs.entries=globalThis.requirejs._eak_seen),this._moduleRegistry=new I7)}this.pluralizedTypes=this.pluralizedTypes||Object.create(null),this.pluralizedTypes.config||(this.pluralizedTypes.config="config")}makeToString(t,e){return this.namespace.modulePrefix+"@"+e+":"}shouldWrapInClassFactory(){return!1}parseName(t){if(!0===t.parsedName)return t;let e,n,r,i=t.split("@");if(3===i.length){if(0===i[0].length){e=`@${i[1]}`;let t=i[2].split(":");n=t[0],r=t[1]}else e=`@${i[1]}`,n=i[0].slice(0,-1),r=i[2];"template:components"===n&&(r=`components/${r}`,n="template")}else if(2===i.length){let t=i[0].split(":");if(2===t.length)0===t[1].length?(n=t[0],r=`@${i[1]}`):(e=t[1],n=t[0],r=i[1]);else{let t=i[1].split(":");e=i[0],n=t[0],r=t[1]}"template"===n&&0===e.lastIndexOf("components/",0)&&(r=`components/${r}`,e=e.slice(11))}else i=t.split(":"),n=i[0],r=i[1];let s=r,o=this.namespace;return{parsedName:!0,fullName:t,prefix:e||this.prefix({type:n}),type:n,fullNameWithoutType:s,name:r,root:o,resolveMethodName:"resolve"+(a=n,k7.get(a))};var a}resolveOther(t){A7("`modulePrefix` must be defined",this.namespace.modulePrefix);let e=this.findModuleName(t);if(e){let r=this._extractDefaultExport(e,t);if(void 0===r)throw new Error(` Expected to find: '${t.fullName}' within '${e}' but got 'undefined'. Did you forget to 'export default' within '${e}'?`);return this.shouldWrapInClassFactory(r,t)&&(n=r,r={create:t=>"function"==typeof n.extend?n.extend(t):n}),r}var n}normalize(t){return this._normalizeCache[t]||(this._normalizeCache[t]=this._normalize(t))}resolve(t){if("resolver:current"===t)return{create:()=>this};let e,n=this.parseName(t),r=n.resolveMethodName;return"function"==typeof this[r]&&(e=this[r](n)),null==e&&(e=this.resolveOther(n)),e}addModules(t){if(!this._moduleRegistry.addModules)throw new Error("addModules is only supported when your Resolver has been configured to use static modules via Resolver.withModules()");this._moduleRegistry.addModules(t)}_normalize(t){let e=t.split(":");if(e.length>1){let t=e[0];return"component"===t||"helper"===t||"modifier"===t||"template"===t&&0===e[1].indexOf("components/")?t+":"+e[1].replace(/_/g,"-"):t+":"+(n=e[1].replace(/\./g,"/"),_7.get(n))}return t;var n}pluralize(t){return this.pluralizedTypes[t]||(this.pluralizedTypes[t]=t+"s")}podBasedLookupWithPrefix(t,e){let n=e.fullNameWithoutType;return"template"===e.type&&(n=n.replace(/^components\//,"")),t+"/"+n+"/"+e.type}podBasedModuleName(t){let e=this.namespace.podModulePrefix||this.namespace.modulePrefix;return this.podBasedLookupWithPrefix(e,t)}podBasedComponentsInSubdir(t){let e=this.namespace.podModulePrefix||this.namespace.modulePrefix;if(e+="/components","component"===t.type||/^components/.test(t.fullNameWithoutType))return this.podBasedLookupWithPrefix(e,t)}resolveEngine(t){let e=t.fullNameWithoutType+"/engine";if(this._moduleRegistry.has(e))return this._extractDefaultExport(e)}resolveRouteMap(t){let e=t.fullNameWithoutType,n=e+"/routes";if(this._moduleRegistry.has(n)){let t=this._extractDefaultExport(n);return A7(`The route map for ${e} should be wrapped by 'buildRoutes' before exporting.`,t.isRouteMap),t}}resolveTemplate(t){return this.resolveOther(t)}mainModuleName(t){if("main"===t.fullNameWithoutType)return t.prefix+"/"+t.type}defaultModuleName(t){return t.prefix+"/"+this.pluralize(t.type)+"/"+t.fullNameWithoutType}nestedColocationComponentModuleName(t){if("component"===t.type)return t.prefix+"/"+this.pluralize(t.type)+"/"+t.fullNameWithoutType+"/index"}prefix(t){let e=this.namespace.modulePrefix;return this.namespace[t.type+"Prefix"]&&(e=this.namespace[t.type+"Prefix"]),e}findModuleName(t){let e,n=this.moduleNameLookupPatterns;for(let r=0,i=n.length;rr.length+i.length)return t+":"+e.slice(s+r.length,o);let a=n+"/"+this.pluralize(t)+"/";return 0===e.indexOf(a)&&e.length>a.length?t+":"+e.slice(a.length):void 0}_extractDefaultExport(t){let e=this._moduleRegistry.get(t,null,null,!0);return e&&e.default&&(e=e.default),e}}function A7(t,e){if(!e)throw new Error(t)}class O7 extends hx{modulePrefix=yx.modulePrefix;podModulePrefix=yx.podModulePrefix;Resolver=P7.withModules(v7);inspector=function(t){!function(t){globalThis.emberInspectorApps||(globalThis.emberInspectorApps=[]),globalThis.emberInspectorApps.push({app:t,name:`app-${globalThis.emberInspectorApps.length}`,loadCompatInspector:()=>MD(()=>import("./modules-4-12-CyDF3xZj.js"),[])}),globalThis.dispatchEvent&&globalThis.dispatchEvent(new Event("Ember"))}(t)}(this)}O7.create(yx.APP);export{Ci as $,Wi as A,as as B,Si as C,Ms as D,Fi as E,po as F,ho as G,ts as H,Os as I,Js as J,Ui as K,Ts as L,xs as M,ao as N,Ls as O,rs as P,Pi as Q,gs as R,Vi as S,As as T,Ve as U,xi as V,mo as W,Rs as X,Ri as Y,mi as Z,ks as _,Cs as a,Xl as a$,ss as a0,di as a1,$i as a2,go as a3,fo as a4,Xs as a5,ji as a6,uo as a7,Gi as a8,Hs as a9,du as aA,$c as aB,Ic as aC,Zc as aD,Nc as aE,Bc as aF,Vc as aG,hu as aH,uu as aI,zc as aJ,Hc as aK,Wc as aL,Uc as aM,et as aN,nd as aO,g as aP,d as aQ,m as aR,p as aS,u as aT,f as aU,ne as aV,Qt as aW,Jt as aX,ae as aY,oe as aZ,se as a_,Ks as aa,Ji as ab,Bi as ac,Ai as ad,yo as ae,Qs as af,vo as ag,gi as ah,fi as ai,Is as aj,Ds as ak,qb as al,ew as am,jr as an,Ew as ao,Jr as ap,pj as aq,Xr as ar,oc as as,Mc as at,Ac as au,Fc as av,Jc as aw,cu as ax,lu as ay,lc as az,us as b,Cx as b$,Yl as b0,Zl as b1,nc as b2,pu as b3,Gl as b4,ic as b5,tc as b6,Jl as b7,fu as b8,si as b9,Ah as bA,ex as bB,Ph as bC,eh as bD,kb as bE,_h as bF,Zu as bG,Wu as bH,Hu as bI,zu as bJ,Ku as bK,Uu as bL,Du as bM,Qu as bN,Yu as bO,Ju as bP,$u as bQ,Nu as bR,Fu as bS,qu as bT,Vu as bU,dx as bV,Y_ as bW,od as bX,_j as bY,hd as bZ,W as b_,Q as ba,at as bb,K_ as bc,st as bd,cl as be,St as bf,tt as bg,nt as bh,no as bi,H as bj,Ct as bk,G as bl,ei as bm,vt as bn,dt as bo,ft as bp,eo as bq,pt as br,ni as bs,_t as bt,bt as bu,kt as bv,wt as bw,Rt as bx,Z as by,mt as bz,$e as c,Ou as c0,rc as c1,gh as c2,Eu as c3,rh as c4,Ru as c5,Ej as c6,Cj as c7,Ta as c8,Vf as c9,ll as ca,ai as cb,IB as cc,Qr as cd,rr as ce,Cb as cf,En as cg,cn as ch,NP as ci,lP as cj,hP as ck,Rx as cl,ZA as cm,eA as cn,PA as co,YP as cp,lo as d,_s as e,Ss as f,qe as g,zs as h,Ki as i,Ys as j,Ni as k,co as l,Hi as m,Ns as n,Vs as o,qs as p,fs as q,os as r,Fs as s,ls as t,ps as u,ys as v,ms as w,vs as x,Ii as y,Li as z}; +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const IF=BigInt(0),PF=BigInt(1),AF=BigInt(2),OF=BigInt(3),FF=BigInt(8),zF=Object.freeze({a:IF,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:PF,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),DF=(t,e)=>(t+e/AF)/e,NF={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){const{n:e}=zF,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-PF*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=DF(s*t,e),l=DF(-r*t,e);let c=lz(t-a*n-l*i,e),u=lz(-a*r-l*s,e);const h=c>o,d=u>o;if(h&&(c=e-c),d&&(u=e-u),c>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:h,k1:c,k2neg:d,k2:u}}};function jF(t){const{a:e,b:n}=zF,r=lz(t*t),i=lz(r*t);return lz(i+e*t+n)}const BF=zF.a===IF;function UF(t){if(!(t instanceof $F))throw new TypeError("JacobianPoint expected")}class $F{constructor(t,e,n){this.x=t,this.y=e,this.z=n}static fromAffine(t){if(!(t instanceof WF))throw new TypeError("JacobianPoint#fromAffine: expected Point");return t.equals(WF.ZERO)?$F.ZERO:new $F(t.x,t.y,PF)}static toAffineBatch(t){const e=function(t,e=zF.P){const n=new Array(t.length),r=t.reduce((t,r,i)=>r===IF?t:(n[i]=t,lz(t*r,e)),PF),i=uz(r,e);return t.reduceRight((t,r,i)=>r===IF?t:(n[i]=lz(t*n[i],e),lz(t*r,e)),i),n}(t.map(t=>t.z));return t.map((t,n)=>t.toAffine(e[n]))}static normalizeZ(t){return $F.toAffineBatch(t).map($F.fromAffine)}equals(t){UF(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t,a=lz(r*r),l=lz(o*o),c=lz(e*l),u=lz(i*a),h=lz(lz(n*o)*l),d=lz(lz(s*r)*a);return c===u&&h===d}negate(){return new $F(this.x,lz(-this.y),this.z)}double(){const{x:t,y:e,z:n}=this,r=lz(t*t),i=lz(e*e),s=lz(i*i),o=t+i,a=lz(AF*(lz(o*o)-r-s)),l=lz(OF*r),c=lz(l*l),u=lz(c-AF*a),h=lz(l*(a-u)-FF*s),d=lz(AF*e*n);return new $F(u,h,d)}add(t){UF(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t;if(i===IF||s===IF)return this;if(e===IF||n===IF)return t;const a=lz(r*r),l=lz(o*o),c=lz(e*l),u=lz(i*a),h=lz(lz(n*o)*l),d=lz(lz(s*r)*a),p=lz(u-c),f=lz(d-h);if(p===IF)return f===IF?this.double():$F.ZERO;const g=lz(p*p),m=lz(p*g),y=lz(c*g),v=lz(f*f-m-AF*y),b=lz(f*(y-v)-h*m),w=lz(r*o*p);return new $F(v,b,w)}subtract(t){return this.add(t.negate())}multiplyUnsafe(t){const e=$F.ZERO;if("bigint"==typeof t&&t===IF)return e;let n=az(t);if(n===PF)return this;if(!BF){let t=e,r=this;for(;n>IF;)n&PF&&(t=t.add(r)),r=r.double(),n>>=PF;return t}let{k1neg:r,k1:i,k2neg:s,k2:o}=NF.splitScalar(n),a=e,l=e,c=this;for(;i>IF||o>IF;)i&PF&&(a=a.add(c)),o&PF&&(l=l.add(c)),c=c.double(),i>>=PF,o>>=PF;return r&&(a=a.negate()),s&&(l=l.negate()),l=new $F(lz(l.x*NF.beta),l.y,l.z),a.add(l)}precomputeWindow(t){const e=BF?128/t+1:256/t+1,n=[];let r=this,i=r;for(let s=0;s>=u,n>a&&(n-=c,t+=PF);const o=e,d=e+Math.abs(n)-1,p=h%2!=0,f=n<0;0===n?s=s.add(qF(p,r[o])):i=i.add(qF(f,r[d]))}return{p:i,f:s}}multiply(t,e){let n,r,i=az(t);if(BF){const{k1neg:t,k1:s,k2neg:o,k2:a}=NF.splitScalar(i);let{p:l,f:c}=this.wNAF(s,e),{p:u,f:h}=this.wNAF(a,e);l=qF(t,l),u=qF(o,u),u=new $F(lz(u.x*NF.beta),u.y,u.z),n=l.add(u),r=c.add(h)}else{const{p:t,f:s}=this.wNAF(i,e);n=t,r=s}return $F.normalizeZ([n,r])[0]}toAffine(t){const{x:e,y:n,z:r}=this,i=this.equals($F.ZERO);null==t&&(t=i?FF:uz(r));const s=t,o=lz(s*s),a=lz(o*s),l=lz(e*o),c=lz(n*a),u=lz(r*s);if(i)return WF.ZERO;if(u!==PF)throw new Error("invZ was invalid");return new WF(l,c)}}function qF(t,e){const n=e.negate();return t?n:e}$F.BASE=new $F(zF.Gx,zF.Gy,PF),$F.ZERO=new $F(IF,PF,IF);const VF=new WeakMap;let WF=class t{constructor(t,e){this.x=t,this.y=e}_setWindowSize(t){this._WINDOW_SIZE=t,VF.delete(this)}hasEvenY(){return this.y%AF===IF}static fromCompressedHex(e){const n=32===e.length,r=sz(n?e:e.subarray(1));if(!dz(r))throw new Error("Point is not on curve");let i=function(t){const{P:e}=zF,n=BigInt(6),r=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=t*t*t%e,c=l*l*t%e,u=cz(c,OF)*c%e,h=cz(u,OF)*c%e,d=cz(h,AF)*l%e,p=cz(d,r)*d%e,f=cz(p,i)*p%e,g=cz(f,o)*f%e,m=cz(g,a)*g%e,y=cz(m,o)*f%e,v=cz(y,OF)*c%e,b=cz(v,s)*p%e,w=cz(b,n)*l%e,_=cz(w,AF);if(_*_%e!==t)throw new Error("Cannot find square root");return _}(jF(r));const s=(i&PF)===PF;n?s&&(i=lz(-i)):!(1&~e[0])!==s&&(i=lz(-i));const o=new t(r,i);return o.assertValidity(),o}static fromUncompressedHex(e){const n=sz(e.subarray(1,33)),r=sz(e.subarray(33,65)),i=new t(n,r);return i.assertValidity(),i}static fromHex(t){const e=oz(t),n=e.length,r=e[0];if(32===n)return this.fromCompressedHex(e);if(33===n&&(2===r||3===r))return this.fromCompressedHex(e);if(65===n&&4===r)return this.fromUncompressedHex(e);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return t.BASE.multiply(function(t){let e;if("bigint"==typeof t)e=t;else if("number"==typeof t&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if("string"==typeof t){if(64!==t.length)throw new Error("Expected 32 bytes of private key");e=iz(t)}else{if(!ZF(t))throw new TypeError("Expected valid private key");if(32!==t.length)throw new Error("Expected 32 bytes of private key");e=sz(t)}if(!hz(e))throw new Error("Expected private key: 0 < key < n");return e}(e))}static fromSignature(e,n,r){const{r:i,s:s}=function(t){if(t instanceof KF)return t.assertValidity(),t;try{return KF.fromDER(t)}catch(v5){return KF.fromCompact(t)}}(n);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const o=function(t,e=!1){const n=function(t){const e=8*t.length-256,n=sz(t);return e>0?n>>BigInt(e):n}(t);if(e)return n;const{n:r}=zF;return n>=r?n-r:n}(oz(e)),{n:a}=zF,l=2===r||3===r?i+a:i,c=uz(l,a),u=lz(-o*c,a),h=lz(s*c,a),d=1&r?"03":"02",p=t.fromHex(d+nz(l)),f=t.BASE.multiplyAndAddUnsafe(p,u,h);if(!f)throw new Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(t=!1){return tz(this.toHex(t))}toHex(t=!1){const e=nz(this.x);return t?`${this.hasEvenY()?"02":"03"}${e}`:`04${e}${nz(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const t="Point is not on elliptic curve",{x:e,y:n}=this;if(!dz(e)||!dz(n))throw new Error(t);const r=lz(n*n);if(lz(r-jF(e))!==IF)throw new Error(t)}equals(t){return this.x===t.x&&this.y===t.y}negate(){return new t(this.x,lz(-this.y))}double(){return $F.fromAffine(this).double().toAffine()}add(t){return $F.fromAffine(this).add($F.fromAffine(t)).toAffine()}subtract(t){return this.add(t.negate())}multiply(t){return $F.fromAffine(this).multiply(t,this).toAffine()}multiplyAndAddUnsafe(e,n,r){const i=$F.fromAffine(this),s=n===IF||n===PF||this!==t.BASE?i.multiplyUnsafe(n):i.multiply(n),o=$F.fromAffine(e).multiplyUnsafe(r),a=s.add(o);return a.equals($F.ZERO)?void 0:a.toAffine()}};function HF(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function GF(t){if(t.length<2||2!==t[0])throw new Error(`Invalid signature integer tag: ${XF(t)}`);const e=t[1],n=t.subarray(2,e+2);if(!e||n.length!==e)throw new Error("Invalid signature integer: wrong length");if(0===n[0]&&n[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:sz(n),left:t.subarray(e+2)}}WF.BASE=new WF(zF.Gx,zF.Gy),WF.ZERO=new WF(IF,IF);class KF{constructor(t,e){this.r=t,this.s=e,this.assertValidity()}static fromCompact(t){const e=ZF(t),n="Signature.fromCompact";if("string"!=typeof t&&!e)throw new TypeError(`${n}: Expected string or Uint8Array`);const r=e?XF(t):t;if(128!==r.length)throw new Error(`${n}: Expected 64-byte hex`);return new KF(iz(r.slice(0,64)),iz(r.slice(64,128)))}static fromDER(t){const e=ZF(t);if("string"!=typeof t&&!e)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:n,s:r}=function(t){if(t.length<2||48!=t[0])throw new Error(`Invalid signature tag: ${XF(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");const{data:e,left:n}=GF(t.subarray(2)),{data:r,left:i}=GF(n);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${XF(i)}`);return{r:e,s:r}}(e?t:tz(t));return new KF(n,r)}static fromHex(t){return this.fromDER(t)}assertValidity(){const{r:t,s:e}=this;if(!hz(t))throw new Error("Invalid Signature: r must be 0 < r < n");if(!hz(e))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const t=zF.n>>PF;return this.s>t}normalizeS(){return this.hasHighS()?new KF(this.r,lz(-this.s,zF.n)):this}toDERRawBytes(){return tz(this.toDERHex())}toDERHex(){const t=HF(rz(this.s)),e=HF(rz(this.r)),n=t.length/2,r=e.length/2,i=rz(n),s=rz(r);return`30${rz(r+n+4)}02${s}${e}02${i}${t}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return tz(this.toCompactHex())}toCompactHex(){return nz(this.r)+nz(this.s)}}function ZF(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}const YF=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function XF(t){!function(t){if(!ZF(t))throw new Error("Uint8Array expected")}(t);let e="";for(let n=0;n=JF._0&&t<=JF._9?t-JF._0:t>=JF.A&&t<=JF.F?t-(JF.A-10):t>=JF.a&&t<=JF.f?t-(JF.a-10):void 0}function tz(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i0)return BigInt(t);if("bigint"==typeof t&&hz(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function lz(t,e=zF.P){const n=t%e;return n>=IF?n:e+n}function cz(t,e){const{P:n}=zF;let r=t;for(;e-- >IF;)r*=r,r%=n;return r}function uz(t,e=zF.P){if(t===IF||e<=IF)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=lz(t,e),r=e,i=IF,s=PF;for(;n!==IF;){const t=r%n,e=i-s*(r/n);r=n,n=t,i=s,s=e}if(r!==PF)throw new Error("invert: does not exist");return lz(i,e)}function hz(t){return IFt.charCodeAt(0)))}class vz{log=ZA.extend("SerialPortSigner");writer=null;pubkey;get isConnected(){return!!this.writer}verifyEvent=IL;nip04;constructor(){this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)}}lastCommand=null;async callMethodOnDevice(t,e,n={}){if(!vz.SUPPORTED)throw new Error("Serial devices are not supported");if(this.writer||await this.connectToDevice(n),this.lastCommand)throw new Error("Previous command to device still pending!");const r=CF();return this.lastCommand=r,this.sendCommand(t,e),setTimeout(()=>{r.reject(new Error("Device timeout")),this.lastCommand===r&&(this.lastCommand=null)},6e3),this.lastCommand}async connectToDevice({onConnect:t,onDisconnect:e,onError:n,onDone:r}){let i,s=await window.navigator.serial.requestPort();await s.open({baudRate:9600}),await new Promise(t=>setTimeout(t,1e3)),(async()=>{for(;s&&s.readable;){const t=new window.TextDecoderStream;s.readable.pipeTo(t.writable),i=t.readable.getReader();const e=this.readFromSerialPort(i);try{for(;;){const{value:t,done:n}=await e("\n");if(t){const{method:e,data:n}=this.parseResponse(t);if("/ping"===e&&this.log("Pong"),-1===vz.PUBLIC_METHODS.indexOf(e))continue;this.log("Received: ",e,n),this.lastCommand&&(this.lastCommand.resolve(n),this.lastCommand=null)}if(n)return this.lastCommand=null,this.writer=null,void(r&&r())}}catch(v5){if(v5 instanceof Error)throw this.writer=null,n&&n(v5),this.lastCommand&&(this.lastCommand.reject(v5),this.lastCommand=null),v5}}})();const o=new window.TextEncoderStream;o.readable.pipeTo(s.writable),this.writer=o.writable.getWriter(),await this.sendCommand(vz.METHOD_PING),await this.sendCommand(vz.METHOD_PING,[window.location.host]),t&&t(),s.addEventListener("disconnect",()=>{this.log("Disconnected"),this.lastCommand=null,this.writer=null,e&&e()})}async sendCommand(t,e=[]){if(!this.writer)return;this.log("Send command",t,e);const n=[t].concat(e).join(" ");await this.writer.write(n+"\n")}readFromSerialPort(t){let e,n=[];return async(r="\n")=>{if(n.length)return{value:n.shift().trim(),done:!1};const i=[];for(e&&(i.push(e),e=void 0);;){const{value:s,done:o}=await t.read();if(s){const t=s.split(r);if(t.length>1)return i.push(t.shift()),e=t.pop(),n=t,{value:i.join("").trim(),done:!1};i.push(s)}if(o)return{value:i.join("").trim(),done:!0}}}}parseResponse(t){const e=t.split(" ")[0];return{method:e,data:t.substring(e.length).trim()}}async nip04Encrypt(t,e){const n=bS(await this.callMethodOnDevice(vz.METHOD_SHARED_SECRET,[pz(t)]));let r=Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(16))),i=gz.encode(e),s=await crypto.subtle.importKey("raw",n,{name:"AES-CBC"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-CBC",iv:r},s,i);return`${mz(new Uint8Array(o))}?iv=${mz(new Uint8Array(r.buffer))}`}async nip04Decrypt(t,e){let[n,r]=e.split("?iv=");const i=bS(await this.callMethodOnDevice(vz.METHOD_SHARED_SECRET,[pz(t)]));let s=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["decrypt"]),o=yz(n),a=yz(r),l=await crypto.subtle.decrypt({name:"AES-CBC",iv:a},s,o);return fz.decode(l)}async getPublicKey(){const t=await this.callMethodOnDevice(vz.METHOD_PUBLIC_KEY,[]);return this.pubkey=t,t}async restore(t){await this.callMethodOnDevice(vz.METHOD_RESTORE,[vS(t)])}async signEvent(t){const e=t.pubkey||this.pubkey;if(!e)throw new Error("Unknown signer pubkey");const n={...t,id:EL({...t,pubkey:e})},r=await this.callMethodOnDevice(vz.METHOD_SIGN_MESSAGE,[n.id]),i={...n,sig:r,pubkey:e};if(!this.verifyEvent(i))throw new Error("Invalid signature");return i}ping(){this.sendCommand(vz.METHOD_PING,[window.location.host])}static SUPPORTED="navigator"in globalThis&&!!navigator.serial;static METHOD_PING="/ping";static METHOD_LOG="/log";static METHOD_SIGN_MESSAGE="/sign-message";static METHOD_SHARED_SECRET="/shared-secret";static METHOD_PUBLIC_KEY="/public-key";static METHOD_RESTORE="/restore";static PUBLIC_METHODS=[vz.METHOD_PUBLIC_KEY,vz.METHOD_SIGN_MESSAGE,vz.METHOD_SHARED_SECRET,vz.METHOD_RESTORE]}function bz(){return"undefined"!=typeof navigator&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)}const wz=Object.freeze(Object.defineProperty({__proto__:null,isMobile:bz},Symbol.toStringTag,{value:"Module"})),_z="marco:nostr_pubkey",xz="marco:nostr_signer_type",Cz="marco:nostr_connect_local_key",Sz="marco:nostr_connect_remote_pubkey",kz="marco:nostr_connect_relay",Ez="wss://relay.nsec.app";class Tz extends qf{static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"pubkey",[Is],function(){return null})}#H=void fF(this,"pubkey");static{dF(this.prototype,"signerType",[Is],function(){return null})}#G=void fF(this,"signerType");static{dF(this.prototype,"connectStatus",[Is],function(){return null})}#K=void fF(this,"connectStatus");static{dF(this.prototype,"connectUri",[Is],function(){return null})}#Z=void fF(this,"connectUri");_signerInstance=null;constructor(){super(...arguments),"undefined"!=typeof localStorage&&(localStorage.debug="applesauce:*");const t=localStorage.getItem(_z),e=localStorage.getItem(xz);t&&(this.pubkey=t,this.signerType=e||"extension",this._verifyPubkey())}async _verifyPubkey(){if("extension"===this.signerType){if(void 0===window.nostr)return void this.disconnect();try{const t=new kF,e=await t.getPublicKey();e!==this.pubkey&&(this.pubkey=e,localStorage.setItem(_z,this.pubkey)),this.nostrData.loadProfile(this.pubkey)}catch(ej){console.warn("Failed to verify extension nostr pubkey, logging out",ej),this.disconnect()}}else if("connect"===this.signerType)try{await this._initConnectSigner()}catch(ej){console.warn("Failed to verify connect nostr pubkey, logging out",ej),this.disconnect()}}get isMobile(){return bz()}get isConnected(){return!!this.pubkey&&("extension"!==this.signerType||void 0!==window.nostr)}get signer(){return this._signerInstance?this._signerInstance:"extension"===this.signerType&&void 0!==window.nostr?new kF:(this.signerType,null)}async connectWithExtension(){if(void 0===window.nostr)throw new Error("No NIP-07 Nostr extension found (e.g., Alby, nos2x).");try{return this._signerInstance=new kF,this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="extension",localStorage.setItem(_z,this.pubkey),localStorage.setItem(xz,"extension"),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(v5){throw console.error("Failed to get public key from extension:",v5),v5}}_getLocalSigner(){let t,e=localStorage.getItem(Cz);return e?t=RF.fromKey(e):(t=new RF,e=Array.from(t.key).map(t=>t.toString(16).padStart(2,"0")).join(""),localStorage.setItem(Cz,e)),t}async connectWithApp(){this.connectStatus="waiting";try{const e=this._getLocalSigner(),n=Ez;localStorage.setItem(kz,n),this.nostrRelay.pool.relay(n).eoseTimeout=18e4,this._signerInstance=new LF({pool:this.nostrRelay.pool,relays:[n],signer:e,onAuth:async t=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${t}`)&&window.open(t,"_blank")}}),this.connectUri=this._signerInstance.getNostrConnectURI({name:"Marco",url:window.location.origin,description:"An unhosted maps application.",icons:[]}),this.isMobile&&(console.debug("Mobile detected, triggering deep link intent."),window.location.href=this.connectUri),console.debug("Opening signer connection to relay..."),await this._signerInstance.open(),console.debug("Signer connection opened successfully."),console.debug("Waiting for remote signer to ack via relay...");try{await this._signerInstance.waitForSigner(),console.debug("Remote signer ack received!")}catch(t){throw console.error("Error while waiting for remote signer ack:",t),t}return this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="connect",this.connectStatus="connected",localStorage.setItem(_z,this.pubkey),localStorage.setItem(xz,"connect"),localStorage.setItem(Sz,this._signerInstance.remote),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(v5){throw this.connectStatus=null,console.error("Failed to connect via Nostr Connect:",v5),v5}}async _initConnectSigner(){const t=localStorage.getItem(Sz),e=localStorage.getItem(kz)||Ez;if(!t)throw new Error("Missing Nostr Connect remote pubkey.");const n=this._getLocalSigner();if(this.nostrRelay.pool.relay(e).eoseTimeout=18e4,this._signerInstance=new LF({pool:this.nostrRelay.pool,relays:[e],signer:n,remote:t,onAuth:async t=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${t}`)&&window.open(t,"_blank")}}),await this._signerInstance.open(),await this._signerInstance.getPublicKey()!==this.pubkey)throw new Error("Remote signer pubkey mismatch");this.nostrData.loadProfile(this.pubkey)}async signEvent(t){if(!this.signer)throw new Error("Not connected or extension missing. Please connect Nostr again.");return await this.signer.signEvent(t)}async disconnect(){this.pubkey=null,this.nostrData?.loadProfile(null),this.signerType=null,this.connectStatus=null,this.connectUri=null,this._signerInstance&&"function"==typeof this._signerInstance.close&&await this._signerInstance.close(),this._signerInstance=null,localStorage.removeItem(_z),localStorage.removeItem(xz),localStorage.removeItem(Cz),localStorage.removeItem(Sz),localStorage.removeItem(kz)}}const Rz=Object.freeze(Object.defineProperty({__proto__:null,default:Tz},Symbol.toStringTag,{value:"Module"})),Mz=(t,e)=>e.some(e=>t instanceof e);let Lz,Iz;const Pz=new WeakMap,Az=new WeakMap,Oz=new WeakMap;let Fz={get(t,e,n){if(t instanceof IDBTransaction){if("done"===e)return Pz.get(t);if("store"===e)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Dz(t[e])},set:(t,e,n)=>(t[e]=n,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function zz(t){Fz=t(Fz)}function Dz(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,n)=>{const r=()=>{t.removeEventListener("success",i),t.removeEventListener("error",s)},i=()=>{e(Dz(t.result)),r()},s=()=>{n(t.error),r()};t.addEventListener("success",i),t.addEventListener("error",s)});return Oz.set(e,t),e}(t);if(Az.has(t))return Az.get(t);const e=function(t){return"function"==typeof t?(e=t,(Iz||(Iz=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Nz(this),t),Dz(this.request)}:function(...t){return Dz(e.apply(Nz(this),t))}):(t instanceof IDBTransaction&&function(t){if(Pz.has(t))return;const e=new Promise((e,n)=>{const r=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",s),t.removeEventListener("abort",s)},i=()=>{e(),r()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),r()};t.addEventListener("complete",i),t.addEventListener("error",s),t.addEventListener("abort",s)});Pz.set(t,e)}(t),Mz(t,Lz||(Lz=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,Fz):t);var e}(t);return e!==t&&(Az.set(t,e),Oz.set(e,t)),e}const Nz=t=>Oz.get(t),jz=["get","getKey","getAll","getAllKeys","count"],Bz=["put","add","delete","clear"],Uz=new Map;function $z(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(Uz.get(e))return Uz.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,i=Bz.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!jz.includes(n))return;const s=async function(t,...e){const s=this.transaction(t,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(e.shift())),(await Promise.all([o[n](...e),i&&s.done]))[0]};return Uz.set(e,s),s}zz(t=>({...t,get:(e,n,r)=>$z(e,n)||t.get(e,n,r),has:(e,n)=>!!$z(e,n)||t.has(e,n)}));const qz=["continue","continuePrimaryKey","advance"],Vz={},Wz=new WeakMap,Hz=new WeakMap,Gz={get(t,e){if(!qz.includes(e))return t[e];let n=Vz[e];return n||(n=Vz[e]=function(...t){Wz.set(this,Hz.get(this)[e](...t))}),n}};async function*Kz(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;const n=new Proxy(e,Gz);for(Hz.set(n,e),Oz.set(n,Nz(e));e;)yield n,e=await(Wz.get(n)||e.continue()),Wz.delete(n)}function Zz(t,e){return e===Symbol.asyncIterator&&Mz(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===e&&Mz(t,[IDBIndex,IDBObjectStore])}function Yz(t){return 0===t||3===t||t>=1e4&&t<2e4}function Xz(t){return t>=3e4&&t<4e4}function Jz(t){return t>=2e4&&t<3e4}zz(t=>({...t,get:(e,n,r)=>Zz(e,n)?Kz:t.get(e,n,r),has:(e,n)=>Zz(e,n)||t.has(e,n)}));const Qz=Symbol.for("indexable-tags");function tD(t,e){if(t.ids&&-1===t.ids.indexOf(e.id))return!1;if(t.kinds&&-1===t.kinds.indexOf(e.kind))return!1;if(t.authors&&-1===t.authors.indexOf(e.pubkey))return!1;if(t.since&&e.created_att.until)return!1;const n=function(t){let e=Reflect.get(t,Qz);if(!e){e=new Set;for(const n of t.tags)n.length>=2&&1===n[0].length&&e.add(n[0]+":"+n[1]);Reflect.set(t,Qz,e)}return e}(e);for(const r in t)if("&"===r[0]){const e=r.slice(1),i=t[r];if(i&&i.length>0)for(const t of i)if(!n.has(e+":"+t))return!1}for(const r in t)if("#"===r[0]){const e=r.slice(1),i=t[r];if(i){const r=t[`&${e}`],s=r?i.filter(t=>!r.includes(t)):i;if(0===s.length)continue;if(!s.some(t=>n.has(e+":"+t)))return!1}}return!0}function eD(t,e){for(let n=0;nt.length>=2&&1===t[0].length&&rD.includes(t[0])).map(t=>t[0]+t[1])}function oD(t){if(Reflect.has(t,iD))return Reflect.get(t,iD);let e;if(Yz(t.kind)||Xz(t.kind)){const n=t.tags.find(t=>"d"===t[0])?.[1];e=t.kind+":"+t.pubkey+":"+(n??"")}else e=t.id;return Reflect.set(t,iD,e),e}async function aD(t="nostr-idb",e){return await function(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(t,e),a=Dz(o);return r&&o.addEventListener("upgradeneeded",t=>{r(Dz(o.result),t.oldVersion,t.newVersion,Dz(o.transaction),t)}),n&&o.addEventListener("blocked",t=>n(t.oldVersion,t.newVersion,t)),a.then(t=>{s&&t.addEventListener("close",()=>s()),i&&t.addEventListener("versionchange",t=>i(t.oldVersion,t.newVersion,t))}).catch(()=>{}),a}(t,3,{...e,async upgrade(t,e,n,r,i){if(0===e){const e=t.createObjectStore("events");e.createIndex("id","event.id",{unique:!0}),e.createIndex("pubkey","event.pubkey"),e.createIndex("kind","event.kind"),e.createIndex("created_at","event.created_at"),e.createIndex("tags","tags",{multiEntry:!0}),t.createObjectStore("used",{keyPath:"uid"}).createIndex("date","date")}1===e&&(t.deleteObjectStore("events"),t.deleteObjectStore("used"),t.deleteObjectStore("seen")),e<=2&&await async function(t){const e=t.objectStore("events");let n=await e.openCursor();const r=[];for(;n;){const t=n.primaryKey,e=n.value,i=e.event;if(Yz(i.kind)||Xz(i.kind)){const n=oD(i);t!==n&&r.push({oldKey:t,newKey:n,value:e})}n=await n.continue()}for(const{oldKey:i,newKey:s,value:o}of r)await e.delete(i),await e.put(o,s)}(r)}})}function lD(t,e){return e.created_at-t.created_at}function cD(t,e=[],n){const r=[],i=new Set;if(n)for(const l of e){const t=n.getPubkeyIndex(l);if(t){for(const e of t)i.add(e);r.push(l)}}if(r.length===e.length)return Promise.resolve(i);const s=t.transaction("events","readonly"),o=s.objectStore("events").index("pubkey"),a=e.filter(t=>!r.includes(t)).map(t=>o.getAllKeys(t).then(e=>((t,e)=>{for(const n of e)i.add(n);n&&n.setPubkeyIndex(t,new Set(e))})(t,e)));return s.commit(),Promise.all(a).then(()=>i)}function uD(t,e,n,r){const i=[],s=new Set;if(r)for(const c of n){const t=r.getTagIndex(e+c);if(t){for(const e of t)s.add(e);i.push(c)}}if(i.length===n.length)return Promise.resolve(s);const o=t.transaction("events","readonly"),a=o.objectStore("events").index("tags"),l=n.map(t=>a.getAllKeys(e+t).then(n=>((t,n)=>{for(const e of n)s.add(e);r&&r.setTagIndex(e+t,new Set(n))})(t,n)));return o.commit(),Promise.all(l).then(()=>s)}function hD(t,e,n,r){if(0===n.length)return Promise.resolve(new Set);if(1===n.length)return uD(t,e,n,r);const i=[],s=[];if(r)for(const c of n){const t=r.getTagIndex(e+c);t&&(s.push(t),i.push(c))}if(i.length===n.length)return Promise.resolve(dD(s));const o=t.transaction("events","readonly"),a=o.objectStore("events").index("tags"),l=n.filter(t=>!i.includes(t)).map(t=>a.getAllKeys(e+t).then(n=>((t,n)=>{const i=new Set(n);s.push(i),r&&r.setTagIndex(e+t,i)})(t,n)));return o.commit(),Promise.all(l).then(()=>dD(s))}function dD(t){if(0===t.length)return new Set;const e=t.slice().sort((t,e)=>t.size-e.size);let n=e[0];for(let r=1;r!r.includes(t)).map(t=>o.getAllKeys(t).then(e=>((t,e)=>{for(const n of e)i.add(n);n&&n.setKindIndex(t,new Set(e))})(t,e)));return s.commit(),Promise.all(a).then(()=>i)}async function fD(t,e,n){let r;if(void 0!==e&&void 0!==n)r=IDBKeyRange.bound(e,n);else if(void 0!==e)r=IDBKeyRange.lowerBound(e);else{if(void 0===n)throw new Error("Missing since or until");r=IDBKeyRange.upperBound(n)}return(await t.getAllKeysFromIndex("events","created_at",r)).reverse()}async function gD(t,e,n){if(e.search)return new Set;if(e.ids)return new Set(e.ids);let r=null;const i=t=>{const e=t instanceof Set?t:new Set(t);if(r)for(const n of r)e.has(n)||r.delete(n);else r=e;return r};let s=null;void 0!==e.since&&(s=await fD(t,e.since,e.until),i(s));for(const o of rD){const r=e[`&${o}`],s=e[`#${o}`];if(r?.length&&i(await hD(t,o,r,n)),s?.length){const e=r?.length?s.filter(t=>!r.includes(t)):s;e.length>0&&i(await uD(t,o,e,n))}}if(e.authors&&i(await cD(t,e.authors,n)),e.kinds&&i(await pD(t,e.kinds,n)),void 0===e.since&&void 0!==e.until&&(s=await fD(t,e.since,e.until),i(s)),e.limit&&s){const t=new Set;for(const n of s){if(t.size>=e.limit)break;r.has(n)&&t.add(n)}return t}if(null===r)throw new Error("Empty filter");return r}async function mD(t,e,n){if(0===e.length)throw new Error("No Filters");let r=new Set;for(const i of e){const e=await gD(t,i,n);for(const t of e)r.add(t)}return r}async function yD(t,e,n,r){const i=await mD(t,e,n);return await async function(t,e,n,r){const i=[];let s=[];if(r)for(const d of e){const t=r.get(d);t?i.push(t):s.push(d)}else s=e;const o=t.transaction("events","readonly"),a=o.objectStore("events"),l=t=>t&&i.push(t.event),c=Array.from(s).map(t=>a.get(t).then(l));o.commit();const u=await Promise.all(c).then(()=>i.sort(lD));let h=1/0;for(const d of n)d.limit&&d.limith&&(u.length=h),u}(t,Array.from(i),e,r)}async function vD(t,e,n){return(await mD(t,e,n)).size}const bD=Object.freeze(Object.defineProperty({__proto__:null,countEventsForFilters:vD,getEventsForFilters:yD,getIdsForFilter:gD,getIdsForFilters:mD,queryForKinds:pD,queryForPubkeys:cD,queryForTag:uD,queryForTagAnd:hD,queryForTime:fD},Symbol.toStringTag,{value:"Module"})),wD=KA("nostr-idb"),_D=wD.extend("prune");async function xD(t,e,n){const r=t.transaction("events","readwrite"),i=r.objectStore("events"),s=await i.get(e);if(!s)return await r.commit(),!1;if(await i.delete(e),await r.commit(),n){const t=s.event;n.removeEvent(t)}return!0}const CD=wD.extend("WriteQueue");class SD{db;queuedIds=new Set;eventQueue=[];lastUsedQueue=new Set;processEvents=null;constructor(t){this.db=t}addEvent(t){this.queuedIds.has(t.id)||(this.eventQueue.push(t),this.queuedIds.add(t.id),this.touch(t))}addEvents(t){const e=t.filter(t=>!this.queuedIds.has(t.id));0!==e.length&&(this.eventQueue.push(...e),this.touch(e))}touch(t){if(Array.isArray(t))for(const e of t)this.lastUsedQueue.add(oD(e));else this.lastUsedQueue.add(oD(t))}matchPending(t){return this.eventQueue.filter(e=>eD(t,e))}async flush(t=1e3){if(this.eventQueue.length>0){let e=[];for(let n=0;nfunction(t){if("object"!=typeof t||null===t)return!1;if("number"!=typeof t.kind)return!1;if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if("string"!=typeof t.pubkey)return!1;if(!/^[a-f0-9]{64}$/.test(t.pubkey))return!1;if(!Array.isArray(t.tags))return!1;for(const e of t.tags){if(!Array.isArray(e))return!1;for(const t of e)if("string"!=typeof t)return!1}return!0}(t))).filter(t=>Yz(t.kind)||Xz(t.kind)),r={};if(n.length>0){const e=t.transaction("events","readonly"),i=n.map(t=>{const n=oD(t);return e.store.get(n).then(t=>t&&(r[n]=t.event.created_at))});e.commit(),await Promise.all(i)}const i=t.transaction("events","readwrite");for(const s of e){const t=oD(s);(!r[t]||s.created_at>r[t])&&i.objectStore("events").put({event:s,tags:sD(s)},t)}await i.commit()}(this.db,e),CD(`Wrote ${e.length} to database`),this.eventQueue.length>0&&CD(`${this.eventQueue.length} left`)}this.lastUsedQueue.size>0&&(await async function(t,e){const n=t.transaction("used","readwrite"),r=Math.floor((new Date).valueOf()/1e3);for(const i of e)n.objectStore("used").put({uid:i,date:r});await n.commit()}(this.db,this.lastUsedQueue),this.lastUsedQueue.clear())}clear(){this.eventQueue=[]}}const kD=wD.extend("cache:indexes");class ED extends Set{type;key;constructor(t,e,n){super(t),this.type=e,this.key=n}}class TD{kinds=new Map;pubkeys=new Map;tags=new Map;get count(){return this.kinds.size+this.pubkeys.size+this.tags.size}max=1e3;lastUsed=[];useIndex(t){const e=this.lastUsed.indexOf(t);-1!==e&&this.lastUsed.splice(e,e+1),this.lastUsed.push(t)}getKindIndex(t){const e=this.kinds.get(t);return e&&this.useIndex(e),e}setKindIndex(t,e){const n=new ED(e,"kind",t);this.kinds.set(t,n),this.useIndex(n),this.pruneIndexes()}getPubkeyIndex(t){const e=this.pubkeys.get(t);return e&&this.useIndex(e),e}setPubkeyIndex(t,e){const n=new ED(e,"pubkey",t);this.pubkeys.set(t,n),this.useIndex(n),this.pruneIndexes()}getTagIndex(t){const e=this.tags.get(t);return e&&this.useIndex(e),e}setTagIndex(t,e){const n=new ED(e,"tag",t);this.tags.set(t,n),this.useIndex(n),this.pruneIndexes()}addEventToIndexes(t){this.getKindIndex(t.kind)?.add(t.id),this.getPubkeyIndex(t.pubkey)?.add(t.id);const e=sD(t);for(const n of e)this.getTagIndex(n)?.add(t.id)}removeEvent(t){this.getKindIndex(t.kind)?.delete(t.id),this.getPubkeyIndex(t.pubkey)?.delete(t.id);const e=sD(t);for(const n of e)this.getTagIndex(n)?.delete(t.id)}clear(){this.kinds.clear(),this.pubkeys.clear(),this.tags.clear(),this.lastUsed=[]}pruneIndexes(){for(;this.lastUsed.length>0&&this.lastUsed.length>this.max;){const t=this.lastUsed.shift();if(!t)return;switch(kD(`Forgetting ${t.type}:${t.key}`),t.type){case"kind":this.kinds.delete(t.key);break;case"pubkey":this.pubkeys.delete(t.key);break;case"tag":this.tags.delete(t.key)}}}}const RD={},MD=function(t,e){let n=Promise.resolve();if(e&&e.length>0){document.getElementsByTagName("link");const t=document.querySelector("meta[property=csp-nonce]"),i=t?.nonce||t?.getAttribute("nonce");r=e.map(t=>{if((t=function(t){return"/"+t}(t))in RD)return;RD[t]=!0;const e=t.endsWith(".css"),n=e?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${t}"]${n}`))return;const r=document.createElement("link");return r.rel=e?"stylesheet":"modulepreload",e||(r.as="script"),r.crossOrigin="",r.href=t,i&&r.setAttribute("nonce",i),document.head.appendChild(r),e?new Promise((e,n)=>{r.addEventListener("load",e),r.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${t}`)))}):void 0}),n=Promise.all(r.map(t=>Promise.resolve(t).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var r;function i(t){const e=new Event("vite:preloadError",{cancelable:!0});if(e.payload=t,window.dispatchEvent(e),!e.defaultPrevented)throw t}return n.then(e=>{for(const t of e||[])"rejected"===t.status&&i(t.reason);return t().catch(i)})},LD={batchWrite:1e3,writeInterval:100,cacheIndexes:1e3,pruneInterval:6e4,maxEvents:1e4},ID=wD.extend("nostridb");class PD{options;running=!1;writeInterval;pruneInterval;eventMap=new Map;writeQueue=null;indexCache;db=null;baseEoseTimeout=4400;subscriptions=new Map;constructor(t,e={}){this.options={...LD,...e},t&&(this.db=t,this.writeQueue=new SD(t)),this.indexCache=new TD,this.indexCache.max=this.options.cacheIndexes,this.start()}async getDb(){return this.db||(this.db=await aD()),this.db}async getWriteQueue(){if(this.writeQueue)return this.writeQueue;const t=await this.getDb();return this.writeQueue=new SD(t),this.writeQueue}async flush(){const t=await this.getWriteQueue();await t.flush(),this.writeInterval=setTimeout(this.flush.bind(this),this.options.writeInterval)}async start(){if(this.running)return;ID("Starting"),this.running=!0;const t=await this.getDb();await this.flush(),this.pruneInterval=setInterval(()=>{!async function(t,e){const n=await function(t){return t.transaction("events","readonly").store.count()}(t);if(n<=e)return;const r=n-e;if(r<=0)return;_D(`Pruning database to ${e}`);const i=(await t.getAll("used")).sort((t,e)=>t.date-e.date),s=[];let o=r;for(const u of i){if(o<=0)break;const t=u.uid;s.push(t),o--}if(0===s.length)return;const a=t.transaction("events","readwrite"),l=t.transaction("used","readwrite"),c=[];for(const u of s)c.push(a.store.delete(u)),c.push(l.store.delete(u));a.commit(),l.commit(),await Promise.all(c),_D(`Removed ${s.length} old events`)}(t,this.options.maxEvents)},this.options.pruneInterval)}async stop(){this.running&&(this.writeInterval&&(clearTimeout(this.writeInterval),this.writeInterval=void 0),this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0),this.running=!1,ID("Stopped"))}async add(t){Jz(t.kind)||((await this.getWriteQueue()).addEvent(t),this.indexCache.addEventToIndexes(t));const e=oD(t);if(!this.eventMap.has(e)){Jz(t.kind)||this.eventMap.set(e,t);for(const[e,n]of this.subscriptions)n.event&&eD(n.filters,t)&&n.event(t)}return!0}async event(t){const e=await this.getDb(),n=await e.get("events",t);return n?.event}async replaceable(t,e,n){return this.event([t,e,n??""].join(":"))}async count(t){const e=Array.isArray(t)?t:[t],n=await this.getDb();return await vD(n,e)}async query(t){const e=Array.isArray(t)?t:[t],n=await this.getDb(),r=(await this.getWriteQueue()).matchPending(e),i=await yD(n,e,this.indexCache,this.eventMap);this.addToEventMaps(i);const s=new Set(r.map(t=>t.id));return r.length>0?[...i.filter(t=>!s.has(t.id)),...r].sort(lD):i}async*subscribe(t){const e=Array.isArray(t)?t:[t],n=[],r=new Set;let i=null,s=!1;const o=this.subscribeInternal(e,{event:t=>{if(!r.has(t.id)&&(r.add(t.id),n.push(t),i)){const t=i;i=null,t()}},complete:()=>{if(s=!0,i){const t=i;i=null,t()}}});try{for(;;){for(;n.length>0;)yield n.shift();if(s)break;await new Promise(t=>{i=t})}}finally{o.close()}}async supports(){return[]}async deleteEvent(t){const e=await this.getDb(),n=await xD(e,t,this.indexCache);return this.eventMap.delete(t),n}async deleteReplaceable(t,e,n){const r=await this.getDb(),i=await async function(t,e,n,r,i){if(!Yz(n)&&!Xz(n))throw new Error(`Kind ${n} is not replaceable`);const s=`${n}:${e}:${r??""}`;return await xD(t,s,i)}(r,t,e,n,this.indexCache);if(i){const r=`${e}:${t}:${n??""}`;this.eventMap.delete(r)}return i}async deleteByFilters(t){const e=Array.isArray(t)?t:[t],n=await this.getDb(),r=await this.getEventIdsForFilters(e),i=await async function(t,e,n){const r=await mD(t,e,n);return await async function(t,e,n){if(0===e.length)return 0;const r=t.transaction("events","readwrite"),i=r.objectStore("events");let s=0;const o=[];for(const a of e){const t=await i.get(a);t&&(o.push(t.event),await i.delete(a),s++)}if(await r.commit(),n&&o.length>0)for(const a of o)n.removeEvent(a);return s}(t,Array.from(r),n)}(n,e,this.indexCache);if(i>0)for(const s of r)this.eventMap.delete(s);return i}async deleteAllEvents(){const t=await this.getDb();await async function(t,e){const n=t.transaction("events","readwrite");await n.objectStore("events").clear(),await n.commit(),e&&e.clear()}(t,this.indexCache),this.eventMap.clear()}async getEventIdsForFilters(t){const e=await this.getDb(),{getIdsForFilters:n}=await MD(async()=>{const{getIdsForFilters:t}=await Promise.resolve().then(()=>bD);return{getIdsForFilters:t}},void 0),r=await n(e,t,this.indexCache);return Array.from(r)}addToEventMaps(t){for(const e of t)this.eventMap.set(oD(e),e)}subscribeInternal(t,e){const n=((t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((t,e)=>t+((e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e>62?"-":"_"),""))(),r={id:n,filters:t,closed:!1,close:()=>this.unsubscribe(n),...e};return this.subscriptions.set(n,r),this.executeSubscription(r),r}async executeSubscription(t){const e=(new Date).valueOf();ID(`Running ${t.id}`,t.filters);const n=(await this.getWriteQueue()).matchPending(t.filters);return new Promise(async r=>{const i=await this.getDb(),s=setTimeout(()=>{t.eose&&!t.closed&&t.eose(),r()},this.baseEoseTimeout);yD(i,t.filters,this.indexCache,this.eventMap).then(i=>{if(clearTimeout(s),this.addToEventMaps(i),t.event&&!t.closed){const r=new Set(n.map(t=>t.id)),s=n.length>0?[...i.filter(t=>!r.has(t.id)),...n].sort(lD):i;for(const e of s)try{t.event(e)}catch(v5){ID("event handler failed with error",v5)}const o=(new Date).valueOf()-e;ID(`Finished ${t.id} took ${o}ms and got ${s.length} events`)}t.eose&&!t.closed&&t.eose(),r()})})}unsubscribe(t){const e=this.subscriptions.get(t);e&&(ID(`Closing ${t}`),e.closed=!0,e.complete?.(),this.subscriptions.delete(t))}}function AD(t){if(!t)return"";let e=t.trim().toLowerCase();if(!e)return"";for(e.startsWith("ws://")||e.startsWith("wss://")||(e="wss://"+e);e.endsWith("/");)e=e.slice(0,-1);return e}function OD(t){if(!t||0===t.length)return[];const e=[...t].sort((t,e)=>t.created_at-e.created_at),n=[];for(const i of e){const t=i.tags.filter(t=>"imeta"===t[0]);for(const e of t){let t=null,r=null,s=null,o=!1,a=16/9;for(const n of e.slice(1))if(n.startsWith("url "))t=n.substring(4);else if(n.startsWith("thumb "))r=n.substring(6);else if(n.startsWith("blurhash "))s=n.substring(9);else if(n.startsWith("dim ")){const t=n.substring(4),[e,r]=t.split("x").map(Number);e&&r&&(a=e/r,e>r&&(o=!0))}t&&n.push({eventId:i.id,pubkey:i.pubkey,createdAt:i.created_at,url:t,thumbUrl:r,blurhash:s,isLandscape:o,aspectRatio:a})}}if(0===n.length)return[];const r=n.findIndex(t=>t.isLandscape);if(r>0){const[t]=n.splice(r,1);n.unshift(t)}return n}const FD=Object.freeze(Object.defineProperty({__proto__:null,normalizeRelayUrl:AD,parsePlacePhotos:OD},Symbol.toStringTag,{value:"Module"})),zD="0123456789bcdefghjkmnpqrstuvwxyz";class DD{static encode(t,e,n){if(void 0===n){for(let n=1;n<=12;n++){const r=DD.encode(t,e,n),i=DD.decode(r);if(i.lat==t&&i.lon==e)return r}n=12}if(t=Number(t),e=Number(e),n=Number(n),isNaN(t)||isNaN(e)||isNaN(n))throw new Error("Invalid geohash");let r=0,i=0,s=!0,o="",a=-90,l=90,c=-180,u=180;for(;o.length=t?(r=2*r+1,c=t):(r*=2,u=t)}else{const e=(a+l)/2;t>=e?(r=2*r+1,a=e):(r*=2,l=e)}s=!s,5==++i&&(o+=zD.charAt(r),i=0,r=0)}return o}static decode(t){const e=DD.bounds(t),n=e.sw.lat,r=e.sw.lon,i=e.ne.lat,s=e.ne.lon;let o=(n+i)/2,a=(r+s)/2;return o=o.toFixed(Math.floor(2-Math.log(i-n)/Math.LN10)),a=a.toFixed(Math.floor(2-Math.log(s-r)/Math.LN10)),{lat:Number(o),lon:Number(a)}}static bounds(t){if(0==t.length)throw new Error("Invalid geohash");t=t.toLowerCase();let e=!0,n=-90,r=90,i=-180,s=180;for(let o=0;o=0;t--){const o=l>>t&1;if(e){const t=(i+s)/2;1==o?i=t:s=t}else{const t=(n+r)/2;1==o?n=t:r=t}e=!e}}return{sw:{lat:n,lon:i},ne:{lat:r,lon:s}}}static adjacent(t,e){if(t=t.toLowerCase(),e=e.toLowerCase(),0==t.length)throw new Error("Invalid geohash");if(-1=="nsew".indexOf(e))throw new Error("Invalid direction");const n=t.slice(-1);let r=t.slice(0,-1);const i=t.length%2;return-1!={n:["prxz","bcfguvyz"],s:["028b","0145hjnp"],e:["bcfguvyz","prxz"],w:["0145hjnp","028b"]}[e][i].indexOf(n)&&""!=r&&(r=DD.adjacent(r,e)),r+zD.charAt({n:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],s:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],e:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],w:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]}[e][i].indexOf(n))}static neighbours(t){return{n:DD.adjacent(t,"n"),ne:DD.adjacent(DD.adjacent(t,"n"),"e"),e:DD.adjacent(t,"e"),se:DD.adjacent(DD.adjacent(t,"s"),"e"),s:DD.adjacent(t,"s"),sw:DD.adjacent(DD.adjacent(t,"s"),"w"),w:DD.adjacent(t,"w"),nw:DD.adjacent(DD.adjacent(t,"n"),"w")}}}function ND(t){const{minLat:e,minLon:n,maxLat:r,maxLon:i}=t,s=new Set;if(Math.abs(r-e)>20||Math.abs(i-n)>20)return console.warn("BBox too large for 4-char geohash scanning, aborting fine scan."),[];for(let o=e;o<=r+.1;o+=.1)for(let t=n;t<=i+.1;t+=.1){const e=Math.min(o,r),n=Math.min(t,i);try{const t=DD.encode(e,n,4);s.add(t)}catch(ej){}}try{s.add(DD.encode(e,n,4))}catch(ej){}try{s.add(DD.encode(r,i,4))}catch(ej){}try{s.add(DD.encode(e,i,4))}catch(ej){}try{s.add(DD.encode(r,n,4))}catch(ej){}return Array.from(s)}const jD=Object.freeze(Object.defineProperty({__proto__:null,getGeohashPrefixesInBbox:ND},Symbol.toStringTag,{value:"Module"})),BD=["wss://purplepag.es","wss://relay.damus.io","wss://nos.lol"],UD=["wss://nostr.kosmos.org"],$D=[];class qD extends qf{static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");store=new VO;static{dF(this.prototype,"profile",[Is],function(){return null})}#Y=void fF(this,"profile");static{dF(this.prototype,"mailboxes",[Is],function(){return null})}#X=void fF(this,"mailboxes");static{dF(this.prototype,"blossomServers",[Is],function(){return[]})}#J=void fF(this,"blossomServers");static{dF(this.prototype,"placePhotos",[Is],function(){return[]})}#Q=void fF(this,"placePhotos");_profileSub=null;_mailboxesSub=null;_blossomSub=null;_photosSub=null;_requestSub=null;_cachePromise=null;loadedGeohashPrefixes=new Set;constructor(){super(...arguments),this._cachePromise=aD("applesauce-events").then(async t=>{this.cache=new PD(t,{cacheIndexes:1e3,maxEvents:1e4}),await this.cache.start(),this._stopPersisting=function(t,e,n){const r=n?.batchTime??5e3,i=t.insert$.pipe(mA(t=>{return e=t,!(!0===Reflect.get(e,NL));var e}),n?.maxBatchSize?yA(r,void 0,n?.maxBatchSize??100):yA(r),mA(t=>t.length>0)).subscribe(t=>{e(t).then(()=>YA(`Saved ${t.length} events to cache`)).catch(e=>YA(`Failed to save ${t.length} events to cache`,e))});return()=>i.unsubscribe()}(this.store,async t=>{const e=t.filter(t=>0===t.kind||10002===t.kind||10063===t.kind||360===t.kind);e.length>0&&await Promise.all(e.map(t=>this.cache.add(t)))},{batchTime:1e3,maxBatchSize:100})}),this.nostrRelay.pool.relays$.subscribe(()=>{})}get defaultReadRelays(){const t=(this.mailboxes?.inboxes||[]).map(AD).filter(Boolean),e=UD.map(AD).filter(Boolean);return Array.from(new Set([...e,...t]))}get defaultWriteRelays(){const t=(this.mailboxes?.outboxes||[]).map(AD).filter(Boolean),e=$D.map(AD).filter(Boolean);return Array.from(new Set([...e,...t]))}get activeReadRelays(){return this.settings.nostrReadRelays?Array.from(new Set(this.settings.nostrReadRelays.map(AD).filter(Boolean))):this.defaultReadRelays}get activeWriteRelays(){return this.settings.nostrWriteRelays?Array.from(new Set(this.settings.nostrWriteRelays.map(AD).filter(Boolean))):this.defaultWriteRelays}async loadPlacesInBounds(t){const e=ND(t).filter(t=>!this.loadedGeohashPrefixes.has(t));if(0!==e.length){console.debug("[nostr-data] Loading place photos for prefixes:",e);try{await this._cachePromise;const t=await this.cache.query([{kinds:[360],"#g":e}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(ej){console.warn("[nostr-data] Failed to read photos from local Nostr IDB cache",ej)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#g":e}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("[nostr-data] Error fetching place photos by geohash:",t)}});for(const t of e)this.loadedGeohashPrefixes.add(t)}}async loadPhotosForPlace(t){if(this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null),this.placePhotos=[],!t||!t.osmId||!t.osmType)return;const e=`osm:${t.osmType}:${t.osmId}`;this._photosSub=this.store.timeline([{kinds:[360],"#i":[e]}]).subscribe(t=>{this.placePhotos=t});try{await this._cachePromise;const t=await this.cache.query([{kinds:[360],"#i":[e]}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(ej){console.warn("[nostr-data] Failed to read photos for place from local Nostr IDB cache",ej)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#i":[e]}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("[nostr-data] Error fetching place photos for place:",t)}})}async loadProfile(t){if(!t)return;this.profile=null,this.mailboxes=null,this.blossomServers=[],this._cleanupSubscriptions(),this._profileSub=this.store.model(UO,t).subscribe(t=>{this.profile=t}),this._mailboxesSub=this.store.model(BO,t).subscribe(t=>{this.mailboxes=t}),this._blossomSub=this.store.replaceable(10063,t).subscribe(t=>{t&&t.tags?this.blossomServers=t.tags.filter(t=>"server"===t[0]&&t[1]).map(t=>t[1]):this.blossomServers=[]});try{await this._cachePromise;const e=await this.cache.query([{authors:[t],kinds:[0,10002,10063]}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(ej){console.warn("Failed to read from local Nostr IDB cache",ej)}const e=Array.from(new Set([...BD,...this.activeWriteRelays]));this._requestSub=this.nostrRelay.pool.request(e,[{authors:[t],kinds:[0,10002,10063]}]).subscribe({next:t=>{this.store.add(t)},error:t=>{console.error("Error fetching profile events:",t)}})}get userDisplayName(){if(this.profile){if(this.profile.nip05)return this.profile.nip05;if(this.profile.displayName||this.profile.display_name)return this.profile.displayName||this.profile.display_name;if(this.profile.name)return this.profile.name}if(this.nostrAuth.pubkey)try{const t=function(t,e){return function(t,e){let n=lk.toWords(e);return lk.encode("npub",n,5e3)}(0,e)}(0,bS(this.nostrAuth.pubkey));return`${t.slice(0,9)}...${t.slice(-4)}`}catch{return this.nostrAuth.pubkey}return"Not connected"}async clearCache(){await this._cachePromise,this.cache&&await this.cache.deleteAllEvents()}_cleanupSubscriptions(){this._requestSub&&(this._requestSub.unsubscribe(),this._requestSub=null),this._profileSub&&(this._profileSub.unsubscribe(),this._profileSub=null),this._mailboxesSub&&(this._mailboxesSub.unsubscribe(),this._mailboxesSub=null),this._blossomSub&&(this._blossomSub.unsubscribe(),this._blossomSub=null),this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null)}willDestroy(){super.willDestroy(...arguments),this._cleanupSubscriptions(),this._stopPersisting&&this._stopPersisting(),this.cache&&this.cache.stop()}}const VD=Object.freeze(Object.defineProperty({__proto__:null,default:qD},Symbol.toStringTag,{value:"Module"}));function WD(t){return NA(t=>"EOSE"!==t,t)}function HD(t){return vA(e=>WP({ok:!1,from:t.url,message:e?.message||"Unknown error"}))}class GD{relays$=new mP([]);status$;get relays(){if(this.relays$ instanceof mP)return this.relays$.value;throw new Error("This group was created with an observable, relays are not available")}constructor(t){this.relays$=Array.isArray(t)?new mP(t):t,this.status$=this.relays$.pipe(zA(t=>0===t.length?WP({}):fA(...t.map(t=>t.status$)).pipe(IA((t,e)=>({...t,[e.url]:e}),{}),FA({}))),OA(1))}get controlled(){return this.relays$ instanceof mP==0}has(t){if(this.controlled)throw new Error("This group was created with an observable, relays are not available");return"string"==typeof t?this.relays.some(e=>e.url===t):this.relays.includes(t)}add(t){this.has(t)||this.relays$.next([...this.relays,t])}remove(t){this.has(t)&&this.relays$.next(this.relays.filter(e=>e!==t))}internalSubscription(t,e=aP){const n=new WeakMap,r=this.relays$.pipe(function(t){return uP((e,n)=>{let r=null,i=!1;const s=()=>{i&&!r&&n.complete()};e.subscribe(hP(n,e=>{const i=r,o=r=hP(n,t=>n.next(t),()=>{r!==o&&null!==r||(r=null,s())});VP(t(e)).subscribe(r),i?.unsubscribe()},()=>{i=!0,s()}))})}(e=>{const r=[];for(const i of e){if(n.has(i)){r.push(n.get(i));continue}const e=t(i).pipe(vA(()=>WP("EOSE")),eA(t=>[i,t]));r.push(e),n.set(i,e)}return fA(...r)}),PA()),i=r.pipe(eA(([t,e])=>e),t=>t.pipe(mA(t=>"EOSE"!==t)),e),s=this.relays$.pipe(zA(t=>r.pipe(mA(([t,e])=>"EOSE"===e),IA((t,[e])=>[...t,e],[]),NA(e=>t.some(t=>!e.includes(t))),xA(),kA("EOSE"))));return fA(i,s).pipe(PA())}internalPublish(t){const e=new WeakMap;return this.relays$.pipe(_A(1),zA(n=>{const r=[];for(const i of n){if(e.has(i)){r.push(e.get(i));continue}const n=t(i).pipe(HD(i));r.push(n),e.set(i,n)}return fA(...r)}))}req(t,e=Rx(),n){return this.internalSubscription(n=>n.req(t,e),n?.eventStore?HO(n?.eventStore):aP)}event(t){return this.internalPublish(e=>e.event(t)).pipe(PA())}async negentropy(t,e,n,r){const i=(await Promise.all(this.relays.map(async t=>[t,await t.getSupported()]))).filter(([t,e])=>e?.includes(77)).map(([t])=>t);if(0===i.length)throw new Error("No relays support NIP-77 negentropy sync");if(!r?.parallel)throw new Error("Negentropy sync must be parallel (for now)");return await Promise.allSettled(i.map(i=>i.negentropy(t,e,n,r))),!0}publish(t,e){return ZP(this.internalPublish(n=>VP(n.publish(t,e))).pipe(uP(function(t,e){(function(t,e){return uP(bA(t,e,arguments.length>=2,!1,!0))})(wA,[])(t).subscribe(e)}),(n=[],uP(function(t,e){var r=!1;t.subscribe(hP(e,function(t){r=!0,e.next(t)},function(){r||e.next(n),e.complete()}))}))));var n}request(t,e){return this.internalSubscription(n=>n.request(t,e).pipe(kA("EOSE")),null==e?.eventStore?aP:HO(e?.eventStore??new TO)).pipe(WD())}subscription(t,e){return this.internalSubscription(n=>n.subscription(t,e),null==e?.eventStore?aP:HO(e?.eventStore??new TO))}count(t,e=Rx()){return this.relays$.pipe(zA(n=>aA(Object.fromEntries(n.map(n=>[n.url,n.count(t,e)])))),PA())}sync(t,e,n){return dA(async()=>{const t=(await Promise.all(this.relays.map(async t=>[t,await t.getSupported()]))).filter(([t,e])=>e?.includes(77)).map(([t])=>t);if(0===t.length)throw new Error("No relays support NIP-77 negentropy sync");return t}).pipe(zA(r=>fA(...r.map(r=>r.sync(t,e,n)))),PA())}}var KD={url:"",deserializer:function(t){return JSON.parse(t.data)},serializer:function(t){return JSON.stringify(t)}},ZD=function(t){function e(e,n){var r=t.call(this)||this;if(r._socket=null,e instanceof lP)r.destination=n,r.source=e;else{var i=r._config=NI({},KD);if(r._output=new fP,"string"==typeof e)i.url=e;else for(var s in e)e.hasOwnProperty(s)&&(i[s]=e[s]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw new Error("no WebSocket constructor can be found");r.destination=new vP}return r}return DI(e,t),e.prototype.lift=function(t){var n=new e(this._config,this.destination);return n.operator=t,n.source=this,n},e.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new vP),this._output=new fP},e.prototype.multiplex=function(t,e,n){var r=this;return new lP(function(i){try{r.next(t())}catch(o){i.error(o)}var s=r.subscribe({next:function(t){try{n(t)&&i.next(t)}catch(o){i.error(o)}},error:function(t){return i.error(t)},complete:function(){return i.complete()}});return function(){try{r.next(e())}catch(o){i.error(o)}s.unsubscribe()}})},e.prototype._connectSocket=function(){var t=this,e=this._config,n=e.WebSocketCtor,r=e.protocol,i=e.url,s=e.binaryType,o=this._output,a=null;try{a=r?new n(i,r):new n(i),this._socket=a,s&&(this._socket.binaryType=s)}catch(ej){return void o.error(ej)}var l=new KI(function(){t._socket=null,a&&1===a.readyState&&a.close()});a.onopen=function(e){if(!t._socket)return a.close(),void t._resetState();var n=t._config.openObserver;n&&n.next(e);var r=t.destination;t.destination=eP.create(function(e){if(1===a.readyState)try{var n=t._config.serializer;a.send(n(e))}catch(ej){t.destination.error(ej)}},function(e){var n=t._config.closingObserver;n&&n.next(void 0),e&&e.code?a.close(e.code,e.reason):o.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }")),t._resetState()},function(){var e=t._config.closingObserver;e&&e.next(void 0),a.close(),t._resetState()}),r&&r instanceof vP&&l.add(r.subscribe(t.destination))},a.onerror=function(e){t._resetState(),o.error(e)},a.onclose=function(e){a===t._socket&&t._resetState();var n=t._config.closeObserver;n&&n.next(e),e.wasClean?o.complete():o.error(e)},a.onmessage=function(e){try{var n=t._config.deserializer;o.next(n(e))}catch(r){o.error(r)}}},e.prototype._subscribe=function(t){var e=this,n=this.source;return n?n.subscribe(t):(this._socket||this._connectSocket(),this._output.subscribe(t),t.add(function(){var t=e._socket;0===e._output.observers.length&&(!t||1!==t.readyState&&0!==t.readyState||t.close(),e._resetState())}),t)},e.prototype.unsubscribe=function(){var e=this._socket;!e||1!==e.readyState&&0!==e.readyState||e.close(),this._resetState(),t.prototype.unsubscribe.call(this)},e}(gP);const YD="auth-required:",XD={count:3,delay:1e3,resetOnSuccess:!0};var JD;!function(t){t[t.RECEIVE=1]="RECEIVE",t[t.SEND=2]="SEND",t[t.BOTH=3]="BOTH"}(JD||(JD={}));class QD extends Error{}const tN={ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0};class eN{url;log=ZA.extend("Relay");socket;_ready$=new mP(!0);ready$=this._ready$.asObservable();reconnectTimer;attempts$=new mP(0);connected$=new mP(!1);challenge$=new mP(null);authenticated$;authenticatedAs$;authentication$=new mP(null);authenticationResponse$=new mP(null);notices$=new mP([]);error$=new mP(null);message$;notice$;lastMessageReceivedAt=0;_lastMessageAt$=new mP(0);lastMessageAt$=this._lastMessageAt$.asObservable();status$;information$;_nip11=null;icon$;limitations$;supported$;open$=new fP;close$=new fP;closing$=new fP;reqs$=new mP({});get ready(){return this._ready$.value}get connected(){return this.connected$.value}get challenge(){return this.challenge$.value}get notices(){return this.notices$.value}get authenticated(){return!0===this.authenticationResponse?.ok}get authentication(){return this.authentication$.value}get authenticatedAs(){return this.authenticated?this.authentication?.pubkey??null:null}get authenticationResponse(){return this.authenticationResponse$.value}get information(){return this._nip11}get lastMessageAt(){return this._lastMessageAt$.value}get reqs(){return this.reqs$.value}eoseTimeout=1e4;eventTimeout=1e4;publishTimeout=3e4;keepAlive=3e4;enablePing=!1;pingFrequency=29e3;pingTimeout=2e4;subscriptionReconnect;requestReconnect;publishRetry;onUnresponsive;receivedAuthRequiredForReq=new mP(!1);receivedAuthRequiredForEvent=new mP(!1);authRequiredForRead$;authRequiredForPublish$;resetState(){null!==this.challenge$.value&&this.challenge$.next(null),this.authenticationResponse$.value&&this.authenticationResponse$.next(null),null!==this.authentication$.value&&this.authentication$.next(null),this.notices$.value.length>0&&this.notices$.next([]),this.receivedAuthRequiredForReq.value&&this.receivedAuthRequiredForReq.next(!1),this.receivedAuthRequiredForEvent.value&&this.receivedAuthRequiredForEvent.next(!1)}watchTower;constructor(t,e){var n;this.url=t,this.log=this.log.extend(t),void 0!==e?.eoseTimeout&&(this.eoseTimeout=e.eoseTimeout),void 0!==e?.eventTimeout&&(this.eventTimeout=e.eventTimeout),void 0!==e?.publishTimeout&&(this.publishTimeout=e.publishTimeout),void 0!==e?.keepAlive&&(this.keepAlive=e.keepAlive),void 0!==e?.enablePing&&(this.enablePing=e.enablePing),void 0!==e?.pingFrequency&&(this.pingFrequency=e.pingFrequency),void 0!==e?.pingTimeout&&(this.pingTimeout=e.pingTimeout),void 0!==e?.onUnresponsive&&(this.onUnresponsive=e.onUnresponsive),this.subscriptionReconnect={...XD,...e?.subscriptionRetry??{}},this.requestReconnect={...XD,...e?.requestRetry??{}},this.publishRetry={...XD,...e?.publishRetry??{}},this.authenticated$=this.authenticationResponse$.pipe(eA(t=>!0===t?.ok)),this.authenticatedAs$=aA([this.authenticated$,this.authentication$]).pipe(eA(([t,e])=>t&&e?e.pubkey:null)),this.reconnectTimer=eN.createReconnectTimer(t),this.open$.subscribe(()=>{this.log("Connected"),this.connected$.next(!0),this.attempts$.next(0),this.error$.next(null),this.resetState()}),this.close$.subscribe(t=>{this.connected$.value?this.log("Disconnected"):this.log("Failed to connect"),this.connected$.value&&this.connected$.next(!1),this.attempts$.next(this.attempts$.value+1),this.resetState(),t.wasClean||this.startReconnectTimer(t)}),this.socket=(n={url:t,openObserver:this.open$,closeObserver:this.close$,closingObserver:this.closing$,WebSocketCtor:e?.WebSocket},new ZD(n)),this.information$=dA(()=>(this.log("Fetching NIP-11 information document"),eN.fetchInformationDocument(this.url))).pipe(vA(()=>WP(null)),jA(t=>this._nip11=t),OA(1)),this.limitations$=this.information$.pipe(eA(t=>t?t.limitation:null)),this.supported$=this.information$.pipe(eA(t=>t&&Array.isArray(t.supported_nips)?t.supported_nips.filter(t=>"number"==typeof t):null)),this.icon$=this.information$.pipe(eA(t=>t?.icon||new URL("/favicon.ico",uI(this.url)).toString())),this.authRequiredForRead$=this.receivedAuthRequiredForReq,this.authRequiredForPublish$=this.receivedAuthRequiredForEvent,this.authRequiredForRead$.pipe(mA(t=>!0===t),_A(1)).subscribe(()=>this.log("Auth required for REQ")),this.authRequiredForPublish$.pipe(mA(t=>!0===t),_A(1)).subscribe(()=>this.log("Auth required for EVENT")),this.status$=aA({url:WP(this.url),connected:this.connected$,authenticated:this.authenticated$,authenticatedAs:this.authenticatedAs$,ready:this._ready$,authRequiredForRead:this.authRequiredForRead$,authRequiredForPublish:this.authRequiredForPublish$,challenge:this.challenge$.asObservable()}).pipe(OA(1));const r=this.socket.pipe(mA(t=>Array.isArray(t)&&"NOTICE"===t[0]),eA(t=>t[1]),IA((t,e)=>[...t,e],[]),jA(t=>this.notices$.next(t))),i=this.socket.pipe(mA(t=>"AUTH"===t[0]),eA(t=>t[1]),jA(t=>{this.log("Received AUTH challenge",t),this.challenge$.next(t)})),s=new fP,o=this.socket.pipe(jA(t=>{const e=Date.now();this.lastMessageReceivedAt=e,this._lastMessageAt$.next(e),s.next(t)}));this.message$=s.asObservable(),this.notice$=this.message$.pipe(mA(t=>Array.isArray(t)&&"NOTICE"===t[0]),eA(t=>t[1]));const a=this.connected$.pipe(zA(t=>t&&this.enablePing?pA(this.pingFrequency,this.pingFrequency).pipe(cA(()=>{if(Date.now()-this.lastMessageReceivedAtArray.isArray(e)&&("EOSE"===e[0]||"CLOSED"===e[0])&&e[1]===t),_A(1),QP({first:this.pingTimeout,with:()=>{const t=Date.now(),e=this.onUnresponsive?.({url:this.url,lastMessageAt:this.lastMessageReceivedAt,now:t,attempts:this.attempts$.value})??"reconnect",n=new Error(`Relay ping timeout after ${this.pingTimeout}ms`);return"reconnect"===e?(this.log("Relay connection has become unresponsive, triggering reconnect"),this.startReconnectTimer(n)):"close"===e?(this.log("Relay connection has become unresponsive, closing connection"),this.error$.next(n),this.socket.complete()):this.log("Relay connection has become unresponsive (ignoring per policy)"),gA}}),EA(()=>this.send(["CLOSE",t])))})):gA),vA(()=>gA));this.watchTower=this.ready$.pipe(zA(t=>t?fA(o,r,i,this.information$,a).pipe(xA(),vA(t=>(this.startReconnectTimer(t instanceof Error?t:new Error("Connection error")),gA)),PA({resetOnRefCountZero:()=>pA(this.keepAlive)})):gA),PA())}startReconnectTimer(t){this.ready&&(this.error$.next(t instanceof Error?t:new Error("Connection error")),this._ready$.next(!1),this.reconnectTimer(t,this.attempts$.value).pipe(_A(1)).subscribe(()=>{this._ready$.next(!0)}))}waitForAuth(t,e){return aA([t,this.authenticated$]).pipe(RA(this.watchTower),mA(([t,e])=>!t||e),_A(1),zA(()=>e))}waitForReady(t){return this.ready?t:this.ready$.pipe(mA(t=>t),_A(1),zA(()=>t))}multiplex(t,e,n){return this.socket.multiplex(t,e,n)}send(t){this.socket.next(t)}req(t,e=Rx()){let n;if("function"==typeof t){const e=t(this);n=(GP(e)?e:fA(WP(e),gA)).pipe(eA(t=>Array.isArray(t)?t:[t]))}else n=(GP(t)?t:fA(WP(t),gA)).pipe(eA(t=>Array.isArray(t)?t:[t]));const r=n.pipe(xA(),kA(null)),i=this.socket.pipe(mA(t=>Array.isArray(t)&&("EVENT"===t[0]||"CLOSED"===t[0]||"EOSE"===t[0])&&t[1]===e),PA()),s=n.pipe(jA(t=>{this.socket.next(["REQ",e,...t]),this.reqs$.next({...this.reqs$.value,[e]:t})}),EA(()=>{this.socket.next(["CLOSE",e]);const{[e]:t,...n}=this.reqs$.value;this.reqs$.next(n)}),zA(()=>i)),o=fA(this.watchTower,s).pipe(DA(i.pipe(xA(),kA(!0))),DA(r),eA(t=>{if("EOSE"===t[0])return"EOSE";if("CLOSED"===t[0])throw new QD(t[2]);return t[2]}),this.handleAuthRequiredForReq("REQ"),(a=this.url,t=>t.pipe(jA(t=>{"string"!=typeof t&&pI(t,a)}))),QP({first:this.eoseTimeout,with:()=>fA(WP("EOSE"),gA)}),PA());var a;return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,o))}count(t,e=Rx()){const n=this.socket.pipe(mA(t=>Array.isArray(t)&&("COUNT"===t[0]||"CLOSED"===t[0])&&t[1]===e)),r=dA(()=>(this.socket.next(Array.isArray(t)?["COUNT",e,...t]:["COUNT",e,t]),fA(this.watchTower,n))).pipe(eA(t=>{if("COUNT"===t[0])return t[2];throw new QD(t[2])}),this.handleAuthRequiredForReq("COUNT"),_A(1),QP({first:this.eoseTimeout,with:()=>HP(()=>new Error("COUNT timeout"))}));return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,r)).pipe(PA())}event(t,e="EVENT"){const n=dA(()=>(this.socket.next([e,t]),this.socket.pipe(mA(e=>"OK"===e[0]&&e[1]===t.id),eA(t=>({ok:t[2],message:t[3],from:this.url}))))).pipe(PA()),r=fA(this.watchTower,n).pipe(DA(n.pipe(xA(),kA(!0))),_A(1),jA(({ok:t,message:e})=>{!1===t&&e?.startsWith(YD)&&!this.receivedAuthRequiredForEvent.value&&(this.log("Auth required for publish"),this.receivedAuthRequiredForEvent.next(!0))}),QP({first:this.eventTimeout,with:()=>WP({ok:!1,from:this.url,message:"Timeout"})}));return"AUTH"===e?this.waitForReady(r).pipe(PA()):this.waitForReady(this.waitForAuth(this.authRequiredForPublish$,r)).pipe(PA())}auth(t){return this.authentication$.next(t),ZP(this.event(t,"AUTH").pipe(jA(t=>this.authenticationResponse$.next(t))))}async negentropy(t,e,n,r){if(!1===(await this.getSupported())?.includes(77))throw new Error("Relay does not support NIP-77");const{buildStorageVector:i,buildStorageFromFilter:s,negentropySync:o}=await MD(async()=>{const{buildStorageVector:t,buildStorageFromFilter:e,negentropySync:n}=await import("./negentropy-CkK5_v5U.js");return{buildStorageVector:t,buildStorageFromFilter:e,negentropySync:n}},[]);return o(Array.isArray(t)?i(t):await s(t,e),this.socket,e,n,r)}authenticate(t){if(!this.challenge)throw new Error("Have not received authentication challenge");const e=t.signEvent(function(t,e){return{kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}(this.url,this.challenge));return ZP((e instanceof Promise?VP(e):WP(e)).pipe(zA(t=>this.auth(t))))}customRetryOperator(t,e){return!1===t?aP:"number"==typeof t?LA({...e,count:t}):!0===t?e?LA(e):LA():LA({...e,...t})}customRepeatOperator(t){return!1===t||void 0===t?aP:!0===t?MA():MA(t)}customTimeoutOperator(t,e){return!1===t?aP:KO(!0===t?e:t??e)}handleAuthRequiredForReq(t){return vA(e=>(e instanceof QD&&e.message.startsWith(YD)&&!this.receivedAuthRequiredForReq.value&&(this.log(`Auth required for ${t}`),this.receivedAuthRequiredForReq.next(!0)),HP(()=>e)))}subscription(t,e){return this.req(t,e?.id).pipe(this.customRetryOperator(e?.reconnect??!0,this.subscriptionReconnect),this.customRepeatOperator(e?.resubscribe),PA())}request(t,e){return this.req(t,e?.id).pipe(this.customRetryOperator(e?.reconnect??!0,this.requestReconnect),this.customRepeatOperator(e?.resubscribe),WD(),PA())}publish(t,e){return ZP(this.event(t).pipe(cA(t=>!1===t.ok&&t.message?.startsWith(YD)?HP(()=>new Error(t.message)):WP(t)),this.customRetryOperator(e?.retries??e?.reconnect??!0,this.publishRetry),this.customTimeoutOperator(e?.timeout,this.publishTimeout)))}sync(t,e,n=JD.RECEIVE){return new lP(r=>{const i=new AbortController;let s=!1;return this.negentropy(t,e,async(e,i)=>{if(n&JD.SEND&&e.length>0){const n=await(async e=>Array.isArray(t)?t.filter(t=>e.includes(t.id)):t.getByFilters({ids:e}))(e);await Promise.allSettled(n.map(t=>ZP(this.event(t))))}n&JD.RECEIVE&&i.length>0&&await ZP(this.req({ids:i}).pipe(WD(),Reflect.has(t,"add")?WO(t):aP,jA(t=>r.next(t))))},{signal:i.signal}).then(()=>{s||r.complete()}).catch(t=>{s||r.error(t)}),()=>{s||(s=!0,i.abort())}}).pipe(PA())}close(){this.socket.unsubscribe()}async getInformation(){return YP(this.information$)}async getLimitations(){return YP(this.limitations$)}async getSupported(){return YP(this.supported$)}static fetchInformationDocument(t){return VP(fetch(uI(t),{headers:{Accept:"application/nostr+json"}}).then(t=>t.json())).pipe(vA(()=>WP(null)),KO(1e4))}static createReconnectTimer(t){return(t,e=0)=>pA(Math.min(1e3*Math.pow(1.5,e),3e5))}}class nN{options;relays$=new mP(new Map);get relays(){return this.relays$.value}status$;ignoreOffline=!0;add$=new fP;remove$=new fP;constructor(t){this.options=t,this.status$=this.relays$.pipe(eA(t=>Array.from(t.values())),zA(t=>0===t.length?WP({}):fA(...t.map(t=>t.status$)).pipe(IA((t,e)=>({...t,[e.url]:e}),{}),FA({}))),OA(1))}relay(t){t=hI(t);let e=this.relays.get(t);return e||(e=new eN(t,this.options),this.relays.set(t,e),this.relays$.next(this.relays),e)}group(t,e=this.ignoreOffline){let n=Array.isArray(t)?t.map(t=>this.relay(t)):t.pipe(eA(t=>t.map(t=>this.relay(t))));return e&&(n=Array.isArray(n)?n.filter(t=>t.ready):n.pipe(eA(t=>t.filter(t=>t.ready)))),new GD(n)}remove(t,e=!0){let n;if("string"==typeof t){if(n=this.relays.get(t),!n)return}else{if(!Array.from(this.relays.values()).some(e=>e===t))return;n=t}e&&n?.close(),this.relays.delete(n.url),this.relays$.next(this.relays),this.remove$.next(n)}req(t,e,n){return this.group(t,!1).req(e,n)}event(t,e){return this.group(t,!1).event(e)}negentropy(t,e,n,r,i){return this.group(t,!1).negentropy(e,n,r,i)}publish(t,e,n){return this.group(t).publish(e,n)}request(t,e,n){return this.group(t).request(e,n)}subscription(t,e,n){return this.group(t).subscription(e,n)}subscriptionMap(t,e){const n=GP(t)?t:WP(t);return this.group(n.pipe(eA(t=>Object.keys(t)))).subscription(t=>n.pipe(eA(e=>e[t.url]),CA(cO)),e)}outboxSubscription(t,e,n){const r=GP(t)?t.pipe(eA(t=>vO(t,e))):vO(t,e);return this.subscriptionMap(r,n)}count(t,e,n){return this.group(t).count(e,n)}sync(t,e,n,r){return this.group(t).sync(e,n,r)}}const rN=Object.freeze(Object.defineProperty({__proto__:null,default:class extends qf{pool=new nN;async publish(t,e){if(!t||0===t.length)throw new Error("No relays provided to publish the event.");const n=await this.pool.publish(t,e);if(!n.some(t=>t.ok))throw new Error(`Failed to publish event. Responses: ${JSON.stringify(n)}`);return n}}},Symbol.toStringTag,{value:"Module"}));class iN{}class sN extends iN{constructor(t){super(),this.message=t}}class oN extends iN{}class aN extends iN{}class lN extends iN{}class cN extends iN{}class uN extends iN{}const hN={invalid_request:class extends iN{},invalid_grant:class extends uN{},unauthorized_client:class extends cN{},access_denied:class extends cN{},unsupported_response_type:class extends cN{},invalid_scope:class extends iN{},server_error:class extends cN{},temporarily_unavailable:class extends cN{},invalid_client:class extends uN{},unsupported_grant_type:class extends uN{},invalid_token:class extends iN{}},dN=t=>{const e=hN[t];return e?new e:new sN(t)},pN="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",fN=t=>{const e=t.slice(7).replace(/"/g,"").split(",").map(t=>{const[e,n]=t.trim().split("=");return{[e]:n}}).reduce((t,e)=>Object.assign(Object.assign({},t),e),{});return{realm:e.realm,error:e.error,errorDescription:e.error_description,errorUri:e.error_uri}},gN=t=>{let e=btoa(t);return e=e.replace(/\+/g,"-"),e=e.replace(/\//g,"_"),e=e.replace(/=/g,""),e},mN=(t,e)=>{let n=e.split("?");if(n.length<2)return;n=n[1].split("#");const r=n[0].split("&");for(const i of r){const[e,n]=i.split("=");if(e===t)return decodeURIComponent(n)}},yN=t=>Object.entries(t).map(([t,e])=>`${t}=${encodeURIComponent(e)}`).join("&");var vN=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(ej){s(ej)}}function a(t){try{l(r.throw(t))}catch(ej){s(ej)}}function l(t){t.done?i(t.value):function(t){return t instanceof n?t:new n(function(e){e(t)})}(t.value).then(o,a)}l((r=r.apply(t,e||[])).next())})};const bN="WWW-Authenticate";class wN{constructor(t,e){this.state={},this.config=t,this.storage=e||xN,this.ready=new Promise(t=>this.setReady=t),this.recoverState()}reset(){return vN(this,void 0,void 0,function*(){this.state={},yield this.saveState(),this.authCodeForAccessTokenPromise=void 0,this.refreshTokenForAccessTokenPromise=void 0})}requestAuthorizationCode(t){return vN(this,void 0,void 0,function*(){const{clientId:e,extraAuthorizationParams:n,redirectUrl:r,scopes:i}=this.config,{codeChallenge:s,codeVerifier:o}=yield(l=void 0,c=function*(){const t=new Uint32Array(96);crypto.getRandomValues(t);const e=gN(Array.from(t).map(t=>pN[t%66]).join("")),n=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=new Uint8Array(n);let i="";const s=r.byteLength;for(let o=0;o{const t=new Uint32Array(32);return crypto.getRandomValues(t),Array.from(t).map(t=>pN[t%66]).join("")})();var l,c;this.state=Object.assign(Object.assign({},this.state),{codeChallenge:s,codeVerifier:o,stateQueryParam:a}),this.saveState();let u=this.config.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(e)}&`+`redirect_uri=${encodeURIComponent(r)}&`+`state=${a}&`+`code_challenge=${encodeURIComponent(s)}&code_challenge_method=S256`;if(i&&(u+=`&scope=${encodeURIComponent(i.join(" "))}`),n||t){const e=Object.assign(Object.assign({},n),t);u+=`&${yN(e)}`}location.replace(u)})}isReturningFromAuthServer(){return!!mN("code",location.href)}receiveCode(){return vN(this,void 0,void 0,function*(){yield this.ready;const t=mN("error",location.href);if(t)throw dN(t);if(mN("state",location.href)!==this.state.stateQueryParam)throw console.warn('"state" parameter doesn\'t match the one sent! Possible malicious activity.'),new lN;if(this.state.authorizationCode=mN("code",location.href),!this.state.authorizationCode)throw new aN;this.saveState()})}getTokens(t){return vN(this,void 0,void 0,function*(){const{accessToken:e,authorizationCode:n,idToken:r,refreshToken:i,scopes:s}=this.state;if(n)return this.exchangeAuthCodeForAccessToken(t);if(!e)throw new oN;return this.isAccessTokenExpired()&&this.config.onAccessTokenExpiry?this.config.onAccessTokenExpiry():Promise.resolve({accessToken:e,idToken:r,refreshToken:i,scopes:s})})}exchangeAuthCodeForAccessToken(t){return vN(this,void 0,void 0,function*(){this.authCodeForAccessTokenPromise||(this.authCodeForAccessTokenPromise=this.fetchAccessTokenUsingCode(t));const e=yield this.authCodeForAccessTokenPromise;return this.authCodeForAccessTokenPromise=void 0,this.state.authorizationCode=void 0,this.setTokens(e)})}exchangeRefreshTokenForAccessToken(){return vN(this,void 0,void 0,function*(){this.refreshTokenForAccessTokenPromise||(this.refreshTokenForAccessTokenPromise=this.fetchAccessTokenUsingRefreshToken());const t=yield this.refreshTokenForAccessTokenPromise;return this.refreshTokenForAccessTokenPromise=void 0,this.setTokens(t)})}makeRetryFetchFunction(t){return(e,...n)=>vN(this,void 0,void 0,function*(){const r=yield t(e,...n);if(401===r.status){const i=r.headers.get(bN.toLowerCase());if(i&&"invalid_token"===fN(i).error)return yield this.exchangeRefreshTokenForAccessToken(),e=yield this.requestInterceptor(e),t(e,...n)}return r})}decorateFetchWithInterceptors(t){return(e,...n)=>vN(this,void 0,void 0,function*(){"string"==typeof e&&(e=new Request(e)),e=yield this.requestInterceptor(e);const r=yield t(e,...n);return this.responseInterceptor(r)})}requestInterceptor(t){return vN(this,void 0,void 0,function*(){const e=yield this.getTokens();return t.headers.set("Authorization",`Bearer ${e.accessToken}`),t})}responseInterceptor(t){return vN(this,void 0,void 0,function*(){if(401!==t.status)return t;const e=t.headers.get(bN.toLowerCase());if(e){const t=fN(e).error;throw"invalid_grant"===t&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),"invalid_token"===t&&this.config.onInvalidToken&&(yield this.config.onInvalidToken()),dN(t)}return t})}getGrantedScopes(){return this.state.scopes}isAuthorized(){return!!this.state.accessToken}isAccessTokenExpired(){const{accessTokenExpiry:t}=this.state;return Boolean(t&&new Date>=new Date(t))}fetchAccessTokenUsingCode(t){return vN(this,void 0,void 0,function*(){const{authorizationCode:e,codeVerifier:n=""}=this.state,{clientId:r,redirectUrl:i}=this.config;n?e||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const s=this.config.tokenUrl,o=Object.assign({grant_type:"authorization_code",code:e,redirect_uri:i,client_id:r,code_verifier:n},t),a=new URLSearchParams(o).toString();return this.makeTokenRequest(s,a)})}fetchAccessTokenUsingRefreshToken(){const{extraRefreshParams:t,clientId:e,tokenUrl:n}=this.config,{refreshToken:r}=this.state;r||console.warn("No refresh token is present.");const i=n;let s=`grant_type=refresh_token&refresh_token=${r}&client_id=${e}`;return t&&(s=`${i}&${yN(t)}`),this.makeTokenRequest(i,s)}makeTokenRequest(t,e){return vN(this,void 0,void 0,function*(){const n=yield fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),r=yield n.json();if(!n.ok)throw"invalid_grant"===r.error&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),dN(r.error);const{access_token:i,expires_in:s,id_token:o,refresh_token:a,scope:l}=r;return{accessToken:i,expiresIn:s,idToken:o,refreshToken:a,scope:l}})}setTokens(t){return vN(this,void 0,void 0,function*(){const{accessToken:e,expiresIn:n,idToken:r,refreshToken:i,scope:s}=t;return this.state.accessToken=e,this.state.accessTokenExpiry=new Date(Date.now()+1e3*parseInt(n,10)).toString(),r&&(this.state.idToken=r),i&&(this.state.refreshToken=i),s&&(this.state.scopes=s.split(" ")),yield this.saveState(),{accessToken:this.state.accessToken,idToken:this.state.idToken,refreshToken:this.state.refreshToken,scopes:s?this.state.scopes:[]}})}recoverState(){return vN(this,void 0,void 0,function*(){this.state=JSON.parse((yield this.storage.loadState())||"{}"),this.setReady(),this.config.storeRefreshToken||(this.state.refreshToken=this.refreshToken)})}saveState(){return vN(this,void 0,void 0,function*(){this.refreshToken=this.state.refreshToken;const t=Object.assign({},this.state);this.config.storeRefreshToken||delete t.refreshToken,yield this.storage.saveState(JSON.stringify(t))})}}const _N="oauth2authcodepkce-state",xN={saveState:t=>localStorage.setItem(_N,t),loadState:()=>localStorage.getItem(_N)};class CN{saveState(t){localStorage.setItem("marco:osm_auth_state",t)}loadState(){const t=localStorage.getItem("marco:osm_auth_state");if(!t)return!1;try{return JSON.parse(t),t}catch(ej){return console.warn("Failed to parse OSM auth state",ej),!1}}}class SN extends qf{static{dF(this.prototype,"isConnected",[Is],function(){return!1})}#tt=void fF(this,"isConnected");static{dF(this.prototype,"userDisplayName",[Is],function(){return null})}#et=void fF(this,"userDisplayName");oauthClient;constructor(){super(...arguments);const t="https://www.openstreetmap.org",e=`${window.location.origin}/oauth/osm/callback`;this.oauthClient=new wN({scopes:["read_prefs","write_api"],authorizationUrl:`${t}/oauth2/authorize`,tokenUrl:`${t}/oauth2/token`,clientId:"jIn8l5mT8FZOGYiIYXG1Yvj_2FZKB9TJ1edZwOJPsRU",redirectUrl:e,storeRefreshToken:!0},new CN),this.restoreSession()}async restoreSession(){try{await this.oauthClient.ready}catch(ej){console.warn("oauthClient.ready failed",ej)}if(await this.oauthClient.isAuthorized()){this.isConnected=!0;const t=localStorage.getItem("marco:osm_user_display_name");t?this.userDisplayName=t:await this.fetchUserInfo()}}async login(){await this.oauthClient.requestAuthorizationCode()}async handleCallback(){await this.oauthClient.receiveCode(),await this.oauthClient.getTokens(),this.isConnected=!0,await this.fetchUserInfo()}async logout(){await this.oauthClient.reset(),this.isConnected=!1,this.userDisplayName=null,localStorage.removeItem("marco:osm_user_display_name")}async fetchUserInfo(){try{const t=await this.oauthClient.getTokens(),e=await fetch("https://api.openstreetmap.org/api/0.6/user/details.json",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(e.ok){const t=await e.json();console.debug("OSM data:",t);const n=t.user.display_name;this.userDisplayName=n,localStorage.setItem("marco:osm_user_display_name",n)}else console.error("Failed to fetch OSM user info",e.status)}catch(ej){console.error("Error fetching OSM user info",ej)}}}const kN=Object.freeze(Object.defineProperty({__proto__:null,default:SN},Symbol.toStringTag,{value:"Module"}));function EN(t){return"string"==typeof t&&t?t.replace(/[_-]/g," ").replace(/\w\S*/g,t=>t.replace(/^\w/,t=>t.toUpperCase())):""}const TN=Object.freeze(Object.defineProperty({__proto__:null,humanizeOsmTag:EN},Symbol.toStringTag,{value:"Module"}));function RN(t,e="Untitled Place"){if(!t)return e;const n=navigator.languages||[navigator.language||"en"];for(const r of n){if(!r)continue;const e=`name:${r.split("-")[0]}`;if(t[e])return t[e]}return t.name?t.name:t["name:en"]?t["name:en"]:e}const MN=["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","highway","aeroway","waterway","natural","place","border_type","admin_title"];function LN(t){if(!t)return null;for(const e of MN){const n=t[e];if(n)return EN("yes"===n?e:n)}return null}const IN=Object.freeze(Object.defineProperty({__proto__:null,getLocalizedName:RN,getPlaceType:LN},Symbol.toStringTag,{value:"Module"})),PN=[{id:"restaurants",label:"Restaurants",icon:"fork-and-knife",filter:['["amenity"~"^(restaurant|fast_food|food_court|pub|cafe)$"]["cuisine"!~"coffee"]'],types:["node","way"]},{id:"coffee",label:"Coffee",icon:"cup-and-saucer",filter:['["amenity"~"^(cafe|ice_cream)$"]','["shop"~"^(coffee|tea)$"]','["cuisine"~"coffee_shop"]'],types:["node","way"]},{id:"groceries",label:"Groceries",icon:"shopping-basket",filter:['["shop"~"^(supermarket|convenience|grocery|greengrocer|bakery|butcher|deli|farm|seafood)$"]'],types:["node","way"]},{id:"things-to-do",label:"Things to do",icon:"camera",filter:['["tourism"~"^(museum|gallery|attraction|viewpoint|zoo|theme_park|aquarium|artwork)$"]','["amenity"~"^(cinema|theatre|arts_centre|planetarium)$"]','["leisure"~"^(sports_centre|stadium|water_park)$"]','["historic"]','["shop"="flea_market"]'],types:["node","way","relation"]},{id:"accommodation",label:"Hotels",icon:"person-sleeping-in-bed",filter:['["tourism"~"^(hotel|hostel|motel|chalet)$"]'],types:["node","way","relation"]}];function AN(t){return PN.find(e=>e.id===t)}const ON=Object.freeze(Object.defineProperty({__proto__:null,POI_CATEGORIES:PN,getCategoryById:AN},Symbol.toStringTag,{value:"Module"}));class FN extends qf{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");controller=null;cachedResults=null;lastQueryKey=null;cachedPlaces=new Map;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}async getNearbyPois(t,e,n=50){const r=`${t},${e},${n}`;if(this.lastQueryKey===r&&this.cachedResults)return console.debug("Returning cached Overpass results for:",r),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,s=[`~"^(${["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","aeroway"].join("|")})$"~".*"`],o=Object.entries({public_transport:["stop_area","platform"]}).map(([t,e])=>`["${t}"!~"^(${e.join("|")})$"]`).join(""),a=`\n[out:json][timeout:25];\n(\n node(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n way(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n relation(around:${n},${t},${e})\n [${s}]${o}[~"^name"~"."];\n);\nout center;\n `.trim(),l=`${this.settings.overpassApi}?data=${encodeURIComponent(a)}`;try{const t=await this.fetchWithRetry(l,{signal:i});if(!t.ok)throw new Error("Overpass request failed");const e=(await t.json()).elements.map(this.normalizePoi);return this.lastQueryKey=r,this.cachedResults=e,e}catch(ej){if("AbortError"===ej.name)return console.debug("Overpass request aborted"),[];throw ej}}async getCategoryPois(t,e,n,r){const i=AN(e);if(!i||!t)return[];const s=n&&r?`cat:${e}:${n}:${r}`:null;if(s&&this.lastQueryKey===s&&this.cachedResults)return console.debug("Returning cached category results for:",s),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const o=this.controller.signal,{minLat:a,minLon:l,maxLat:c,maxLon:u}=t,h=[],d=i.types||["node","way","relation"];i.filter.forEach(t=>{d.forEach(e=>{h.push(`${e}${t}[~"^name"~"."];`)})});const p=`\n[out:json][timeout:25][bbox:${a},${l},${c},${u}];\n(\n ${h.join("\n ")}\n);\nout center;\n `.trim(),f=`${this.settings.overpassApi}?data=${encodeURIComponent(p)}`;try{const t=await this.fetchWithRetry(f,{signal:o});if(!t.ok)throw new Error("Overpass request failed");const e=(await t.json()).elements.map(this.normalizePoi);return s&&(this.lastQueryKey=s,this.cachedResults=e),e}catch(ej){if("AbortError"===ej.name)return console.debug("Category search aborted"),[];throw console.error("Category search failed",ej),ej}}normalizePoi(t){const e=t.tags||{},n=LN(e)||"Point of Interest";return{title:RN(e),lat:t.lat||t.center?.lat,lon:t.lon||t.center?.lon,url:e.website,osmId:String(t.id),osmType:t.type,osmTags:e,description:e.description,source:"osm",type:n}}async fetchWithRetry(t,e={},n=3){try{const r=await fetch(t,e);return!r.ok&&n>0&&[502,503,504,429].includes(r.status)?(console.warn(`Overpass request failed with ${r.status}. Retrying... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1)):r}catch(ej){if(n>0&&"AbortError"!==ej.name)return console.debug(`Retrying Overpass request... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1);throw ej}}async getPoiById(t,e=null){let n;n="node"===e?`[out:json][timeout:25];node(${t});out center;`:"way"===e?`[out:json][timeout:25];way(${t});out center;`:`\n[out:json][timeout:25];\n(\n node(${t});\n way(${t});\n);\nout center;\n `.trim();const r=`${this.settings.overpassApi}?data=${encodeURIComponent(n)}`,i=await this.fetchWithRetry(r);if(!i.ok)throw new Error("Overpass request failed");const s=await i.json();return s.elements[0]?this.normalizePoi(s.elements[0]):null}async fetchOsmObject(t,e){if(!t||!e)return null;const n=`${e}:${t}`,r=this.cachedPlaces.get(n);if(r&&Date.now()-r.timestamp<1e4)return console.debug(`Using in-memory cached OSM object for ${n}`),r.data;let i;if("node"===e)i=`https://www.openstreetmap.org/api/0.6/node/${t}.json`;else if("way"===e)i=`https://www.openstreetmap.org/api/0.6/way/${t}/full.json`;else{if("relation"!==e)return console.error("Unknown OSM type:",e),null;i=`https://www.openstreetmap.org/api/0.6/relation/${t}/full.json`}try{const r=await this.fetchWithRetry(i);if(!r.ok){if(410===r.status)return console.warn("OSM object has been deleted"),null;throw new Error(`OSM API request failed: ${r.status}`)}const s=await r.json(),o=this.normalizeOsmApiData(s.elements,t,e);return this.cachedPlaces.set(n,{data:o,timestamp:Date.now()}),setTimeout(()=>{this.cachedPlaces.delete(n)},1e4),o}catch(ej){return console.error("Failed to fetch OSM object:",ej),null}}normalizeOsmApiData(t,e,n){if(!t||0===t.length)return null;let r=t.find(t=>String(t.id)===String(e)&&t.type===n);if(!r)return null;let i=r;if("relation"===n&&r.members){const e=r.members.find(t=>"label"===t.role&&"node"===t.type),n=r.members.find(t=>"admin_centre"===t.role&&"node"===t.type),s=e||n;if(s){const e=t.find(t=>String(t.id)===String(s.ref)&&"node"===t.type);e&&(i=e)}}let s=i.lat,o=i.lon,a=null,l=null;if("way"===n&&r.nodes){const e=new Map;t.forEach(t=>{"node"===t.type&&e.set(t.id,[t.lon,t.lat])});const n=r.nodes.map(t=>e.get(t)).filter(Boolean);if(n.length>0){if(i===r){const t=n.reduce((t,e)=>t+e[1],0),e=n.reduce((t,e)=>t+e[0],0);s=t/n.length,o=e/n.length}const t=n.map(t=>t[1]),e=n.map(t=>t[0]);if(a={minLat:Math.min(...t),maxLat:Math.max(...t),minLon:Math.min(...e),maxLon:Math.max(...e)},n.length>1){const t=n[0],e=n[n.length-1];l=t[0]===e[0]&&t[1]===e[1]?{type:"Polygon",coordinates:[n]}:{type:"LineString",coordinates:n}}}}else if("relation"===n&&r.members){const e=[],n=new Map;t.forEach(t=>{"node"===t.type&&n.set(t.id,t)});const c=[];if(r.members.forEach(r=>{if("node"===r.type){const t=n.get(r.ref);t&&e.push(t)}else if("way"===r.type){const i=t.find(t=>"way"===t.type&&t.id===r.ref);if(i&&i.nodes){const t=[];i.nodes.forEach(r=>{const i=n.get(r);i&&(e.push(i),t.push([i.lon,i.lat]))}),t.length>1&&c.push(t)}}}),e.length>0){if(i===r){const t=e.reduce((t,e)=>t+e.lat,0),n=e.reduce((t,e)=>t+e.lon,0);s=t/e.length,o=n/e.length}const t=e.map(t=>t.lat),n=e.map(t=>t.lon);a={minLat:Math.min(...t),maxLat:Math.max(...t),minLon:Math.min(...n),maxLon:Math.max(...n)}}c.length>0&&(l={type:"MultiLineString",coordinates:c})}const c=i.tags||{},u=LN(c)||"Point of Interest";return{title:RN(c),lat:s,lon:o,bbox:a,geojson:l,url:c.website,osmId:String(i.id),osmType:i.type,osmTags:c,description:c.description,source:"osm",type:u}}}const zN=Object.freeze(Object.defineProperty({__proto__:null,default:FN},Symbol.toStringTag,{value:"Module"}));class DN extends qf{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");controller=null;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}get baseUrl(){return this.settings.photonApi}async search(t,e,n,r=10){if(!t||t.length<2)return[];this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,s=new URLSearchParams({q:t,limit:String(r)});e&&n&&(s.append("lat",parseFloat(e).toFixed(4)),s.append("lon",parseFloat(n).toFixed(4)));const o=`${this.baseUrl}?${s.toString()}`;try{const t=await this.fetchWithRetry(o,{signal:i});if(!t.ok)throw new Error(`Photon request failed with status ${t.status}`);const e=await t.json();return e.features?e.features.map(t=>this.normalizeFeature(t)):[]}catch(ej){return"AbortError"===ej.name||console.error("Photon search error:",ej),[]}}normalizeFeature(t){const e=t.properties||{},n=(t.geometry||{}).coordinates||[],r=n[0],i=n[1],s=[];e.street&&s.push(e.housenumber?`${e.street} ${e.housenumber}`:e.street),e.city&&e.city!==e.name&&s.push(e.city),e.state&&e.state!==e.city&&s.push(e.state),e.country&&s.push(e.country);const o=s.join(", "),a=e.name||o||"Unknown Place",l={...e};e.osm_key&&e.osm_value&&(l[e.osm_key]=e.osm_value);const c=LN(l)||EN(e.osm_value);return{title:a,lat:i,lon:r,osmId:e.osm_id,osmType:{N:"node",W:"way",R:"relation"}[e.osm_type]||e.osm_type,osmTags:l,description:e.name?o:s.slice(1).join(", "),source:"photon",type:c}}async fetchWithRetry(t,e={},n=3){try{const r=await fetch(t,e);return!r.ok&&n>0&&[502,503,504,429].includes(r.status)?(console.warn(`Photon request failed with ${r.status}. Retrying... (${n} left)`),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1)):r}catch(ej){if(n>0&&"AbortError"!==ej.name)return console.debug(`Retrying Photon request... (${n} left)`,ej),await new Promise(t=>setTimeout(t,1e3)),this.fetchWithRetry(t,e,n-1);throw ej}}}const NN=Object.freeze(Object.defineProperty({__proto__:null,default:DN},Symbol.toStringTag,{value:"Module"})),jN={overpassApi:"https://overpass-api.de/api/interpreter",mapKinetic:!0,photonApi:"https://photon.komoot.io/api/",showQuickSearchButtons:!0,nostrPhotoFallbackUploads:!1,nostrReadRelays:null,nostrWriteRelays:null};class BN extends qf{static{dF(this.prototype,"overpassApi",[Is],function(){return jN.overpassApi})}#nt=void fF(this,"overpassApi");static{dF(this.prototype,"mapKinetic",[Is],function(){return jN.mapKinetic})}#rt=void fF(this,"mapKinetic");static{dF(this.prototype,"photonApi",[Is],function(){return jN.photonApi})}#it=void fF(this,"photonApi");static{dF(this.prototype,"showQuickSearchButtons",[Is],function(){return jN.showQuickSearchButtons})}#st=void fF(this,"showQuickSearchButtons");static{dF(this.prototype,"nostrPhotoFallbackUploads",[Is],function(){return jN.nostrPhotoFallbackUploads})}#ot=void fF(this,"nostrPhotoFallbackUploads");static{dF(this.prototype,"nostrReadRelays",[Is],function(){return jN.nostrReadRelays})}#at=void fF(this,"nostrReadRelays");static{dF(this.prototype,"nostrWriteRelays",[Is],function(){return jN.nostrWriteRelays})}#lt=void fF(this,"nostrWriteRelays");overpassApis=[{name:"overpass-api.de (DE)",url:"https://overpass-api.de/api/interpreter"},{name:"private.coffee (AT)",url:"https://overpass.private.coffee/api/interpreter"}];photonApis=[{name:"photon.komoot.io",url:"https://photon.komoot.io/api/"}];constructor(){super(...arguments),this.loadSettings()}loadSettings(){let t={};const e=localStorage.getItem("marco:settings");if(e)try{t=JSON.parse(e)}catch(ej){console.error("Failed to parse settings from localStorage",ej)}else{const e=localStorage.getItem("marco:overpass-api");e&&(t.overpassApi=e);const n=localStorage.getItem("marco:map-kinetic");null!==n&&(t.mapKinetic="true"===n);const r=localStorage.getItem("marco:show-quick-search");null!==r&&(t.showQuickSearchButtons="true"===r);const i=localStorage.getItem("marco:nostr-photo-fallback-uploads");null!==i&&(t.nostrPhotoFallbackUploads="true"===i);const s=localStorage.getItem("marco:photon-api");s&&(t.photonApi=s)}const n={...jN,...t};this.overpassApis.some(t=>t.url===n.overpassApi)||(n.overpassApi=jN.overpassApi),this.overpassApi=n.overpassApi,this.mapKinetic=n.mapKinetic,this.photonApi=n.photonApi,this.showQuickSearchButtons=n.showQuickSearchButtons,this.nostrPhotoFallbackUploads=n.nostrPhotoFallbackUploads,this.nostrReadRelays=n.nostrReadRelays,this.nostrWriteRelays=n.nostrWriteRelays,this.saveSettings()}saveSettings(){const t={overpassApi:this.overpassApi,mapKinetic:this.mapKinetic,photonApi:this.photonApi,showQuickSearchButtons:this.showQuickSearchButtons,nostrPhotoFallbackUploads:this.nostrPhotoFallbackUploads,nostrReadRelays:this.nostrReadRelays,nostrWriteRelays:this.nostrWriteRelays};localStorage.setItem("marco:settings",JSON.stringify(t))}update(t,e){t in jN&&(this[t]=e,this.saveSettings())}}const UN=Object.freeze(Object.defineProperty({__proto__:null,default:BN},Symbol.toStringTag,{value:"Module"}));var $N,qN={exports:{}},VN=($N||($N=1,qN.exports=function(){var t={548:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Access=void 0;class n{constructor(){this.reset()}get scopes(){return Object.keys(this.scopeModeMap).map(t=>({name:t,mode:this.scopeModeMap[t]}))}get scopeParameter(){return this.scopes.map(t=>`${this._scopeNameForParameter(t)}:${t.mode}`).join(" ")}claim(t,e){if("string"!=typeof t||-1!==t.indexOf("/")||0===t.length)throw new Error("Scope should be a non-empty string without forward slashes");if("string"!=typeof e||!e.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(t),this.scopeModeMap[t]=e}get(t){return this.scopeModeMap[t]}remove(t){const e={};for(const n in this.scopeModeMap)e[n]=this.scopeModeMap[n];this.reset(),delete e[t];for(const n in e)this.claim(n,e[n])}checkPermission(t,e){const n=this.get(t);return n&&("r"===e||"rw"===n)}checkPathPermission(t,e){if(this.checkPermission("*",e))return!0;const n=this._getModuleName(t);return!!this.checkPermission(n,e)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(t){if("/"!==t[0])throw new Error("Path should start with a slash");const e=t.replace(/^\/public/,"").match(/^\/([^/]*)\//);return e?e[1]:"*"}_adjustRootPaths(t){"*"in this.scopeModeMap||"*"===t?this.rootPaths=["/"]:t in this.scopeModeMap||(this.rootPaths.push("/"+t+"/"),this.rootPaths.push("/public/"+t+"/"))}_scopeNameForParameter(t){if("*"===t.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return t.name}setStorageType(t){this.storageType=t}static _rs_init(){}}e.Access=n,e.default=n},275:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Authorize=void 0;const s=i(n(334)),o=n(746),a=i(n(503)),l=n(368);let c;function u(t){const e=t||h.getLocation().href,n={};for(const[s,o]of new URL(e).searchParams)n[s]=o;const r=e.indexOf("#");if(-1===r)return n;const i=e.substring(r+1);return i.includes("=")?i.split("&").reduce(function(t,e){const n=e.split("=");if("state"===n[0]&&n[1].match(/rsDiscovery/)){let e=decodeURIComponent(n[1]);const r=e.substr(e.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];t.rsDiscovery=JSON.parse(atob(r)),e=e.replace(new RegExp("&?rsDiscovery="+r),""),e.length>0&&(t.state=e)}else t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]);return t},n):n}class h{static authorize(t,e){if((0,s.default)("[Authorize] authURL = ",e.authURL,"scope = ",e.scope,"redirectUri = ",e.redirectUri,"clientId = ",e.clientId,"response_type =",e.response_type),!e.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,o.localStorageAvailable)()&&"remotestorage"===t.backend){e.redirectUri+=e.redirectUri.indexOf("#")>0?"&":"#";const n={userAddress:t.remote.userAddress,href:t.remote.href,storageApi:t.remote.storageApi,properties:t.remote.properties};e.redirectUri+="rsDiscovery="+(0,o.toBase64)(JSON.stringify(n))}const n=function(t){const e=new URL(t.redirectUri);t.state||(t.state=e.hash?e.hash.substring(1):""),t.response_type||(t.response_type="token");const n=new URL(t.authURL);n.searchParams.set("redirect_uri",t.redirectUri.replace(/#.*$/,"")),n.searchParams.set("scope",t.scope),n.searchParams.set("client_id",t.clientId);for(const r of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const e=t[r];e&&n.searchParams.set(r,e)}return n.href}(e);o.globalContext.cordova?h.openWindow(n,e.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then(e=>{t.remote.configure({token:e.access_token})}):h.setLocation(n)}static refreshAccessToken(t,e,n){return r(this,void 0,void 0,function*(){var t,r,i;yield e.configure({token:null,tokenType:null});const o=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:n}),c=yield(0,l.requestWithTimeout)("POST",e.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),responseType:"json"});if(200!==(null==c?void 0:c.status))throw yield e.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(c.response));{(0,s.default)(`[Authorize] access token good for ${null===(t=null==c?void 0:c.response)||void 0===t?void 0:t.expires_in} seconds`);const n={token:null===(r=null==c?void 0:c.response)||void 0===r?void 0:r.access_token,tokenType:null===(i=null==c?void 0:c.response)||void 0===i?void 0:i.token_type};if(!n.token)throw new Error(`no access_token in "successful" refresh: ${c.response}`);yield e.configure(n)}})}static setLocation(t){if("string"==typeof t)document.location.href=t;else{if("object"!=typeof t)throw"Invalid location "+t;document.location=t}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(t){t.removeEventListener("features-loaded",c)}}e.Authorize=h,h.IMPLIED_FAKE_TOKEN=!1,h.getLocation=function(){return document.location},h.openWindow=function(t,e,n){return new Promise((r,i)=>{const s=open(t,"_blank",n);function o(){i("Authorization was canceled")}s&&!s.closed?(s.addEventListener("loadstart",function(t){if(0!==t.url.indexOf(e))return;s.removeEventListener("exit",o),s.close();const n=u(t.url);n?r(n):i("Authorization error")}),s.addEventListener("exit",o)):i("Authorization popup was blocked")})},h._rs_init=function(t){const e=u();let n;e&&(n=h.getLocation(),n.hash=""),c=function(){let i=!1;if(e){if(e.error)throw"access_denied"===e.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${e.error}`);e.rsDiscovery&&t.remote.configure(e.rsDiscovery),e.access_token&&(t.remote.configure({token:e.access_token}),i=!0),e.remotestorage&&(t.connect(e.remotestorage),i=!0),e.state&&(n=h.getLocation(),h.setLocation(n.href.split("#")[0]+"#"+e.state)),e.code&&(function(e){r(this,void 0,void 0,function*(){var r,i,o,a;const c=sessionStorage.getItem("remotestorage:codeVerifier");if(!c)return void(0,s.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");n=h.getLocation();let u=n.origin;"/"!==n.pathname&&(u+=n.pathname);const d=new URLSearchParams({code:e,grant_type:"authorization_code",client_id:t.remote.clientId,redirect_uri:u,code_verifier:c}),p=yield(0,l.requestWithTimeout)("POST",t.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:d.toString(),responseType:"json"});if(200===p.status){(0,s.default)(`[Authorize] access token good for ${null===(r=null==p?void 0:p.response)||void 0===r?void 0:r.expires_in} seconds`);const e={token:null===(i=null==p?void 0:p.response)||void 0===i?void 0:i.access_token,refreshToken:null===(o=null==p?void 0:p.response)||void 0===o?void 0:o.refresh_token,tokenType:null===(a=null==p?void 0:p.response)||void 0===a?void 0:a.token_type};e.token?t.remote.configure(e):t._emit("error",new Error(`no access_token in "successful" response: ${p.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else t._emit("error",new Error(`${p.statusText}: ${p.response}`))})}(e.code),i=!0),i||t.remote.stopWaitingForToken()}else t.remote.stopWaitingForToken()},t.on("features-loaded",c)},e.default=h},424:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.BaseClient=void 0;const s=i(n(439)),o=i(n(613)),a=i(n(491)),l=i(n(93)),c=i(n(28)),u=n(746);class h{constructor(t,e){if(this.schemas={configurable:!0,get(){return h.Types.inScope(this.moduleName)}},"/"!==e[e.length-1])throw"Not a folder: "+e;"/"===e&&(this.makePath=t=>("/"===t[0]?"":"/")+t),this.storage=t,this.base=e,this.moduleName=function(t){const e=t.split("/");return t.length>2?e[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),t.onChange(this.base,this._fireChange.bind(this))}scope(t){return new h(this.storage,this.makePath(t))}getListing(t,e){return r(this,void 0,void 0,function*(){if("string"!=typeof t)t="";else if(t.length>0&&!(0,u.isFolder)(t))return Promise.reject("Not a folder: "+t);return this.storage.get(this.makePath(t),e).then(t=>404===t.statusCode?{}:t.body)})}getAll(t,e){return r(this,void 0,void 0,function*(){if("string"!=typeof t)t="";else if(t.length>0&&!(0,u.isFolder)(t))return Promise.reject("Not a folder: "+t);return this.storage.get(this.makePath(t),e).then(n=>{if(404===n.statusCode)return{};if("object"==typeof n.body){const r=Object.keys(n.body);if(0===r.length)return{};const i=r.map(r=>this.storage.get(this.makePath(t+r),e).then(t=>{if("string"==typeof t.body)try{t.body=JSON.parse(t.body)}catch(t){}"object"==typeof t.body&&(n.body[r]=t.body)}));return Promise.all(i).then(()=>n.body)}})})}getFile(t,e){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(t),e).then(t=>({data:t.body,contentType:t.contentType,revision:t.revision}))})}storeFile(t,e,n){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'contentType' of baseClient.storeFile must be a string"):"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof n&&"object"!=typeof n?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(e),n,t).then(t=>200===t.statusCode||201===t.statusCode?t.revision:Promise.reject("Request (PUT "+this.makePath(e)+") failed with status: "+t.statusCode)))})}getObject(t,e){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(t),e).then(e=>{if("object"==typeof e.body)return e.body;if("string"==typeof e.body)try{return JSON.parse(e.body)}catch(e){throw new Error("Not valid JSON: "+this.makePath(t))}else if(void 0!==e.body&&200===e.statusCode)return Promise.reject("Not an object: "+this.makePath(t))})})}storeObject(t,e,n){return r(this,void 0,void 0,function*(){if("string"!=typeof t)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof e)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof n)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(n,t);try{const t=this.validate(n);if(!t.valid)return Promise.reject(t)}catch(t){return Promise.reject(t)}return this.storage.put(this.makePath(e),JSON.stringify(n),"application/json; charset=UTF-8").then(t=>200===t.statusCode||201===t.statusCode?t.revision:Promise.reject("Request (PUT "+this.makePath(e)+") failed with status: "+t.statusCode))})}remove(t){return r(this,void 0,void 0,function*(){return"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(t),this.storage.connected))})}getItemURL(t){if("string"!=typeof t)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(t=(0,u.cleanPath)(this.makePath(t)),this.storage.remote.href+t):void 0}cache(t,e="ALL"){if("string"!=typeof t)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof e)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==e&&"SEEN"!==e&&"ALL"!==e)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(t),e),this}declareType(t,e,n){let r;if(n&&"string"==typeof e)r=e;else if(n||"string"==typeof e){if(!n&&"string"==typeof e)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else n=e,r=this._defaultTypeURI(t);h.Types.declare(this.moduleName,t,r,n)}validate(t){const e=h.Types.getSchema(t["@context"]);if(e)return s.default.validateResult(t,e);throw new a.default(t["@context"])}_defaultTypeURI(t){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(t)}_attachType(t,e){t["@context"]=h.Types.resolveAlias(this.moduleName+"/"+e)||this._defaultTypeURI(e)}makePath(t){return this.base+(t||"")}_fireChange(t){c.default.changeEvents[t.origin]&&(["new","old","lastCommon"].forEach(function(e){if((!t[e+"ContentType"]||/^application\/(.*)json(.*)/.exec(t[e+"ContentType"]))&&"string"==typeof t[e+"Value"])try{t[e+"Value"]=JSON.parse(t[e+"Value"])}catch(t){}}),this._emit("change",t))}static _rs_init(){}}e.BaseClient=h,h.Types=o.default,(0,u.applyMixins)(h,[l.default]),e.default=h},285:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Caching=void 0;const i=n(746),s=r(n(334));class o{constructor(t){this.pendingActivations=[],this._access=t.access,this.reset()}set(t,e){if("string"!=typeof t)throw new Error("path should be a string");if(!(0,i.isFolder)(t))throw new Error("path should be a folder");if(!this._access.checkPathPermission(t,"r"))throw new Error('No access to path "'+t+'". You must claim access to it first.');if(void 0===e||!e.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[t]=e,"ALL"===e&&(this.activateHandler?this.activateHandler(t):this.pendingActivations.push(t))}enable(t){this.set(t,"ALL")}disable(t){this.set(t,"FLUSH")}onActivate(t){(0,s.default)("[Caching] Setting activate handler",t,this.pendingActivations),this.activateHandler=t;for(let e=0;e{this.emitChange(t.data)})}get(t,e,n){return r(this,void 0,void 0,function*(){return"number"==typeof e?this.getNodes((0,c.pathsFromRoot)(t)).then(r=>{const i=u(r[t]);return h(r,e)?n(t):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}}):this.getNodes([t]).then(e=>{const n=u(e[t]);if(n){if((0,c.isFolder)(t))for(const t in n.itemsMap)n.itemsMap.hasOwnProperty(t)&&!1===n.itemsMap[t]&&delete n.itemsMap[t];return{statusCode:200,body:n.body||n.itemsMap,contentType:n.contentType}}return{statusCode:404}})})}put(t,e,n){return r(this,void 0,void 0,function*(){const r=(0,c.pathsFromRoot)(t);return this._updateNodes(r,function(t,r){try{for(let i=0,s=t.length;i0)break}else console.error("Cannot delete non-existing node "+i)}return n})})}flush(t){return this._getAllDescendentPaths(t).then(t=>this.getNodes(t)).then(t=>{for(const e in t){const n=t[e];n&&n.common&&n.local&&this.emitChange({path:n.path,origin:"local",oldValue:!1===n.local.body?void 0:n.local.body,newValue:!1===n.common.body?void 0:n.common.body}),t[e]=void 0}return this.setNodes(t)})}emitChange(t){a.default.changeEvents[t.origin]&&this._emit("change",t)}fireInitial(){a.default.changeEvents.local&&this.forAllNodes(t=>{if((0,c.isDocument)(t.path)){const e=u(t);e&&this.emitChange({path:t.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:e.body,newContentType:e.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(t){this.diffHandler=t}_updateNodes(t,e){return new Promise((n,r)=>{this._doUpdateNodes(t,e,{resolve:n,reject:r})})}_doUpdateNodes(t,e,n){return r(this,void 0,void 0,function*(){if(this._updateNodesRunning)return void this._updateNodesQueued.push({paths:t,cb:e,promise:n});this._updateNodesRunning=!0;try{let r=yield this.getNodes(t);const i=(0,c.deepClone)(r),s=[];r=e(t,r);for(const t in r){const e=r[t];(0,c.equal)(e,i[t])?delete r[t]:(0,c.isDocument)(t)&&((0,c.equal)(e.local.body,e.local.previousBody)&&e.local.contentType===e.local.previousContentType||s.push({path:t,origin:"window",oldValue:e.local.previousBody,newValue:!1===e.local.body?void 0:e.local.body,oldContentType:e.local.previousContentType,newContentType:e.local.contentType}),void 0===e.local.body?r[t]=void 0:(delete e.local.previousBody,delete e.local.previousContentType))}yield this.setNodes(r),this._emitChangeEvents(s),n.resolve({statusCode:200})}catch(t){n.reject(t)}this._updateNodesRunning=!1;const r=this._updateNodesQueued.shift();r&&(yield this._doUpdateNodes(r.paths,r.cb,r.promise))})}_emitChangeEvents(t){for(let e=0,n=t.length;e{const n=[t],r=u(e[t]),i=Object.keys(r.itemsMap).map(e=>this._getAllDescendentPaths(t+e).then(t=>{for(let e=0,r=t.length;en)}):Promise.resolve([t])}_getInternals(){return{getLatest:u,makeNode:d,isOutdated:h}}}(0,c.applyMixins)(f,[o.default]),t.exports=f},28:function(t){t.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},373:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(199)),s=r(n(28)),o=r(n(334)),a=n(746);let l;const c="remotestorage:discover";let u={};const h=function(t){return new Promise((e,n)=>{if(t in u)return e(u[t]);const r=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:s.default.discoveryTimeout});return setTimeout(()=>n(new Error("timed out")),s.default.discoveryTimeout),r.lookup(t,function(r,i){if(r)return n(r);if("object"!=typeof i.idx.links.remotestorage||"number"!=typeof i.idx.links.remotestorage.length||i.idx.links.remotestorage.length<=0)return(0,o.default)("[Discover] WebFinger record for "+t+" does not have remotestorage defined in the links section ",JSON.stringify(i.json)),n("WebFinger record for "+t+" does not have remotestorage defined in the links section.");const s=i.idx.links.remotestorage[0],a=s.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||s.properties["auth-endpoint"],h=s.properties["http://remotestorage.io/spec/version"]||s.type;return u[t]={href:s.href,storageApi:h,authURL:a,properties:s.properties},l&&localStorage.setItem(c,JSON.stringify({cache:u})),e(u[t])})})};(h.DiscoveryError=function(t){this.name="DiscoveryError",this.message=t,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),h.DiscoveryError.prototype.constructor=h.DiscoveryError,h._rs_init=function(){if(l=(0,a.localStorageAvailable)(),l){const t=JSON.parse(localStorage.getItem(c));t&&(u=t.cache)}},h._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},h._rs_cleanup=function(){l&&localStorage.removeItem(c)},t.exports=h},706:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(93)),o=i(n(424)),a=i(n(941)),l=i(n(982)),c=i(n(503)),u=n(746),h=n(368),d=n(684),p=i(n(275));let f;const g="remotestorage:dropbox",m="https://api.dropboxapi.com/2/files/list_folder",y="https://api.dropboxapi.com/2/files/list_folder/continue",v="/remotestorage";function b(t){return(v+"/"+t).replace(/\/+$/,"").replace(/\/+/g,"/")}const w=/[\u007f-\uffff]/g;function _(t){return JSON.stringify(t).replace(w,function(t){return"\\u"+("000"+t.charCodeAt(0).toString(16)).slice(-4)})}function x(t,e){return new RegExp("^"+e.join("\\/")+"(\\/|$)").test(t.error_summary)}function C(t){return t instanceof ArrayBuffer||(0,h.isArrayBufferView)(t)}class S extends d.RemoteBase{constructor(t){if(super(t),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=t.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},f=(0,u.localStorageAvailable)(),f){const t=(0,u.getJSONFromLocalStorage)(g);t&&this.configure(t),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return r(this,void 0,void 0,function*(){try{if(this.rs.setBackend("dropbox"),this.token)T(this.rs);else{const{codeVerifier:t,codeChallenge:e,state:n}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",t),sessionStorage.setItem("remotestorage:state",n),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:n,code_challenge:e,code_challenge_method:"S256",token_access_type:"offline"})}}catch(t){throw this.rs._emit("error",t),this.rs.setBackend(void 0),t}})}configure(t){return r(this,void 0,void 0,function*(){void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.token&&(this.token=t.token),void 0!==t.refreshToken&&(this.refreshToken=t.refreshToken),void 0!==t.tokenType&&(this.tokenType=t.tokenType);const e=()=>{f&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),e();else try{const t=yield this.info();this.userAddress=t.email,this._emit("connected"),e()}catch(t){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),e.apply(this)}else(()=>{this.connected=!1,f&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()})}_getFolder(t){const e=this._revCache,n=n=>{let i;if(200!==n.status&&409!==n.status)return Promise.reject("Unexpected response status: "+n.status);try{i=JSON.parse(n.responseText)}catch(t){return Promise.reject(t)}if(409===n.status)return x(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const s=i.entries.reduce((n,r)=>{try{const i="folder"===r[".tag"],s=r.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)n[s]={ETag:e.get(t+s)};else{const e=new Date(r.server_modified);n[s]={ETag:r.rev,"Content-Length":r.size,"Last-Modified":e.toUTCString()},this._revCache.set(t+s,r.rev)}}catch(e){console.error(`[Dropbox] folder “${t}” has entry ${JSON.stringify(r)}:`,e)}return n},{});return i.has_more?r(i.cursor).then(function(t){return Object.assign(s,t)}):Promise.resolve(s)},r=t=>{const e={body:{cursor:t}};return this._request("POST",y,e).then(n)};return this._request("POST",m,{body:{path:b(t)}}).then(n).then(function(n){return Promise.resolve({statusCode:200,body:n,contentType:"application/json; charset=UTF-8",revision:e.get(t)})})}get(t,e={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");const n=this._revCache.get(t);if(null===n)return Promise.resolve({statusCode:404});if(e&&e.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(t,e));if(n&&n===e.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===t.slice(-1))return this._getFolder(t);const r={headers:{"Dropbox-API-Arg":_({path:b(t)})},responseType:"arraybuffer"};return e&&e.ifNoneMatch&&(r.headers["If-None-Match"]=e.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",r).then(e=>{const n=e.status;let r,i,s,o;return 200!==n&&409!==n?Promise.resolve({statusCode:n}):(r=e.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(e.response,"UTF-8").then(a=>{i=a,409===n&&(r=i);try{r=JSON.parse(r)}catch(t){return Promise.reject(t)}if(409===n)return x(r,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+t+'"): '+r.error_summary));if(s=e.getResponseHeader("Content-Type"),o=r.rev,this._revCache.set(t,o),this._shareIfNeeded(t),(0,u.shouldBeTreatedAsBinary)(a,s))i=e.response;else try{i=JSON.parse(i),s="application/json; charset=UTF-8"}catch(t){}return{statusCode:n,body:i,contentType:s,revision:o}}))})}put(t,e,n){return r(this,arguments,void 0,function*(t,e,n,r={}){if(!this.connected)throw new Error("not connected (path: "+t+")");const i=this._revCache.get(t);if(r&&r.ifMatch&&i&&i!==r.ifMatch)return{statusCode:412,revision:i};if(r&&"*"===r.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!n.match(/charset=/)&&C(e)&&(n+="; charset=binary"),e.length>157286400)throw new Error("Cannot upload file larger than 150MB");const s={body:e,contentType:n,path:t};if(r&&(r.ifMatch||"*"===r.ifNoneMatch)){const e=yield this._getMetadata(t);if(r&&"*"===r.ifNoneMatch&&e)return{statusCode:412,revision:e.rev};if(r&&r.ifMatch&&e&&e.rev!==r.ifMatch)return{statusCode:412,revision:e.rev}}const o=yield this._uploadSimple(s);return this._shareIfNeeded(t),o})}delete(t){return r(this,arguments,void 0,function*(t,e={}){if(!this.connected)throw new Error("not connected (path: "+t+")");const n=this._revCache.get(t);if((null==e?void 0:e.ifMatch)&&n&&e.ifMatch!==n)return{statusCode:412,revision:n};if(null==e?void 0:e.ifMatch){const n=yield this._getMetadata(t);if((null==e?void 0:e.ifMatch)&&n&&n.rev!==e.ifMatch)return{statusCode:412,revision:n.rev}}return this._deleteSimple(t)})}_shareIfNeeded(t){if(t.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[t])return this.share(t)}share(t){const e={body:{path:b(t)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",e).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let n;try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?x(n,["shared_link_already_exists"])?this._getSharedLink(t):Promise.reject(new Error("API error: "+n.error_summary)):Promise.resolve(n.url)}).then(e=>(this._itemRefs[t]=e,f&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(e)),e=>(e.message='Sharing Dropbox file or folder ("'+t+'") failed: '+e.message,Promise.reject(e)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then(function(t){let e;try{const n=JSON.parse(t.responseText);e=null==n?void 0:n.email}catch(e){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+t.responseText))}return Promise.resolve({email:e})})}_request(t,e,n){return r(this,arguments,void 0,function*(t,e,n,r=1){if(this.isForbiddenRequestMethod(t,e))throw`Don't use ${t} on directories!`;if(!this.token)throw new c.default("No access token");n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,"object"!=typeof n.body||C(n.body)||(n.body=JSON.stringify(n.body),n.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:t,isFolder:(0,u.isFolder)(e)});try{const i=yield(0,h.requestWithTimeout)(t,e,n);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?r>=3?(console.error(`Abandoned after ${r} attempts: ${t} ${e}`),i):(this.rs._emit("wire-busy",{method:t,isFolder:(0,u.isFolder)(e)}),yield p.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!0}),this._request(t,e,n,r+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),r>=3?(console.warn(`Abandoned after ${r} attempts: ${t} ${e}`),i):(yield new Promise(t=>setTimeout(t,(0,h.retryAfterMs)(i))),this._request(t,e,n,r+1))):i}catch(n){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,u.isFolder)(e),success:!1}),n}})}fetchDelta(...t){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const e=t=>r(this,void 0,void 0,function*(){let n,r;"string"==typeof t?(n=y,r={cursor:t}):(n=m,r={path:v,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",n,{body:r});if(401===i.status)throw new c.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let s;try{s=JSON.parse(i.responseText)}catch(t){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!x(s,["path","not_found"]))throw new Error("API returned an error: "+s.error_summary);s={cursor:null,entries:[],has_more:!1}}if(t||this._revCache.deactivatePropagation(),s.entries.forEach(t=>{const e=t.path_display.slice(14);"deleted"===t[".tag"]?(this._revCache.delete(e),this._revCache.delete(e+"/")):"file"===t[".tag"]&&this._revCache.set(e,t.rev)}),this._fetchDeltaCursor=s.cursor,s.has_more)return e(s.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(t){if("timeout"===t)return;throw t}});return this._fetchDeltaPromise=e(this._fetchDeltaCursor).catch(t=>("object"==typeof t&&"message"in t?t.message="Dropbox: fetchDelta: "+t.message:t=`Dropbox: fetchDelta: ${t}`,this.rs._emit("error",t),this._fetchDeltaPromise=null,Promise.reject(t))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(t))),this._fetchDeltaPromise}_getMetadata(t){const e={path:b(t)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:e}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?x(e,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+e.error_summary)):Promise.resolve(e)}).then(void 0,e=>(e.message='Could not load metadata for file or folder ("'+t+'"): '+e.message,Promise.reject(e)))}_uploadSimple(t){const e={path:b(t.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return t.ifMatch&&(e.mode={".tag":"update",update:t.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:t.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":_(e)}}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let n;try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid API result: "+e.responseText))}return 409===e.status?x(n,["path","conflict"])?this._getMetadata(t.path).then(function(t){return Promise.resolve({statusCode:412,revision:t.rev})}):(this.rs._emit("error",new Error(n.error_summary)),Promise.resolve({statusCode:e.status})):(this._revCache.set(t.path,n.rev),Promise.resolve({statusCode:e.status,revision:n.rev}))})}_deleteSimple(t){const e={path:b(t)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:e}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}if(409===t.status){if(x(e,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(e.error_summary))}return Promise.resolve({statusCode:t.status})}).then(e=>(200!==e.statusCode&&404!==e.statusCode||(this._revCache.delete(t),delete this._itemRefs[t]),Promise.resolve(e)),e=>(e.message='Could not delete Dropbox file or folder ("'+t+'"): '+e.message,Promise.reject(e)))}_getSharedLink(t){return r(this,void 0,void 0,function*(){const e={body:{path:b(t),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",e).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status: "+t.status));let e;try{e=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?Promise.reject(new Error("API error: "+(null==e?void 0:e.error_summary)||0)):e.links.length?Promise.resolve(e.links[0].url):Promise.reject(new Error("No links returned"))},e=>(e.message='Could not get link to a shared file or folder ("'+t+'"): '+e.message,Promise.reject(e)))})}static _rs_init(t){f=(0,u.localStorageAvailable)(),t.apiKeys.dropbox&&(t.dropbox=new S(t)),"dropbox"===t.backend&&T(t)}static _rs_supported(){return!0}static _rs_cleanup(t){!function(t){(function(t){t._origRemote&&(t.remote=t._origRemote,delete t._origRemote)})(t),function(t){t._dropboxOrigSync&&(t.sync.sync=t._dropboxOrigSync,delete t._dropboxOrigSync)}(t),function(t){t._origBaseClientGetItemURL&&(o.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}(t),E(t)}(t),f&&localStorage.removeItem(g),t.setBackend(void 0)}}function k(t,...e){t._dropboxOrigSync||(t._dropboxOrigSync=t.sync.sync.bind(t.sync),t.sync.sync=function(){return this.dropbox.fetchDelta(t,...e).then(t._dropboxOrigSync,function(e){t._emit("error",new l.default(e)),t._emit("sync-done")})}.bind(t))}function E(t){t._dropboxOrigSyncCycle&&(t.syncCycle=t._dropboxOrigSyncCycle,delete t._dropboxOrigSyncCycle)}function T(t){!function(t){t._origRemote||(t._origRemote=t.remote,t.remote=t.dropbox)}(t),t.sync?k(t):function(t,...e){t._dropboxOrigSyncCycle||(t._dropboxOrigSyncCycle=t.syncCycle,t.syncCycle=()=>{if(!t.sync)throw new Error("expected sync to be initialized by now");k(t),t._dropboxOrigSyncCycle(t,...e),E(t)})}(t),function(t){t._origBaseClientGetItemURL||(t._origBaseClientGetItemURL=o.default.prototype.getItemURL,o.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(t)}(0,u.applyMixins)(S,[s.default]),t.exports=S},451:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(93)),s=n(746),o=r(n(334));class a{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?((0,o.default)("[Env] Going into background mode"),this.goBackground()):((0,o.default)("[Env] Going into foreground mode"),this.goForeground())}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,s.applyMixins)(a,[i.default]),t.exports=a},93:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.EventHandling=void 0;const i=r(n(334));class s{addEvents(t){t.forEach(t=>this._addEvent(t))}addEventListener(t,e){if("string"!=typeof t)throw new Error("Argument eventName should be a string");if("function"!=typeof e)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",t),this._validateEvent(t),this._handlers[t].push(e)}on(t,e){return this.addEventListener(t,e)}removeEventListener(t,e){this._validateEvent(t);const n=this._handlers[t].length;for(let r=0;r{t(...e)})}_validateEvent(t){if(!(t in this._handlers))throw new Error("Unknown event: "+t)}_delegateEvent(t,e){e.on(t,e=>{this._emit(t,e)})}_addEvent(t){void 0===this._handlers&&(this._handlers={}),this._handlers[t]=[]}}e.EventHandling=s,e.default=s},545:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(28)),s=r(n(451)),o=r(n(334)),a=n(746),l=r(n(370)),c=r(n(548)),u=r(n(275)),h=r(n(373)),d=r(n(424)),p=r(n(801)),f=r(n(706)),g=r(n(600)),m=r(n(313)),y=r(n(285)),v=r(n(567)),b=r(n(794)),w=r(n(365)),_={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:g.default,Dropbox:f.default,GoogleDrive:p.default,Access:c.default,Discover:h.default,Authorize:u.default,BaseClient:d.default,Env:s.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:y.default,IndexedDB:v.default,LocalStorage:b.default,InMemoryStorage:w.default,Sync:m.default}),i.default.disableFeatures.forEach(t=>{this.featureModules[t]&&delete this.featureModules[t]}),this._allLoaded=!1;for(const t in this.featureModules)this.loadFeature(t)},hasFeature(t){for(let e=this.features.length-1;e>=0;e--)if(this.features[e].name===t)return this.features[e].supported;return!1},loadFeature(t){const e=this.featureModules[t],n=!e._rs_supported||e._rs_supported();(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initializing ...`),"object"==typeof n?n.then(()=>{this.featureSupported(t,!0),this.initFeature(t)},()=>{this.featureSupported(t,!1)}):"boolean"==typeof n?(this.featureSupported(t,n),n&&this.initFeature(t)):this.featureSupported(t,!1)},initFeature(t){const e=this.featureModules[t];let n;try{n=e._rs_init(this)}catch(e){return void this.featureFailed(t,e)}"object"==typeof n&&"function"==typeof n.then?n.then(()=>{this.featureInitialized(t)},e=>{this.featureFailed(t,e)}):this.featureInitialized(t)},featureFailed(t,e){(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initialization failed (${e})`),this.featureDone()},featureSupported(t,e){(0,o.default)(`[RemoteStorage] [FEATURE ${t}]${e?"":"not "} supported`),e||this.featureDone()},featureInitialized(t){(0,o.default)(`[RemoteStorage] [FEATURE ${t}] initialized`),this.features.push({name:t,init:this.featureModules[t]._rs_init,supported:!0,cleanup:this.featureModules[t]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(t=>{if(this.features.some(e=>e.name===t))return this.features.local=this.featureModules[t],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(t){console.error("'ready' failed: ",t,t.stack),this._emit("error",t)}},featuresLoaded(){(0,o.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(l.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._emit("not-connected")}),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(t){(0,a.logError)(t),this._emit("error",t)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let t=0;t=n-this.maxAge?e.v:void 0}set(t,e){this._items[t]={v:e,t:(new Date).getTime()}}}class v extends l.RemoteBase{constructor(t,e){if(super(t),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=e,this._fileIdCache=new y(300),d=(0,o.localStorageAvailable)(),d){const t=(0,o.getJSONFromLocalStorage)(u);t&&this.configure(t)}}configure(t){void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.token&&(this.token=t.token);const e=function(){d&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},n=function(){this.connected=!1,delete this.token,d&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),e.apply(this)):this.info().then(t=>{this.userAddress=t.user.emailAddress,this._emit("connected"),e.apply(this)}).catch(()=>{n.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):n.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(t,e={}){return(0,o.isFolder)(t)?this._getFolder(m(t)):this._getFile(m(t),e)}put(t,e,n,r={}){const i=m(t);function s(t){if(t.status>=200&&t.status<300){const e=JSON.parse(t.responseText),n=this.stripQuotes(e.etag);return Promise.resolve({statusCode:200,contentType:e.mimeType,revision:n})}return 412===t.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+t.status+" ("+t.responseText+")")}return this._getFileId(i).then(t=>t?r&&"*"===r.ifNoneMatch?s({status:412}):this._updateFile(t,i,e,n,r).then(s):this._createFile(i,e,n).then(s))}delete(t,e={}){const n=m(t);return this._getFileId(n).then(t=>t?this._getMeta(t).then(n=>{let r;return"object"==typeof n&&"string"==typeof n.etag&&(r=this.stripQuotes(n.etag)),e&&e.ifMatch&&e.ifMatch!==r?{statusCode:412,revision:r}:this._request("DELETE",c+"/drive/v2/files/"+t,{}).then(t=>200===t.status||204===t.status?{statusCode:200}:Promise.reject("Delete failed: "+t.status+" ("+t.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){const t=c+"/drive/v2/about?fields=user";return this._request("GET",t,{}).then(function(t){try{const e=JSON.parse(t.responseText);return Promise.resolve(e)}catch(t){return Promise.reject(t)}})}_updateFile(t,e,n,r,i){const s={mimeType:r},o={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(o["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",c+"/upload/drive/v2/files/"+t+"?uploadType=resumable",{body:JSON.stringify(s),headers:o}).then(t=>412===t.status?t:this._request("PUT",t.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(n):n}))}_createFile(t,e,n){return this._getParentId(t).then(r=>{const i={title:p(g(t)),mimeType:n,parents:[{kind:"drive#fileLink",id:r}]};return this._request("POST",c+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(t=>this._request("POST",t.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(e):e}))})}_getFile(t,e){return this._getFileId(t).then(t=>this._getMeta(t).then(t=>{let n;if("object"==typeof t&&"string"==typeof t.etag&&(n=this.stripQuotes(t.etag)),e&&e.ifNoneMatch&&n===e.ifNoneMatch)return Promise.resolve({statusCode:304});if(!t.downloadUrl){if(!t.exportLinks||!t.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:t.mimeType,revision:n});t.mimeType+=";export=text/html",t.downloadUrl=t.exportLinks["text/html"]}return this._request("GET",t.downloadUrl,{responseType:"arraybuffer"}).then(e=>(0,o.getTextFromArrayBuffer)(e.response,"UTF-8").then(function(r){let i=r;if(t.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(t){}else(0,o.shouldBeTreatedAsBinary)(r,t.mimeType)&&(i=e.response);return{statusCode:200,body:i,contentType:t.mimeType,revision:n}}))}))}_getFolder(t){return this._getFileId(t).then(e=>{let n,r,i;if(!e)return Promise.resolve({statusCode:404});const s="'"+e+"' in parents";return this._request("GET",c+"/drive/v2/files?q="+encodeURIComponent(s)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(e=>{var s;if(200!==e.status)return Promise.reject("request failed or something: "+e.status);try{n=JSON.parse(e.responseText)}catch(t){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const a of n.items)(null===(s=a.labels)||void 0===s?void 0:s.trashed)||(r=this.stripQuotes(a.etag),a.mimeType===h?(this._fileIdCache.set(t+(0,o.cleanPath)(a.title)+"/",a.id),i[a.title+"/"]={ETag:r}):(this._fileIdCache.set(t+(0,o.cleanPath)(a.title),a.id),i[a.title]={ETag:r,"Content-Type":a.mimeType,"Content-Length":a.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(t){const e=f(t);return this._getFileId(e).then(t=>t?Promise.resolve(t):this._createFolder(e))}_createFolder(t){return this._getParentId(t).then(e=>this._request("POST",c+"/drive/v2/files",{body:JSON.stringify({title:p(g(t)),mimeType:h,parents:[{id:e}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(t=>{const e=JSON.parse(t.responseText);return Promise.resolve(e.id)}))}_getFileId(t){let e;return"/"===t?Promise.resolve("root"):(e=this._fileIdCache.get(t))?Promise.resolve(e):this._getFolder(f(t)).then(()=>(e=this._fileIdCache.get(t),e?Promise.resolve(e):"/"===t.substr(-1)?this._createFolder(t).then(()=>this._getFileId(t)):Promise.resolve()))}_getMeta(t){return this._request("GET",c+"/drive/v2/files/"+t,{}).then(function(e){return 200===e.status?Promise.resolve(JSON.parse(e.responseText)):Promise.reject("request (getting metadata for "+t+") failed with status: "+e.status)})}_request(t,e,n){return this.isForbiddenRequestMethod(t,e)?Promise.reject(`Don't use ${t} on directories!`):(n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:t,isFolder:(0,o.isFolder)(e)}),(0,a.requestWithTimeout)(t,e,n).then(n=>n&&401===n.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,o.isFolder)(e),success:!0}),Promise.resolve(n)),n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,o.isFolder)(e),success:!1}),Promise.reject(n))))}static _rs_init(t){const e=t.apiKeys.googledrive;var n;e&&(t.googledrive=new v(t,e.clientId),"googledrive"===t.backend&&(t._origRemote=t.remote,t.remote=t.googledrive,(n=t)._origBaseClientGetItemURL||(n._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(t){var e;t.setBackend(void 0),t._origRemote&&(t.remote=t._origRemote,delete t._origRemote),(e=t)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}}(0,o.applyMixins)(v,[s.default]),t.exports=v},567:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(93)),o=i(n(496)),a=i(n(334)),l=n(746),c="remotestorage";let u;class h extends o.default{constructor(t){super(),this.addEvents(["change","local-events-done"]),this.db=t||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(t){return r(this,void 0,void 0,function*(){const e=[],n={};for(let r=0,i=t.length;r0?this.getNodesFromDb(e).then(function(t){for(const e in n)t[e]=n[e];return t}):n})}setNodes(t){return r(this,void 0,void 0,function*(){for(const e in t)this.changesQueued[e]=t[e]||!1;this.maybeFlush()})}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=n.g.setInterval(function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(t){return new Promise((e,n)=>{const r=this.db.transaction(["nodes"],"readonly"),i=r.objectStore("nodes"),s={};this.getsRunning++,t.map(t=>{i.get(t).onsuccess=e=>{s[t]=e.target.result}}),r.oncomplete=()=>{e(s),this.getsRunning--},r.onerror=r.onabort=()=>{n("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(t){return r(this,void 0,void 0,function*(){return new Promise((e,n)=>{const r=this.db.transaction(["nodes"],"readwrite"),i=r.objectStore("nodes"),s=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting puts",t,this.putsRunning);for(const o in t){const e=t[o];if("object"==typeof e)try{i.put(e)}catch(t){throw(0,a.default)("[IndexedDB] Error while putting",e,t),t}else try{i.delete(o)}catch(t){throw(0,a.default)("[IndexedDB] Error while removing",i,e,t),t}}r.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished puts",t,this.putsRunning,(new Date).getTime()-s+"ms"),e()},r.onerror=()=>{this.putsRunning--,n("transaction error")},r.onabort=()=>{n("transaction abort"),this.putsRunning--}})})}reset(t){const e=this.db.name;this.db.close(),h.clean(e,()=>{h.open(e,(n,r)=>{n?(0,a.default)(`[IndexedDB] Error while resetting database ${e}:`,n):this.db=r,"function"==typeof t&&t(self)})})}forAllNodes(t){return r(this,void 0,void 0,function*(){return new Promise(e=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=n=>{const r=n.target.result;r?(t(r.value),r.continue()):e()}})})}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(t,e){const n=setTimeout(function(){e("timeout trying to open db")},1e4);try{const r=indexedDB.open(t,2);r.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",r),clearTimeout(n),e(r.error)},r.onupgradeneeded=function(t){const e=r.result;(0,a.default)("[IndexedDB] Upgrade: from ",t.oldVersion," to ",t.newVersion),1!==t.oldVersion&&((0,a.default)("[IndexedDB] Creating object store: nodes"),e.createObjectStore("nodes",{keyPath:"path"})),(0,a.default)("[IndexedDB] Creating object store: changes"),e.createObjectStore("changes",{keyPath:"path"})},r.onsuccess=function(){clearTimeout(n);const i=r.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),void h.clean(t,function(){h.open(t,e)});e(null,r.result)}}catch(r){(0,a.default)("[IndexedDB] Failed to open database: "+r),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(n),h.clean(t,function(){h.open(t,e)})}}static clean(t,e){const n=indexedDB.deleteDatabase(t);n.onsuccess=function(){(0,a.default)(`[IndexedDB] Deleted database "${t}"`),e()},n.onerror=n.onabort=function(e){console.error('Failed to remove database "'+t+'"',e)}}static _rs_init(t){return new Promise((e,n)=>{h.open(c,function(r,i){r?n(r):(u=i,i.onerror=()=>{t._emit("error",r)},e())})})}static _rs_supported(){return new Promise((t,e)=>{const n=(0,l.getGlobalContext)();let r=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(r=!0)),"indexedDB"in n&&!r)try{const n=indexedDB.open("rs-check");n.onerror=function(){e()},n.onsuccess=function(){n.result.close(),indexedDB.deleteDatabase("rs-check"),t()}}catch(t){e()}else e()})}static _rs_cleanup(t){return new Promise(e=>{t.local instanceof h&&t.local.closeDB(),h.clean(c,e)})}diffHandler(){}}(0,l.applyMixins)(h,[s.default]),t.exports=h},365:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const i=r(n(93)),s=r(n(496)),o=n(746);class a extends s.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(t){const e={};for(let n=0,r=t.length;n=2e3&&t<=36e5}var E;!function(t){t.GOOGLE="googledrive",t.DROPBOX="dropbox"}(E||(E={}));class T{constructor(t){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=w.default.loadFeatures,this.features=w.default.features,this.loadFeature=w.default.loadFeature,this.featureSupported=w.default.featureSupported,this.featureDone=w.default.featureDone,this.featuresDone=w.default.featuresDone,this.featuresLoaded=w.default.featuresLoaded,this.featureInitialized=w.default.featureInitialized,this.featureFailed=w.default.featureFailed,this.hasFeature=w.default.hasFeature,this._setCachingModule=w.default._setCachingModule,this._collectCleanupFunctions=w.default._collectCleanupFunctions,this._fireReady=w.default._fireReady,this.initFeature=w.default.initFeature,"object"==typeof t&&(0,c.extend)(a.default,t),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-started","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),C=(0,c.localStorageAvailable)(),C){this.apiKeys=(0,c.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const t=localStorage.getItem("remotestorage:backend");"dropbox"===t||"googledrive"===t?this.setBackend(t):this.setBackend("remotestorage")}const e=this.on;this.on=function(t,n){if(this._allLoaded)switch(t){case"features-loaded":setTimeout(n,0);break;case"ready":this.remote&&setTimeout(n,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(n,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(n,0)}return e.call(this,t,n)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){a.default.modules.forEach(this.addModule.bind(this))}authorize(t){if(this.access.setStorageType(this.remote.storageApi),void 0===t.scope&&(t.scope=this.access.scopeParameter),x.cordova)t.redirectUri=a.default.cordovaRedirectUri;else{const e=h.default.getLocation();let n=e.origin;"/"!==e.pathname&&(n+=e.pathname),t.redirectUri=n}void 0===t.clientId&&(t.clientId=t.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h.default.authorize(this,t)}impliedauth(t,e){t=t||this.remote.storageApi,e=e||String(document.location),(0,l.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+t+" redirectUri = "+e),this.remote.configure({token:h.default.IMPLIED_FAKE_TOKEN}),document.location.href=e}connect(t,e){if(this.setBackend("remotestorage"),t.indexOf("@")<0&&!t.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new T.DiscoveryError("Not a valid user address or URL."));else{if(t.indexOf("@")<0&&!t.match(/^https?:\/\//)&&(t=`https://${t}`),x.cordova){if("string"!=typeof a.default.cordovaRedirectUri)return void this._emit("error",new T.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!x.cordova.InAppBrowser)return void this._emit("error",new T.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:t}),this._emit("connecting"),(0,y.default)(t).then(n=>{if(this._emit("authing"),n.userAddress=t,this.remote.configure(n),!this.remote.connected)if(n.authURL)if(void 0===e)this.authorize({authURL:n.authURL});else{if("string"!=typeof e)throw new Error("Supplied bearer token must be a string");(0,l.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:e})}else this.impliedauth()},()=>{this._emit("error",new T.DiscoveryError("No storage information found for this user address."))})}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const t=this._cleanups.length;let e=0;const n=()=>{e++,e>=t&&(this._init(),(0,l.default)('Cleanups done, emitting "disconnected" event'),this._emit("disconnected"))};t>0?this._cleanups.forEach(t=>{const e=t(this);"object"==typeof e&&"function"==typeof e.then?e.then(n):n()}):n()}setBackend(t){this.backend=t,C&&(void 0!==t?localStorage.setItem("remotestorage:backend",t):localStorage.removeItem("remotestorage:backend"))}onChange(t,e){this._pathHandlers.change[t]||(this._pathHandlers.change[t]=[]),this._pathHandlers.change[t].push(e)}enableLog(){a.default.logging=!0}disableLog(){a.default.logging=!1}log(...t){l.default.apply(T,t)}setApiKeys(t){const e=[E.GOOGLE,E.DROPBOX];if("object"!=typeof t||!Object.keys(t).every(t=>e.includes(t)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(t).forEach(e=>{const n=t[e];if(n){switch(e){case E.DROPBOX:this.apiKeys[E.DROPBOX]={appKey:n},void 0!==this.dropbox&&this.dropbox.clientId===n||m.default._rs_init(this);break;case E.GOOGLE:this.apiKeys[E.GOOGLE]={clientId:n},void 0!==this.googledrive&&this.googledrive.clientId===n||g.default._rs_init(this)}return!0}delete this.apiKeys[e]}),C&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(t){if("string"!=typeof t||!t.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");a.default.cordovaRedirectUri=t}_setGPD(t,e){function n(t){return function(...n){return t.apply(e,n).then(S.bind(this))}}this.get=n(t.get),this.put=n(t.put),this.delete=n(t.delete)}_pendingGPD(t){return(...e)=>{const n=Array.prototype.slice.call(e);return new Promise((e,r)=>{this._pending.push({method:t,args:n,promise:{resolve:e,reject:r}})})}}_processPending(){this._pending.forEach(t=>{try{this[t.method](...t.args).then(t.promise.resolve,t.promise.reject)}catch(e){t.promise.reject(e)}}),this._pending=[]}_bindChange(t){t.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(t,e){Object.keys(this._pathHandlers[t]).forEach(n=>{const r=n.length;e.path.substr(0,r)===n&&this._pathHandlers[t][n].forEach(t=>{const r={};for(const n in e)r[n]=e[n];r.relativePath=e.path.replace(new RegExp("^"+n),"");try{t(r)}catch(t){console.error("'change' handler failed: ",t,t.stack),this._emit("error",t)}})})}scope(t){if("string"!=typeof t)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(t,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestorage.io/rs.js/docs/api/access/classes/Access.html#claim"),new d.default(this,t)}getSyncInterval(){return a.default.syncInterval}setSyncInterval(t){if(!k(t))throw t+" is not a valid sync interval";const e=a.default.syncInterval;a.default.syncInterval=t,this._emit("sync-interval-change",{oldValue:e,newValue:t})}getBackgroundSyncInterval(){return a.default.backgroundSyncInterval}setBackgroundSyncInterval(t){if(!k(t))throw t+" is not a valid sync interval";const e=a.default.backgroundSyncInterval;a.default.backgroundSyncInterval=t,this._emit("sync-interval-change",{oldValue:e,newValue:t})}getCurrentSyncInterval(){return a.default.isBackground?a.default.backgroundSyncInterval:a.default.syncInterval}getRequestTimeout(){return a.default.requestTimeout}setRequestTimeout(t){if("number"!=typeof t)throw t+" is not a valid request timeout";a.default.requestTimeout=t}setupSyncCycle(){this.sync&&!this.sync.stopped&&((0,l.default)("[Sync] Setting up sync cycle"),this.on("sync-done",()=>{(0,l.default)("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync&&!this.sync.stopped&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}),this.sync.sync())}startSync(){return a.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?((0,l.default)("[Sync] Stopping sync"),this.sync.stopped=!0):((0,l.default)("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)}addModule(t){const e=t.name,n=t.builder;if(Object.defineProperty(this,e,{configurable:!0,get:function(){const t=this._loadModule(e,n);return Object.defineProperty(this,e,{value:t}),t}}),-1!==e.indexOf("-")){const t=e.replace(/\-[a-z]/g,function(t){return t[1].toUpperCase()});Object.defineProperty(this,t,{get:function(){return this[e]}})}}_loadModule(t,e){if(e)return e(new d.default(this,"/"+t+"/"),new d.default(this,"/public/"+t+"/")).exports;throw"Unknown module: "+t}}e.RemoteStorage=T,T.SyncError=v.default,T.Unauthorized=b.default,T.DiscoveryError=y.default.DiscoveryError,T.util=_,Object.defineProperty(T.prototype,"access",{configurable:!0,get:function(){const t=new u.default;return Object.defineProperty(this,"access",{value:t}),t}}),Object.defineProperty(T.prototype,"caching",{configurable:!0,get:function(){const t=new p.default(this);return Object.defineProperty(this,"caching",{value:t}),t}}),(0,c.applyMixins)(T,[f.EventHandling]),e.default=T},368:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.isArrayBufferView=void 0,e.retryAfterMs=function(t){const e=1e3*parseInt(t.getResponseHeader("Retry-After"));return e>=1e3?e:Math.max(1500,Math.min(6e4,Math.round(o.default.syncInterval/(2.9+.2*Math.random()))))},e.requestWithTimeout=function(t,n,i){return r(this,void 0,void 0,function*(){return"function"==typeof fetch?function(t,e,n){return r(this,void 0,void 0,function*(){const r="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise((t,e)=>{i=setTimeout(()=>{r&&r.abort(),e("timeout")},o.default.requestTimeout)});let l;const c={},u=fetch(e,{method:t,headers:n.headers,body:n.body,signal:r?r.signal:void 0}).then(t=>{switch((0,s.default)("[requests fetch]",t),t.headers.forEach((t,e)=>{c[e.toUpperCase()]=t}),l={readyState:4,status:t.status,statusText:t.statusText,response:void 0,getResponseHeader:t=>c[t.toUpperCase()]||null,responseType:n.responseType,responseURL:e},n.responseType){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"json":return t.json();case void 0:case"":case"text":return t.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}}).then(t=>(l.response=t,n.responseType&&"text"!==n.responseType||(l.responseText=t),l)).finally(()=>{clearTimeout(i)});return Promise.race([u,a])})}(t,n,i):"function"==typeof XMLHttpRequest?function(t,n,i){return r(this,void 0,void 0,function*(){return new Promise((r,a)=>{(0,s.default)("[requests XHR]",t,n);let l=!1;const c=setTimeout(()=>{l=!0,a("timeout")},o.default.requestTimeout),u=new XMLHttpRequest;if(u.open(t,n,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const t in i.headers)u.setRequestHeader(t,i.headers[t]);u.onload=()=>{l||(clearTimeout(c),r(u))},u.onerror=t=>{l||(clearTimeout(c),a(t))};let h=i.body;"object"==typeof h&&!(0,e.isArrayBufferView)(h)&&h instanceof ArrayBuffer&&(h=new Uint8Array(h)),u.send(h)})})}(t,n,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")})};const s=i(n(334)),o=i(n(28));if("function"==typeof(n.g||window).ArrayBufferView)e.isArrayBufferView=function(t){return t&&t instanceof(n.g||window).ArrayBufferView};else{const t=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];e.isArrayBufferView=function(e){for(let n=0;n<8;n++)if(e instanceof t[n])return!0;return!1}}},941:function(t){t.exports=class{constructor(t){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=t,this.activatePropagation()}get(t){t=t.toLowerCase();let e=this._storage[t];return void 0===e&&(e=this.defaultValue,this._storage[t]=e),e}set(t,e){return t=t.toLowerCase(),this._storage[t]===e||(this._storage[t]=e,e||delete this._itemsRev[t],this._updateParentFolderItemRev(t,e),this._canPropagate&&this._propagate(t)),e}delete(t){return this.set(t,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(t){let e=0;if(0===t.length)return e;for(let n=0;n0&&(n=this._generateHash(t))}return this.set(t,n),n}}},491:function(t){class e extends Error{constructor(t){super();const e=new Error("Schema not found: "+t);return e.name="SchemaNotFound",e}}t.exports=e},982:function(t){class e extends Error{constructor(t){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof t?this.message+=t:(this.message+=t.message,this.stack=t.stack,this.originalError=t)}}t.exports=e},313:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Sync=void 0;const s=i(n(28)),o=i(n(451)),a=i(n(93)),l=i(n(334)),c=i(n(275)),u=i(n(982)),h=i(n(503)),d=n(746);let p,f;function g(t,e,n){return{action:t,path:e,promise:n}}function m(t,e){return t.common.revision!==e&&(!t.remote||t.remote.revision!==e)}function y(t){return!!t.common&&!!t.common.revision}class v{constructor(t){this.numThreads=10,this._tasks={},this._running={},this._timeStarted={},this._finishedTasks=[],this.rs=t,this.rs.local.onDiff(t=>{this.addTask(t),this.doTasks()}),this.rs.caching.onActivate(t=>{this.addTask(t),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(t){return r(this,void 0,void 0,function*(){return new Promise((e,n)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(t,function(){this.rs.local.get(t).then(t=>e(t))}.bind(this)),this.doTasks()):n("cannot fulfill maxAge requirement - remote is not online"):n("cannot fulfill maxAge requirement - remote is not connected")})})}corruptServerItemsMap(t){if("object"!=typeof t||Array.isArray(t))return!0;for(const e in t){const n=t[e];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if((0,d.isFolder)(e)){if(-1!==e.substring(0,e.length-1).indexOf("/"))return!0}else if(-1!==e.indexOf("/"))return!0}return!1}corruptItemsMap(t){if("object"!=typeof t||Array.isArray(t))return!0;for(const e in t)if("boolean"!=typeof t[e])return!0;return!1}corruptRevision(t){return"object"!=typeof t||Array.isArray(t)||t.revision&&"string"!=typeof t.revision||t.body&&"string"!=typeof t.body&&"object"!=typeof t.body||t.contentType&&"string"!=typeof t.contentType||t.contentLength&&"number"!=typeof t.contentLength||t.timestamp&&"number"!=typeof t.timestamp||t.itemsMap&&this.corruptItemsMap(t.itemsMap)}isCorrupt(t){return"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.path||this.corruptRevision(t.common)||t.local&&this.corruptRevision(t.local)||t.remote&&this.corruptRevision(t.remote)||t.push&&this.corruptRevision(t.push)}hasTasks(){return Object.keys(this._tasks).length>0}collectDiffTasks(){return r(this,void 0,void 0,function*(){let t=0;return this.rs.local.forAllNodes(e=>{t>100||(this.isCorrupt(e)?((0,l.default)("[Sync] WARNING: corrupt node in local cache",e),"object"==typeof e&&e.path&&(this.addTask(e.path),t++)):(this.needsFetch(e)&&this.rs.access.checkPathPermission(e.path,"r")||(0,d.isDocument)(e.path)&&this.needsPush(e)&&this.rs.access.checkPathPermission(e.path,"rw"))&&(this.addTask(e.path),t++))}).then(()=>t)})}inConflict(t){return!(!t.local||!t.remote||void 0===t.remote.body&&!t.remote.itemsMap)}needsRefresh(t){return!!t.common&&(!t.common.timestamp||this.now()-t.common.timestamp>s.default.syncInterval)}needsFetch(t){return!!this.inConflict(t)||!(!t.common||void 0!==t.common.itemsMap||void 0!==t.common.body)||!(!t.remote||void 0!==t.remote.itemsMap||void 0!==t.remote.body)}needsPush(t){return!this.inConflict(t)&&(!(!t.local||t.push)||void 0)}needsRemotePut(t){return t.local&&"string"==typeof t.local.body}needsRemoteDelete(t){return t.local&&!1===t.local.body}getParentPath(t){const e=t.match(/^(.*\/)([^\/]+\/?)$/);if(e)return e[1];throw new Error('Not a valid path: "'+t+'"')}deleteChildPathsFromTasks(){for(const t in this._tasks){const e=(0,d.pathsFromRoot)(t);for(let n=1;n{let e;if(this.needsRefresh(t)){try{e=this.getParentPath(t.path)}catch(t){}e&&this.rs.access.checkPathPermission(e,"r")?this.addTask(e):this.rs.access.checkPathPermission(t.path,"r")&&this.addTask(t.path)}}),this.deleteChildPathsFromTasks()})}flush(t){for(const e in t)"FLUSH"===this.rs.caching.checkPath(e)&&t[e]&&!t[e].local&&((0,l.default)("[Sync] Flushing",e),t[e]=void 0);return t}doTask(t){return r(this,void 0,void 0,function*(){return this.rs.local.getNodes([t]).then(e=>{const n=e[t];return void 0===n||function(t){return!(!t.remote||!t.remote.revision||t.remote.itemsMap||t.remote.body)}(n)?g("get",t,this.rs.remote.get(t)):this.needsRemotePut(n)?(n.push=(0,d.deepClone)(n.local),n.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(e)).then(()=>{let e;return e=y(n)?{ifMatch:n.common.revision}:{ifNoneMatch:"*"},g("put",t,this.rs.remote.put(t,n.push.body,n.push.contentType,e))})):this.needsRemoteDelete(n)?(n.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(e)).then(()=>y(n)?g("delete",t,this.rs.remote.delete(t,{ifMatch:n.common.revision})):g("get",t,this.rs.remote.get(t)))):y(n)?g("get",t,this.rs.remote.get(t,{ifNoneMatch:n.common.revision})):g("get",t,this.rs.remote.get(t))})})}autoMergeFolder(t){if(t.remote.itemsMap&&(t.common=t.remote,delete t.remote,t.common.itemsMap)){for(const e in t.common.itemsMap)t.local.itemsMap[e]||(t.local.itemsMap[e]=!1);for(const e in t.local.itemsMap)t.common.itemsMap[e]||this.addTask(t.path+e);(0,d.equal)(t.local.itemsMap,t.common.itemsMap)&&delete t.local}return t}autoMergeDocument(t){var e;return function(t){return(!t.remote||!t.remote.revision||t.remote.revision===t.common.revision)&&(void 0===t.common.body&&!1===t.remote.body||t.remote.body===t.common.body&&t.remote.contentType===t.common.contentType)}(t)?delete(t=function(t){return t.remote&&!1===t.remote.body&&t.local&&!1===t.local.body&&delete t.local,t}(t)).remote:void 0!==t.remote.body&&(!1===t.remote.body&&!1===(null===(e=t.local)||void 0===e?void 0:e.body)||((0,l.default)("[Sync] Emitting conflict event"),setTimeout(this.rs.local.emitChange.bind(this.rs.local),10,{origin:"conflict",path:t.path,oldValue:t.local.body,newValue:t.remote.body,lastCommonValue:t.common.body,oldContentType:t.local.contentType,newContentType:t.remote.contentType,lastCommonContentType:t.common.contentType})),!1===t.remote.body?t.common={}:t.common=t.remote,delete t.remote,delete t.local),t}autoMerge(t){if(t.remote){if(t.local)return(0,d.isFolder)(t.path)?this.autoMergeFolder(t):this.autoMergeDocument(t);if((0,d.isFolder)(t.path))void 0!==t.remote.itemsMap&&(t.common=t.remote,delete t.remote);else if(void 0!==t.remote.body){const e={origin:"remote",path:t.path,oldValue:!1===t.common.body?void 0:t.common.body,newValue:!1===t.remote.body?void 0:t.remote.body,oldContentType:t.common.contentType,newContentType:t.remote.contentType};if(void 0===e.oldValue&&void 0===e.newValue||this.rs.local.emitChange(e),!1===t.remote.body)return;t.common=t.remote,delete t.remote}return t}t.common.body&&this.rs.local.emitChange({origin:"remote",path:t.path,oldValue:t.common.body,newValue:void 0,oldContentType:t.common.contentType,newContentType:void 0})}updateCommonTimestamp(t,e){return r(this,void 0,void 0,function*(){return this.rs.local.getNodes([t]).then(n=>(n[t]&&n[t].common&&n[t].common.revision===e&&(n[t].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(n))))})}markChildren(t,e,n,i){return r(this,void 0,void 0,function*(){const r=[],s={},o={};for(const n in e)r.push(t+n),s[t+n]=e[n];for(const e in i)r.push(t+e);const a=yield this.rs.local.getNodes(r);let l,c;for(const e in a)if(c=a[e],s[e])c&&c.common?m(c,s[e].ETag)&&(n[e]=(0,d.deepClone)(c),n[e].remote={revision:s[e].ETag,timestamp:this.now()},n[e]=this.autoMerge(n[e])):(l=this.rs.caching.checkPath(e),"ALL"===l&&(n[e]={path:e,common:{timestamp:this.now()},remote:{revision:s[e].ETag,timestamp:this.now()}})),n[e]&&s[e]["Content-Type"]&&(n[e].remote.contentType=s[e]["Content-Type"]),n[e]&&s[e]["Content-Length"]&&(n[e].remote.contentLength=s[e]["Content-Length"]);else if(i[e.substring(t.length)]&&c&&c.common){if(c.common.itemsMap)for(const t in c.common.itemsMap)o[e+t]=!0;if(c.local&&c.local.itemsMap)for(const t in c.local.itemsMap)o[e+t]=!0;if(c.remote||(0,d.isFolder)(e))n[e]=void 0;else if(n[e]=this.autoMerge(c),void 0===n[e]){const r=this.getParentPath(e),i=n[r],s=e.substring(t.length);i&&i.local&&(delete i.local.itemsMap[s],(0,d.equal)(i.local.itemsMap,i.common.itemsMap)&&delete i.local)}}const u=yield this.markRemoteDeletions(Object.keys(o),n);u&&(yield this.rs.local.setNodes(this.flush(u)))})}markRemoteDeletions(t,e){return r(this,void 0,void 0,function*(){if(0===t.length)return e;const n=yield this.rs.local.getNodes(t),r={};function i(t,e){if(t&&t.itemsMap)for(const n in t.itemsMap)r[e+n]=!0}for(const t in n){const r=n[t];r&&((0,d.isFolder)(t)?(i(r.common,t),i(r.local,t)):r.common&&void 0!==r.common.body&&(e[t]=(0,d.deepClone)(r),e[t].remote={body:!1,timestamp:this.now()},e[t]=this.autoMerge(e[t])))}const s=yield this.markRemoteDeletions(Object.keys(r),e);s&&(yield this.rs.local.setNodes(this.flush(s)))})}completeFetch(t,e,n,i){return r(this,void 0,void 0,function*(){let r,s;const o=(0,d.pathsFromRoot)(t);(0,d.isFolder)(t)?r=[t]:(s=o[1],r=[t,s]);const a=yield this.rs.local.getNodes(r),l=a[s],c={};let u,h=a[t];function p(t){if(t&&t.itemsMap)for(u in t.itemsMap)e[u]||(c[u]=!0)}if("object"==typeof h&&h.path===t&&"object"==typeof h.common||(h={path:t,common:{}},a[t]=h),h.remote={revision:i,timestamp:this.now()},(0,d.isFolder)(t))for(u in p(h.common),p(h.remote),h.remote.itemsMap={},e)h.remote.itemsMap[u]=!0;else h.remote.body=e,h.remote.contentType=n,l&&l.local&&l.local.itemsMap&&(u=t.substring(s.length),!1!==e?l.local.itemsMap[u]=!0:l.local.itemsMap[u]&&delete l.local.itemsMap[u],(0,d.equal)(l.local.itemsMap,l.common.itemsMap)&&delete l.local);return a[t]=this.autoMerge(h),{toBeSaved:a,missingChildren:c}})}completePush(t,e,n,i){return r(this,void 0,void 0,function*(){const r=yield this.rs.local.getNodes([t]),s=r[t];if(!s.push)throw this.stopped=!0,new Error("completePush called but no push version!");n?((0,l.default)("[Sync] We have a conflict"),s.remote&&s.remote.revision===i||(s.remote={revision:i||"conflict",timestamp:this.now()},delete s.push),r[t]=this.autoMerge(s)):(s.common={revision:i,timestamp:this.now()},"put"===e?(s.common.body=s.push.body,s.common.contentType=s.push.contentType,(0,d.equal)(s.local.body,s.push.body)&&s.local.contentType===s.push.contentType&&delete s.local,delete s.push):"delete"===e&&(!1===s.local.body?r[t]=void 0:delete s.push)),yield this.rs.local.setNodes(this.flush(r))})}dealWithFailure(t){return r(this,void 0,void 0,function*(){const e=yield this.rs.local.getNodes([t]);if(e[t])return delete e[t].push,this.rs.local.setNodes(this.flush(e))})}interpretStatus(t){const e={statusCode:t,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof t&&("offline"===t||"timeout"===t))return e.successful=!1,e.networkProblems=!0,e;if("number"==typeof t){const n=Math.floor(t/100);return e.successful=2===n||304===t||412===t||404===t,e.conflict=412===t,e.unAuth=401===t&&this.rs.remote.token!==c.default.IMPLIED_FAKE_TOKEN||402===t||403===t,e.notFound=404===t,e.changed=304!==t,e}}handleGetResponse(t,e,n,i,s){return r(this,void 0,void 0,function*(){if(e.notFound&&(n=!!(0,d.isFolder)(t)&&{}),e.changed){const e=yield this.completeFetch(t,n,i,s);if((0,d.isFolder)(t)){if(this.corruptServerItemsMap(n))return(0,l.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+t),!1;yield this.markChildren(t,n,e.toBeSaved,e.missingChildren)}else yield this.rs.local.setNodes(this.flush(e.toBeSaved))}else yield this.updateCommonTimestamp(t,s);return!0})}handleResponse(t,e,n){return r(this,void 0,void 0,function*(){const r=this.interpretStatus(n.statusCode);if(r.successful){if("get"===e)return this.handleGetResponse(t,r,n.body,n.contentType,n.revision);if("put"===e||"delete"===e)return this.completePush(t,e,r.conflict,n.revision).then(function(){return!0});throw new Error(`cannot handle response for unknown action ${e}`)}{let e;return e=r.unAuth?new h.default:r.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+r.statusCode+" received."),this.dealWithFailure(t).then(()=>{throw this.rs._emit("error",e),e})}})}finishTask(t){return r(this,arguments,void 0,function*(t,e=!0){if(void 0===t.action)return void delete this._running[t.path];if(e&&((0,l.default)("[Sync] queue finished task:",t.path),this._finishedTasks.push(t),this._finishedTasks.length>1))return void(0,l.default)("[Sync] delaying finished task:",t.path);let n;(0,l.default)("[Sync] run task:",t.path);try{n=yield t.promise}catch(e){(0,l.default)("[Sync] wire client rejects its promise",t.path,t.action,e),n={statusCode:"offline"}}try{const e=yield this.handleResponse(t.path,t.action,n);this.finishSuccessfulTask(t,e)}catch(e){this.finishUnsuccessfulTask(t,e)}})}finishSuccessfulTask(t,e){return r(this,void 0,void 0,function*(){if(this._finishedTasks.shift(),delete this._timeStarted[t.path],delete this._running[t.path],e&&this._tasks[t.path]){for(let e=0;e0?yield this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then(()=>{!this.hasTasks()||this.stopped?(this.done||(this.done=!0),this.rs._emit("sync-done",{completed:!0})):setTimeout(()=>{this.doTasks()},10)})})}finishUnsuccessfulTask(t,e){return r(this,void 0,void 0,function*(){(0,l.default)("[Sync]",e.message),this._finishedTasks.shift(),delete this._timeStarted[t.path],delete this._running[t.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?yield this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))})}tasksWanted(){return this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0}doTasks(){const t=this.tasksWanted()-Object.keys(this._running).length;if(t<=0)return!0;this.hasTasks()&&!this.done&&this.rs._emit("sync-started");let e,n=0;for(e in this._tasks)if(!this._running[e]&&(this._timeStarted[e]=this.now(),this._running[e]=this.doTask(e).then(this.finishTask.bind(this)),n++,n>=t))break;return n>=t}collectTasks(){return r(this,arguments,void 0,function*(t=!0){if(!this.hasTasks()&&!this.stopped)return(yield this.collectDiffTasks())>0?void 0:t?this.collectRefreshTasks():void 0})}addTask(t,e){this._tasks[t]||(this._tasks[t]=[]),"function"==typeof e&&this._tasks[t].push(e)}sync(){return r(this,void 0,void 0,function*(){if(this.done=!1,!this.doTasks()){try{yield this.collectTasks()}catch(t){throw(0,l.default)("[Sync] Sync error",t),new Error("Local cache unavailable")}this.doTasks()}})}static _rs_init(t){p=function(){const e=new o.default;e.isBrowser()&&function(t,e){function n(t){const n=e.getCurrentSyncInterval();s.default.isBackground=!t;const r=e.getCurrentSyncInterval();e._emit("sync-interval-change",{oldValue:n,newValue:r})}t.on("background",()=>n(!1)),t.on("foreground",()=>n(!0))}(e,t),t.sync||(t.sync=new v(t),t.syncStopped&&((0,l.default)("[Sync] Initializing with sync stopped"),t.sync.stopped=!0,delete t.syncStopped)),t.setupSyncCycle()},f=function(){t.removeEventListener("connected",f),t.startSync()},t.on("ready",p),t.on("connected",f)}static _rs_cleanup(t){t.stopSync(),t.removeEventListener("ready",p),t.removeEventListener("connected",f),t.sync=void 0,delete t.sync}}e.Sync=v,(0,d.applyMixins)(v,[a.default]),e.default=v},370:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})};const i=(this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}})(n(334));function s(t){return"dropbox"===this.backend&&!!t.match(/^\/public\/.*[^\/]$/)}const o={get:function(t,e){if(this.local){if(void 0===e)e="object"==typeof(n=this).remote&&n.remote.connected&&n.remote.online?2*n.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof e&&!1!==e)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(t,e,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(t);var n},put:function(t,e,n){return s.bind(this)(t)?o._wrapBusyDone.call(this,this.remote.put(t,e,n)):this.local?this.local.put(t,e,n):o._wrapBusyDone.call(this,this.remote.put(t,e,n))},delete:function(t,e){return this.local?this.local.delete(t,e):o._wrapBusyDone.call(this,this.remote.delete(t,e))},_wrapBusyDone:function(t){return r(this,void 0,void 0,function*(){return this._emit("wire-busy"),t.then(t=>(this._emit("wire-done",{success:!0}),Promise.resolve(t)),t=>(this._emit("wire-done",{success:!1}),Promise.reject(t)))})}};t.exports=o},613:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseClientTypes=void 0;class n{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(t,e,n,r){const i=t+"/"+e;if(r.extends){const e=r.extends.split("/"),n=1===e.length?t+"/"+e.shift():e.join("/"),s=this.uris[n];if(!s)throw"Type '"+i+"' tries to extend unknown schema '"+n+"'";r.extends=this.schemas[s]}this.uris[i]=n,this.aliases[n]=i,this.schemas[n]=r}resolveAlias(t){return this.uris[t]}getSchema(t){return this.schemas[t]}inScope(t){const e=t.length,n={};for(const r in this.uris)if(r.substr(0,e+1)===t+"/"){const t=this.uris[r];n[t]=this.schemas[t]}return n}}e.BaseClientTypes=n;const r=new n;e.default=r},503:function(t){class e extends Error{constructor(t,e={}){super(),this.name="Unauthorized",this.message=void 0===t?"App authorization expired or revoked.":t,void 0!==e.code&&(this.code=e.code),this.stack=(new Error).stack}}t.exports=e},746:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})};function i(t,e){if("object"==typeof t&&!Array.isArray(t)&&null!==t)for(const n in t)if("object"==typeof t[n]&&null!==t[n])if("[object ArrayBuffer]"===t[n].toString()){e[n]=new ArrayBuffer(t[n].byteLength);const r=new Int8Array(t[n]);new Int8Array(e[n]).set(r)}else i(t[n],e[n])}Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=e.getTextFromArrayBuffer=e.shouldBeTreatedAsBinary=e.getJSONFromLocalStorage=e.localStorageAvailable=e.pathsFromRoot=e.deepClone=e.equal=e.bindAll=e.cleanPath=e.baseName=e.isDocument=e.isFolder=e.containingFolder=e.extend=e.getGlobalContext=e.globalContext=e.logError=void 0,e.generateCodeVerifier=function(){return r(this,arguments,void 0,function*(t=128){const e=new Uint8Array(t);crypto.getRandomValues(e);const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=Array.from(e).map(t=>n[t%66]),i=r.join(""),s=Uint8Array.from(r.map(t=>t.charCodeAt(0))),o=(a=yield crypto.subtle.digest("SHA-256",s),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(e),{codeVerifier:i,codeChallenge:o,state:Array.from(e).map(t=>n[t%66]).join("")}})},e.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(n=>{Object.defineProperty(t.prototype,n,Object.getOwnPropertyDescriptor(e.prototype,n))})})},e.logError=t=>{"string"==typeof t?console.error(t):console.error(t.message,t.stack)},e.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:n.g,e.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:n.g,e.extend=(...t)=>{const e=t[0];return Array.prototype.slice.call(t,1).forEach(function(t){for(const n in t)e[n]=t[n]}),e},e.containingFolder=t=>{if(""===t)return"/";if(!t)throw"Path not given!";return t.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},e.isFolder=t=>"/"===t.slice(-1),e.isDocument=t=>!(0,e.isFolder)(t),e.baseName=t=>{const n=t.split("/");return(0,e.isFolder)(t)?n[n.length-2]+"/":n[n.length-1]},e.cleanPath=t=>t.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),e.bindAll=t=>{for(const e in this)"function"==typeof t[e]&&(t[e]=t[e].bind(t))},e.equal=(t,n,r=[])=>{let i;if(typeof t!=typeof n)return!1;if("number"==typeof t||"boolean"==typeof t||"string"==typeof t)return t===n;if("function"==typeof t)return t.toString()===n.toString();if(t instanceof ArrayBuffer&&n instanceof ArrayBuffer&&(t=new Uint8Array(t),n=new Uint8Array(n)),t instanceof Array){if(t.length!==n.length)return!1;for(let i=0,s=t.length;i=0)continue;s=r.slice(),s.push(n[i])}if(!(0,e.equal)(t[i],n[i],s))return!1}}return!0},e.deepClone=t=>{if(void 0!==t){const e=JSON.parse(JSON.stringify(t));return i(t,e),e}},e.pathsFromRoot=t=>{const e=[t],n=t.replace(/\/$/,"").split("/");for(;n.length>1;)n.pop(),e.push(n.join("/")+"/");return e},e.localStorageAvailable=()=>{const t=(0,e.getGlobalContext)();if(!("localStorage"in t))return!1;try{return t.localStorage.setItem("rs-check","1"),t.localStorage.removeItem("rs-check"),!0}catch(t){return!1}},e.getJSONFromLocalStorage=t=>{const n=(0,e.getGlobalContext)();try{return JSON.parse(n.localStorage.getItem(t))}catch(t){}},e.shouldBeTreatedAsBinary=(t,e)=>!!(e&&e.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(t)),e.getTextFromArrayBuffer=(t,n)=>new Promise(r=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const e=Buffer.from(t);r(e.toString(n))}else{let i;const s=e.globalContext;if(s.BlobBuilder=s.BlobBuilder||s.WebKitBlobBuilder,void 0!==s.BlobBuilder){const e=new s.BlobBuilder;e.append(t),i=e.getBlob()}else i=new Blob([t]);const o=new FileReader;"function"==typeof o.addEventListener?o.addEventListener("loadend",function(t){r(t.target.result)}):o.onloadend=function(t){r(t.target.result)},o.readAsText(i,n)}}),e.toBase64=t=>{const n=(0,e.getGlobalContext)();return"btoa"in n?n.btoa(t):Buffer.from(t).toString("base64")}},600:function(t,e,n){var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}l((r=r.apply(t,e||[])).next())})},i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const s=i(n(275)),o=i(n(93)),a=i(n(503)),l=i(n(334)),c=n(746),u=n(368),h=n(684);let d;const p="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends h.RemoteBase{constructor(t){if(super(t),this._revisionCache={},d=(0,c.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),d){const t=function(){const t=(0,c.getJSONFromLocalStorage)(p)||{},{userAddress:e,href:n,storageApi:r,token:i,properties:s}=t;return{userAddress:e,href:n,storageApi:r,token:i,properties:s}}();t&&setTimeout(()=>{this.configure(t)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const t=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return t?t[1]:"2012.04"}}_request(t,e,n,i,o,h,d){return r(this,void 0,void 0,function*(){if(this.isForbiddenRequestMethod(t,e))return Promise.reject(`Don't use ${t} on directories!`);let r;return n!==s.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+n),this.rs._emit("wire-busy",{method:t,isFolder:(0,c.isFolder)(e)}),(0,u.requestWithTimeout)(t,e,{body:o,headers:i,responseType:"arraybuffer"}).then(n=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:t,isFolder:(0,c.isFolder)(e),success:!0}),i=n.status,[401,403,404,412].indexOf(i)>=0)return(0,l.default)("[WireClient] Error response status",n.status),r=h?this.stripQuotes(n.getResponseHeader("ETag")):void 0,401===n.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:n.status,revision:r});if(function(t){return[201,204,304].indexOf(t)>=0}(n.status)||200===n.status&&"GET"!==t)return r=this.stripQuotes(n.getResponseHeader("ETag")),(0,l.default)("[WireClient] Successful request",r),Promise.resolve({statusCode:n.status,revision:r});{const t=n.getResponseHeader("Content-Type");r=h?this.stripQuotes(n.getResponseHeader("ETag")):200===n.status?d:void 0;const e=function(t){let e,n="utf-8";return t&&(e=t.match(/charset=(.+)$/),e&&(n=e[1])),n}(t);return(0,c.shouldBeTreatedAsBinary)(n.response,t)?((0,l.default)("[WireClient] Successful request with unknown or binary mime-type",r),Promise.resolve({statusCode:n.status,body:n.response,contentType:t,revision:r})):(0,c.getTextFromArrayBuffer)(n.response,e).then(e=>((0,l.default)("[WireClient] Successful request",r),Promise.resolve({statusCode:n.status,body:e,contentType:t,revision:r})))}var i},n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:t,isFolder:(0,c.isFolder)(e),success:!1}),Promise.reject(n)))})}configure(t){if("object"!=typeof t)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==t.userAddress&&(this.userAddress=t.userAddress),void 0!==t.href&&(this.href=t.href),void 0!==t.storageApi&&(this.storageApi=t.storageApi),void 0!==t.token&&(this.token=t.token),void 0!==t.properties&&(this.properties=t.properties),"string"==typeof this.storageApi){const t=f[this.storageApi]||5;this.supportsRevs=t>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,d&&localStorage.setItem(p,JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(t,e={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");const n={};return this.supportsRevs&&e.ifNoneMatch&&(n["If-None-Match"]=this.addQuotes(e.ifNoneMatch)),this._request("GET",this.href+(0,c.cleanPath)(t),this.token,n,void 0,this.supportsRevs,this._revisionCache[t]).then(e=>{if(!(0,c.isFolder)(t))return Promise.resolve(e);let n={};if(void 0!==e.body)try{e.body=JSON.parse(e.body)}catch(e){return Promise.reject("Folder description at "+this.href+(0,c.cleanPath)(t)+" is not JSON")}if(200===e.statusCode&&"object"==typeof e.body){if(0===Object.keys(e.body).length)e.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(r=e.body)["@context"]&&"object"==typeof r.items){for(const n in e.body.items)this._revisionCache[t+n]=e.body.items[n].ETag;n=e.body.items}else Object.keys(e.body).forEach(r=>{this._revisionCache[t+r]=e.body[r],n[r]={ETag:e.body[r]}});return e.body=n,Promise.resolve(e)}return Promise.resolve(e);var r})}put(t,e,n,r={}){if(!this.connected)return Promise.reject("not connected (path: "+t+")");!n.match(/charset=/)&&(e instanceof ArrayBuffer||(0,u.isArrayBufferView)(e))&&(n+="; charset=binary");const i={"Content-Type":n};return this.supportsRevs&&(r.ifMatch&&(i["If-Match"]=this.addQuotes(r.ifMatch)),r.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(r.ifNoneMatch))),this._request("PUT",this.href+(0,c.cleanPath)(t),this.token,i,e,this.supportsRevs)}delete(t,e={}){if(!this.connected)throw new Error("not connected (path: "+t+")");e||(e={});const n={};return this.supportsRevs&&e.ifMatch&&(n["If-Match"]=this.addQuotes(e.ifMatch)),this._request("DELETE",this.href+(0,c.cleanPath)(t),this.token,n,void 0,this.supportsRevs)}static _rs_init(t){t.remote=new g(t),t.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){d&&delete localStorage[p]}}(0,c.applyMixins)(g,[o.default]),t.exports=g},439:function(t,e){var n,r;n=function(){var t,e,n,r;Object.keys||(Object.keys=(t=Object.prototype.hasOwnProperty,e=!{toString:null}.propertyIsEnumerable("toString"),r=(n=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var s=[];for(var o in i)t.call(i,o)&&s.push(o);if(e)for(var a=0;a>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&((r=Number(arguments[1]))!=r?r=0:0!==r&&r!==1/0&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);i0&&(e+=u.suffices["*"]&&n||",",u.suffices["*"]&&l&&(e+=u.name+"=")),e+=a?encodeURIComponent(h[p]).replace(/!/g,"%21"):o(h[p])}else if("object"==typeof h){l&&!u.suffices["*"]&&(e+=u.name+"=");var f=!0;for(var g in h)f||(e+=u.suffices["*"]&&n||","),f=!1,e+=a?encodeURIComponent(g).replace(/!/g,"%21"):o(g),e+=u.suffices["*"]?"=":",",e+=a?encodeURIComponent(h[g]).replace(/!/g,"%21"):o(h[g])}else l&&(e+=u.name,c&&""===h||(e+="=")),null!=u.truncate&&(h=h.substring(0,u.truncate)),e+=a?encodeURIComponent(h).replace(/!/g,"%21"):o(h)}return e};return w.varNames=u,{prefix:r,substitution:w}}function l(t){if(!(this instanceof l))return new l(t);for(var e=t.split("{"),n=[e.shift()],r=[],i=[],s=[];e.length>0;){var o=e.shift(),c=o.split("}")[0],u=o.substring(c.length+1),h=a(c);i.push(h.substitution),r.push(h.prefix),n.push(u),s=s.concat(h.substitution.varNames)}this.fill=function(t){for(var e=n[0],r=0;r0&&"/"===e.charAt(t.length-1)||"#"===n.charAt(0)||"?"===n.charAt(0))return!0}return!1}(e,t.id)&&void 0===this.schemas[t.id]&&(this.schemas[t.id]=t),t)if("enum"!==r)if("object"==typeof t[r])this.searchSchemas(t[r],e);else if("$ref"===r){var i=g(t[r]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},c.prototype.addSchema=function(t,e){if("string"!=typeof t||void 0===e){if("object"!=typeof t||"string"!=typeof t.id)return;t=(e=t).id}t===g(t)+"#"&&(t=g(t)),this.schemas[t]=e,delete this.missingMap[t],m(e,t),this.searchSchemas(e,t)},c.prototype.getSchemaMap=function(){var t={};for(var e in this.schemas)t[e]=this.schemas[e];return t},c.prototype.getSchemaUris=function(t){var e=[];for(var n in this.schemas)t&&!t.test(n)||e.push(n);return e},c.prototype.getMissingUris=function(t){var e=[];for(var n in this.missingMap)t&&!t.test(n)||e.push(n);return e},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(t,e,n,r,i){var s;if(!(e=this.resolveRefs(e)))return null;if(e instanceof x)return this.errors.push(e),e;var o,a=this.errors.length,l=null,c=null;if(this.checkRecursive&&t&&"object"==typeof t){if(s=!this.scanned.length,t[this.validatedSchemasKey]){var u=t[this.validatedSchemasKey].indexOf(e);if(-1!==u)return this.errors=this.errors.concat(t[this.validationErrorsKey][u]),null}if(Object.isFrozen(t)&&-1!==(o=this.scannedFrozen.indexOf(t))){var h=this.scannedFrozenSchemas[o].indexOf(e);if(-1!==h)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[o][h]),null}if(this.scanned.push(t),Object.isFrozen(t))-1===o&&(o=this.scannedFrozen.length,this.scannedFrozen.push(t),this.scannedFrozenSchemas.push([])),l=this.scannedFrozenSchemas[o].length,this.scannedFrozenSchemas[o][l]=e,this.scannedFrozenValidationErrors[o][l]=[];else{if(!t[this.validatedSchemasKey])try{Object.defineProperty(t,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(t,this.validationErrorsKey,{value:[],configurable:!0})}catch(e){t[this.validatedSchemasKey]=[],t[this.validationErrorsKey]=[]}c=t[this.validatedSchemasKey].length,t[this.validatedSchemasKey][c]=e,t[this.validationErrorsKey][c]=[]}}var d=this.errors.length,p=this.validateBasic(t,e,i)||this.validateNumeric(t,e,i)||this.validateString(t,e,i)||this.validateArray(t,e,i)||this.validateObject(t,e,i)||this.validateCombinations(t,e,i)||this.validateHypermedia(t,e,i)||this.validateFormat(t,e,i)||this.validateDefinedKeywords(t,e,i)||null;if(s){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(p||d!==this.errors.length)for(;n&&n.length||r&&r.length;){var f=n&&n.length?""+n.pop():null,g=r&&r.length?""+r.pop():null;p&&(p=p.prefixWith(f,g)),this.prefixErrors(d,f,g)}return null!==l?this.scannedFrozenValidationErrors[o][l]=this.errors.slice(a):null!==c&&(t[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(p)},c.prototype.validateFormat=function(t,e){if("string"!=typeof e.format||!this.formatValidators[e.format])return null;var n=this.formatValidators[e.format].call(null,t,e);return"string"==typeof n||"number"==typeof n?this.createError(v.FORMAT_CUSTOM,{message:n},"","/format",null,t,e):n&&"object"==typeof n?this.createError(v.FORMAT_CUSTOM,{message:n.message||"?"},n.dataPath||"",n.schemaPath||"/format",null,t,e):null},c.prototype.validateDefinedKeywords=function(t,e,n){for(var r in this.definedKeywords)if(void 0!==e[r])for(var i=this.definedKeywords[r],s=0;s=h&&re.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:t,maximum:e.maximum},"","/maximum",null,t,e);if(e.exclusiveMaximum&&t===e.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:t,maximum:e.maximum},"","/exclusiveMaximum",null,t,e)}return null},c.prototype.validateNaN=function(t,e){return"number"!=typeof t?null:!0===isNaN(t)||t===1/0||t===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:t},"","/type",null,t,e):null},c.prototype.validateString=function(t,e,n){return this.validateStringLength(t,e,n)||this.validateStringPattern(t,e,n)||null},c.prototype.validateStringLength=function(t,e){return"string"!=typeof t?null:void 0!==e.minLength&&t.lengthe.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:t.length,maximum:e.maxLength},"","/maxLength",null,t,e):null},c.prototype.validateStringPattern=function(t,e){if("string"!=typeof t||"string"!=typeof e.pattern&&!(e.pattern instanceof RegExp))return null;var n;if(e.pattern instanceof RegExp)n=e.pattern;else{var r,i="",s=e.pattern.match(/^\/(.+)\/([img]*)$/);s?(r=s[1],i=s[2]):r=e.pattern,n=new RegExp(r,i)}return n.test(t)?null:this.createError(v.STRING_PATTERN,{pattern:e.pattern},"","/pattern",null,t,e)},c.prototype.validateArray=function(t,e,n){return Array.isArray(t)&&(this.validateArrayLength(t,e,n)||this.validateArrayUniqueItems(t,e,n)||this.validateArrayItems(t,e,n))||null},c.prototype.validateArrayLength=function(t,e){var n;return void 0!==e.minItems&&t.lengthe.maxItems&&(n=this.createError(v.ARRAY_LENGTH_LONG,{length:t.length,maximum:e.maxItems},"","/maxItems",null,t,e),this.handleError(n))?n:null},c.prototype.validateArrayUniqueItems=function(t,e){if(e.uniqueItems)for(var n=0;ne.maxProperties&&(n=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:r.length,maximum:e.maxProperties},"","/maxProperties",null,t,e),this.handleError(n))?n:null},c.prototype.validateObjectRequiredProperties=function(t,e){if(void 0!==e.required)for(var n=0;n 10000");if(void 0!==v[t])throw new Error("Error already defined: "+t+" as "+v[t]);if(void 0!==b[e])throw new Error("Error code already used: "+b[e]+" as "+e);for(var r in v[t]=e,b[e]=t,_[t]=_[e]=n,C){var i=C[r];i[t]&&(i[e]=i[e]||i[t])}},reset:function(){r.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:m,resolveUrl:f,getDocumentUri:g,errorCodes:v};return i.language("en"),i}();return S.addLanguage("en-gb",_),S.tv4=S,S},void 0===(r=n.apply(e,[]))||(t.exports=r)},199:function(t,e,n){var r;"function"!=typeof fetch&&"function"!=typeof XMLHttpRequest&&(XMLHttpRequest=n(317)),function(){var n={"http://webfist.org/spec/rel":"webfist","http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},i={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},s=["webfinger","host-meta","host-meta.json"];function o(t){return t.toString=function(){return this.message},t}function a(t){"object"!=typeof t&&(t={}),this.config={tls_only:void 0===t.tls_only||t.tls_only,webfist_fallback:void 0!==t.webfist_fallback&&t.webfist_fallback,uri_fallback:void 0!==t.uri_fallback&&t.uri_fallback,request_timeout:void 0!==t.request_timeout?t.request_timeout:1e4}}a.prototype.__fetchJRD=function(t,e,n){if("function"==typeof fetch)return this.__fetchJRD_fetch(t,e,n);if("function"==typeof XMLHttpRequest)return this.__fetchJRD_XHR(t,e,n);throw new Error("add a polyfill for fetch or XMLHttpRequest")},a.prototype.__fetchJRD_fetch=function(t,e,n){var r,i=this;"function"==typeof AbortController&&(r=new AbortController);var s=fetch(t,{headers:{Accept:"application/jrd+json, application/json"},signal:r?r.signal:void 0}).then(function(e){if(e.ok)return e.text();throw 404===e.status?o({message:"resource not found",url:t,status:e.status}):o({message:"error during request",url:t,status:e.status})},function(e){throw o({message:"error during request",url:t,status:void 0,err:e})}).then(function(e){if(i.__isValidJSON(e))return e;throw o({message:"invalid json",url:t,status:void 0})}),a=new Promise(function(e,n){setTimeout(function(){n(o({message:"request timed out",url:t,status:void 0})),r&&r.abort()},i.config.request_timeout)});Promise.race([s,a]).then(function(t){n(t)}).catch(function(t){e(t)})},a.prototype.__fetchJRD_XHR=function(t,e,n){var r=this,i=!1,s=new XMLHttpRequest;function a(){if(!i)return i=!0,200===s.status?r.__isValidJSON(s.responseText)?n(s.responseText):e(o({message:"invalid json",url:t,status:s.status})):404===s.status?e(o({message:"resource not found",url:t,status:s.status})):s.status>=301&&s.status<=302?function(t){return"string"==typeof t&&"https"===t.split("://")[0]}(s.getResponseHeader("Location"))?l():e(o({message:"no redirect URL found",url:t,status:s.status})):e(o({message:"error during request",url:t,status:s.status}))}function l(){s.onreadystatechange=function(){4===s.readyState&&a()},s.onload=function(){a()},s.ontimeout=function(){return e(o({message:"request timed out",url:t,status:s.status}))},s.open("GET",t,!0),s.timeout=r.config.request_timeout,s.setRequestHeader("Accept","application/jrd+json, application/json"),s.send()}return l()},a.prototype.__isValidJSON=function(t){try{JSON.parse(t)}catch(t){return!1}return!0},a.prototype.__isLocalhost=function(t){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(t)},a.prototype.__processJRD=function(t,e,r,s){var a=JSON.parse(e);if("object"!=typeof a||"object"!=typeof a.links)return void 0!==a.error?r(o({message:a.error,request:t})):r(o({message:"unknown response from server",request:t}));var l=a.links;Array.isArray(l)||(l=[]);var c={object:a,json:e,idx:{}};c.idx.properties={name:void 0},c.idx.links=JSON.parse(JSON.stringify(i)),l.map(function(t){if(n.hasOwnProperty(t.rel)&&c.idx.links[n[t.rel]]){var e={};Object.keys(t).map(function(n){e[n]=t[n]}),c.idx.links[n[t.rel]].push(e)}});var u=JSON.parse(e).properties;for(var h in u)u.hasOwnProperty(h)&&"http://packetizer.com/ns/name"===h&&(c.idx.properties.name=u[h]);return s(c)},a.prototype.lookup=function(t,e){if("string"!=typeof t)throw new Error("first parameter must be a user address");if("function"!=typeof e)throw new Error("second parameter must be a callback");var n=this,r="";r=t.indexOf("://")>-1?t.replace(/ /g,"").split("/")[2]:t.replace(/ /g,"").split("@")[1];var i=0,o="https";function a(){var e="";return t.split("://")[1]||(e="acct:"),o+"://"+r+"/.well-known/"+s[i]+"?resource="+e+t}function l(t){if(n.config.uri_fallback&&"webfist.org"!==r&&i!==s.length-1)return i+=1,c();if(!n.config.tls_only&&"https"===o)return i=0,o="http",c();if(!n.config.webfist_fallback||"webfist.org"===r)return e(t);i=0,o="http",r="webfist.org";var l=a();n.__fetchJRD(l,e,function(t){n.__processJRD(l,t,e,function(t){"object"==typeof t.idx.links.webfist&&"string"==typeof t.idx.links.webfist[0].href&&n.__fetchJRD(t.idx.links.webfist[0].href,e,function(t){n.__processJRD(l,t,e,function(){return e(null,e)})})})})}function c(){var t=a();n.__fetchJRD(t,l,function(r){n.__processJRD(t,r,e,function(t){e(null,t)})})}return n.__isLocalhost(r)&&(o="http"),setTimeout(c,0)},a.prototype.lookupLink=function(t,e,n){if(!i.hasOwnProperty(e))return n("unsupported rel "+e);this.lookup(t,function(t,r){var i=r.idx.links[e];return t?n(t):0===i.length?n('no links found with rel="'+e+'"'):n(null,i[0])})},void 0===(r=function(){return a}.apply(e,[]))||(t.exports=r)}()},317:function(t){t.exports=XMLHttpRequest}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var s=e[r]={exports:{}};return t[r].call(s.exports,s,s.exports,n),s.exports}return n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n(423).default}()),qN.exports); +/*! For license information please see remotestorage.js.LICENSE.txt */const WN=BA(VN),HN="0123456789ABCDEFGHJKMNPQRSTVWXYZ",GN=0xffffffffffff;var KN;!function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"}(KN||(KN={}));class ZN extends Error{constructor(t,e){super(`${e} (${t})`),this.name="ULIDError",this.code=t}}function YN(t){const e=Math.floor(32*t())%32;return HN.charAt(e)}const XN={type:"object",properties:{id:{type:"string"},title:{type:"string"},lat:{type:"number"},lon:{type:"number"},geohash:{type:"string"},zoom:{type:"number"},url:{type:"string"},osmId:{type:"string"},osmType:{type:"string"},osmTags:{type:"object",additionalProperties:{type:"string"}},description:{type:"string"},tags:{type:"array",items:{type:"string"},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","lat","lon","geohash","createdAt"]},JN={type:"object",properties:{id:{type:"string"},title:{type:"string"},color:{type:"string"},placeRefs:{type:"array",items:{type:"object",properties:{id:{type:"string"},geohash:{type:"string"}},required:["id","geohash"]},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","placeRefs","createdAt"]},QN={name:"places",builder:function(t){function e(t,e){return`${t.substring(0,2)}/${t.substring(2,4)}/${e}`}t.declareType("place",XN),t.declareType("list",JN);const n={async getAll(){const e=await t.getAll("_lists/");return e?Object.values(e):[]},async get(e){const n=`_lists/${e}`;return t.getObject(n)},async create(e,n,r){const i=`_lists/${e}`;let s=await t.getObject(i);const o=(new Date).toISOString();return s?(s.title=n,r&&(s.color=r),s.updatedAt=o):s={id:e,title:n,color:r,placeRefs:[],createdAt:o,updatedAt:o},await t.storeObject("list",i,s),s},async delete(e){await t.remove(`_lists/${e}`)},async addPlace(e,n,r){const i=`_lists/${e}`,s=await t.getObject(i);if(!s)throw new Error(`List not found: ${e}`);return-1===s.placeRefs.findIndex(t=>t.id===n)&&(s.placeRefs.push({id:n,geohash:r}),s.updatedAt=(new Date).toISOString(),await t.storeObject("list",i,s)),s},async removePlace(e,n){const r=`_lists/${e}`,i=await t.getObject(r);if(!i)throw new Error(`List not found: ${e}`);const s=i.placeRefs.findIndex(t=>t.id===n);return-1!==s&&(i.placeRefs.splice(s,1),i.updatedAt=(new Date).toISOString(),await t.storeObject("list",r,i)),i},async initDefaults(){const t=[{id:"to-go",title:"Want to go",color:"#2e9e4f"},{id:"to-do",title:"To do",color:"#2a7fff"}];for(const e of t)await this.get(e.id)||await this.create(e.id,e.title,e.color)}},r={lists:n,store:async function(n){const r=function(t){const e=(new Date).toISOString(),n=t.id||function(){const t=function(){const t="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:null,e=t&&(t.crypto||t.msCrypto)||null;if("function"==typeof e?.getRandomValues)return()=>{const t=new Uint8Array(1);return e.getRandomValues(t),t[0]/256};if("function"==typeof e?.randomBytes)return()=>e.randomBytes(1).readUInt8()/256;throw new ZN(KN.PRNGDetectFailure,"Failed to find a reliable PRNG")}();return function(t,e=10){if(isNaN(t))throw new ZN(KN.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>GN)throw new ZN(KN.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${GN}: ${t}`);if(t<0)throw new ZN(KN.EncodeTimeNegative,`Time must be positive: ${t}`);if(!1===Number.isInteger(t))throw new ZN(KN.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let i=e;i>0;i--)n=t%32,r=HN.charAt(n)+r,t=(t-n)/32;return r}(Date.now(),10)+function(t,e){let n="";for(;t>0;t--)n=YN(e)+n;return n}(16,t)}(),r="number"==typeof t.lat?t.lat:0,i="number"==typeof t.lon?t.lon:0,s=t.title||"Untitled Place",o=t.geohash||DD.encode(r,i,10),a={...t,id:n,lat:r,lon:i,geohash:o,title:s,tags:t.tags||[],createdAt:t.createdAt||e,updatedAt:t.id?e:void 0};return Object.keys(a).forEach(t=>{void 0===a[t]&&delete a[t]}),a}(n),i=e(r.geohash,r.id);return await t.storeObject("place",i,r),r},remove:async function(r,i){if(!r||!i)throw new Error("Both id and geohash are required to remove a place");const s=await n.getAll();await Promise.all(s.map(async e=>{const n=e.placeRefs.findIndex(t=>t.id===r);-1!==n&&(e.placeRefs.splice(n,1),e.updatedAt=(new Date).toISOString(),await t.storeObject("list",`_lists/${e.id}`,e))}));const o=e(i,r);return t.remove(o)},get:async function(n,r){if(!n||!r)throw new Error("Both id and geohash are required to get a place");const i=e(r,n);return t.getObject(i)},listByPrefix:async function(e){let n="";return e.length>=2&&(n+=e.substring(0,2)+"/"),e.length>=4&&(n+=e.substring(2,4)+"/"),t.getAll(n)},getPlaces:async function(e){const n=[],r=async e=>{const r=await t.getAll(e,!1);r&&Object.values(r).forEach(t=>{t&&"object"==typeof t&&!t.toString().endsWith("/")&&n.push(t)})};if(e&&e.length>0){const t=e.map(async t=>{if(t.length<4)return;const e=t.substring(0,2),n=t.substring(2,4);await r(`${e}/${n}/`)});await Promise.all(t)}else{const e=t=>{if(!t||"object"!=typeof t)return[];let e=t;return t.items&&"object"==typeof t.items&&(e=t.items),Object.keys(e).filter(t=>t.endsWith("/")&&!t.startsWith("@"))},n=await t.getListing("",!1),i=e(n);await Promise.all(i.map(async n=>{const i=await t.getListing(n,!1),s=e(i);await Promise.all(s.map(async t=>{await r(n+t)}))}))}return n}};return{exports:r}}};var tj,ej,nj={exports:{}},rj=tj?nj.exports:(tj=1,self,ej=()=>(()=>{var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function r(t){var e=function(t){if("object"!=n(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=n(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==n(e)?e:e+""}t.d(e,{default:()=>i});const i=function(){return t=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.rs=e,this.leaveOpen=!!n.leaveOpen&&n.leaveOpen,this.autoCloseAfter=n.autoCloseAfter?n.autoCloseAfter:1500,this.skipInitial=!!n.skipInitial&&n.skipInitial,this.logging=!!n.logging&&n.logging,this.parentContainerEl=null,n.hasOwnProperty("modalBackdrop")){if("boolean"!=typeof n.modalBackdrop&&"onlySmallScreens"!==n.modalBackdrop)throw'options.modalBackdrop has to be true/false or "onlySmallScreens"';this.modalBackdrop=n.modalBackdrop}else this.modalBackdrop="onlySmallScreens";this.active=!1,this.online=!1,this.closed=!1,this.lastSynced=null,this.lastSyncedUpdateLoop=null},e=[{key:"log",value:function(){if(this.logging){for(var t,e=arguments.length,n=new Array(e),r=0;r

Connect your storage

To sync data with your account
';var e=document.createElement("style");return e.innerHTML='#remotestorage-widget {\n z-index: 21000000;\n}\n\n.rs-widget {\n box-sizing: border-box;\n overflow: hidden;\n max-width: 350px;\n padding: 10px;\n margin: 10px;\n border-radius: 3px;\n background-color: #fff;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n font-family: arial, sans-serif;\n font-size: 16px;\n color: #333;\n will-change: max-height, height, width, opacity, max-width, background, box-shadow;\n transition-property: width, height, opacity, max-width, max-height, background, box-shadow;\n transition-duration: 300ms;\n}\n\n.rs-widget * {\n box-sizing: border-box;\n}\n\n.rs-widget .rs-hidden {\n display: none;\n}\n\n.rs-box {\n overflow: hidden;\n will-change: height;\n transition-property: height, width, max-height;\n transition-duration: 300ms;\n transition-timing-function: ease-in;\n opacity: 0;\n max-height: 0px;\n}\n\n.rs-box.rs-selected:not([aria-hidden=true]) {\n opacity: 1;\n max-height: 420px;\n}\n\n/* Main logo */\n.rs-main-logo {\n float: left;\n height: 36px;\n width: 36px;\n margin-top: 1px;\n margin-right: 0.625em;\n transition: margin-left 300ms ease-out, transform 300ms ease-out;\n cursor: pointer;\n}\n.rs-widget .rs-backend-remotestorage svg#rs-main-logo-remotestorage {\n display: block;\n}\n.rs-widget[class*="rs-backend-"]:not(.rs-backend-remotestorage) svg#rs-main-logo-remotestorage {\n display: none;\n}\n.rs-widget.rs-backend-dropbox svg#rs-main-logo-dropbox {\n display: block;\n}\n.rs-widget:not(.rs-backend-dropbox) svg#rs-main-logo-dropbox {\n display: none;\n}\n.rs-widget.rs-backend-googledrive svg#rs-main-logo-googledrive {\n display: block;\n}\n.rs-widget:not(.rs-backend-googledrive) svg#rs-main-logo-googledrive {\n display: none;\n}\n\npolygon.rs-logo-shape {\n fill: #FF4B03;\n}\n\npolygon.rs-logo-shape,\n#rs-main-logo-dropbox path,\n#rs-main-logo-googledrive path {\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n.rs-offline polygon.rs-logo-shape,\n.rs-offline #rs-main-logo-dropbox path,\n.rs-offline #rs-main-logo-googledrive path {\n fill: #888;\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n/* Hide everything except logo when connected and clicked outside of box */\n.rs-closed {\n max-width: 56px;\n background-color: transparent;\n box-shadow: none;\n opacity: 0.5;\n\n transition: max-height 100ms ease-out 0ms, max-width 300ms ease-out 300ms, background 300ms ease-in 200ms, opacity 300ms ease 200ms;\n}\n\n.rs-closed:hover {\n cursor: pointer;\n opacity: 1;\n}\n\n.rs-box-initial {\n transition-duration: 0ms;\n}\n\n.rs-box-initial:hover {\n cursor: pointer;\n}\n\n.rs-widget a {\n color: #0093cc;\n}\n\n/* HEADLINE */\n.rs-small-headline {\n font-size: 1em;\n font-weight: bold;\n margin: 0;\n margin-bottom: 2px;\n height: 1.2em;\n word-break: break-all;\n overflow: hidden;\n line-height: 1em;\n}\n\n.rs-sub-headline {\n word-break: break-all;\n overflow: hidden;\n color: #666;\n font-size: 0.92em;\n height: 1.2em;\n}\n.rs-big-headline {\n font-size: 1.625em;\n font-weight: normal;\n text-align: center;\n margin-top: 20px;\n margin-bottom: 20px;\n}\n\n/* BUTTONS */\n.rs-button {\n font: inherit;\n color: inherit;\n background-color: transparent;\n border: 1px solid #dcdcdc;\n border-radius: 3px;\n cursor: pointer;\n}\n.rs-button-small {\n padding: 0.6em 0.7em;\n margin-left: 0.2em;\n transition: border-color 300ms ease-out;\n}\n.rs-button-small svg {\n vertical-align: top;\n}\n.rs-button-wrap {\n margin-top: 10px;\n}\n\n.rs-button-wrap img,\n.rs-button-wrap svg {\n float: left;\n margin-right: 0.6em;\n width: 40px;\n height: 40px;\n}\n\n.rs-button-big {\n padding: 15px 10px;\n margin-bottom: 10px;\n display: block;\n width: 100%;\n text-align: left;\n transition: box-shadow 200ms;\n}\n.rs-button-big > div {\n font-size: 1.125em;\n padding: 10px 0;\n}\n.rs-button-big:hover {\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:active {\n background-color: #eee;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:last-child {\n margin-bottom: 0;\n}\n\n.rs-content {\n padding: 0 10px 10px 10px;\n}\n\n\n.rs-state-choose .rs-main-logo,\n.rs-state-sign-in .rs-main-logo {\n margin-left: 45%;\n float: none;\n}\n\n.rs-sign-in-form input[type=text] {\n padding: 15px 10px;\n display: block;\n width: 100%;\n font: inherit;\n height: 52px;\n border: 1px solid #aaa;\n border-radius: 0;\n box-shadow: none;\n}\n.rs-sign-in-form button.rs-connect {\n padding: 15px 10px;\n margin-top: 20px;\n margin-bottom: 15px;\n display: block;\n width: 100%;\n border: none;\n border-radius: 3px;\n background-color: #3fb34f;\n font: inherit;\n color: #fff;\n transition: box-shadow 200ms, background-color 200ms;\n}\n\n.rs-sign-in-form button.rs-connect:hover {\n cursor: pointer;\n background-color: #4BCB5D;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n\n.rs-sign-in-form button.rs-connect:active {\n background-color: #3fb34f;\n}\n\n.rs-sign-in-form button.rs-connect:disabled,\n.rs-sign-in-form button.rs-connect:disabled:hover {\n background-color: #aaa;\n}\n\n.rs-sign-in-form button.rs-connecting svg {\n height: 1em;\n width: auto;\n vertical-align: middle;\n margin-left: 0.5em;\n animation: rs-spin 1s linear infinite;\n}\n\n.rs-sign-in-error.rs-hidden,\n.rs-box-error.rs-hidden {\n height: 0;\n}\n\n.rs-sign-in-error.rs-visible,\n.rs-box-error.rs-visible {\n height: auto;\n border-radius: 3px;\n padding: 0.5em 0.5em;\n margin-top: 0.5em;\n text-align: center;\n background-color: rgba(255,0,0,0.1);\n color: darkred;\n}\n\n.rs-box-error {\n display: flex;\n flex-direction: row;\n}\n\n.rs-box-error .rs-error-message {\n flex: auto;\n}\n\n /*Choose provider box */\n.rs-box-choose {\n text-align: center;\n overflow: hidden;\n}\n\n.rs-box-choose p {\n margin-top: 0;\n margin-bottom: 20px;\n line-height: 1.4em;\n}\n\n/*Connected box */\n.rs-box-connected {\n display: flex;\n flex-direction: row;\n height: 40px;\n transition: height 0s;\n}\n.rs-connected-text {\n flex: auto;\n min-width: 0;\n}\n.rs-box-connected .rs-user {\n font-weight: bold;\n text-overflow: ellipsis;\n overflow: hidden;\n word-break: keep-all;\n}\n.rs-connected-buttons, .rs-error-buttons {\n flex: none;\n}\n.rs-disconnect:hover {\n border-color: #FF2D2D;\n}\n.rs-disconnect:hover .rs-icon{\n fill: #FF2D2D;\n}\n.rs-sync:hover {\n border-color: #FFBB0C;\n}\n.rs-sync:hover .rs-icon {\n fill: #FFBB0C;\n}\n.rs-sync.rs-rotate {\n border-color: #FFBB0C;\n}\n.rs-sync.rs-rotate .rs-icon {\n fill: #FFBB0C;\n animation: rs-spin 1s linear infinite;\n}\n\n/* Floating widget styles (top right corner) */\n.rs-floating {\n position: fixed;\n top: 0;\n right: 0;\n}\n\n@keyframes rs-spin {\n 100% {\n transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n/* Small/mobile screens */\n@media screen and (max-width: 420px) {\n .rs-widget {\n font-size: 100%;\n transition: all 300ms ease-out;\n max-width: 400px;\n }\n .rs-floating {\n position: relative;\n top: auto;\n right: auto\n }\n .rs-closed {\n max-width: 56px;\n }\n .rs-state-choose,\n .rs-state-sign-in {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n max-width: 100%;\n }\n}\n\n/* remove dotted outline border on Firefox */\n.rs-widget a:focus,\n.rs-widget a:active,\n.rs-widget button:focus,\n.rs-widget input:focus {\n outline:none;\n}\n.rs-widget button::-moz-focus-inner,\n.rs-widget input[type="button"]::-moz-focus-inner {\n border:0;\n}\n\n/* prevent rounded buttons on mobile Safari */\n.rs-widget button,\n.rs-widget input[type="button"] {\n -webkit-appearance: none;\n}\n\n.remotestorage-widget-modal-backdrop {\n display: none;\n position: fixed;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-color: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: opacity 0.3s linear;\n}\n\n.remotestorage-widget-modal-backdrop.visible {\n opacity: 1;\n transition: opacity 0.3s linear;\n}\n',t.appendChild(e),t}},{key:"setModalClass",value:function(){if(this.modalBackdrop){if("onlySmallScreens"===this.modalBackdrop&&!this.isSmallScreen())return;this.rsWidget.classList.add("rs-modal")}}},{key:"setupElements",value:function(){if(!this.parentContainerEl)throw new Error("Parent container element not found");this.rsWidget=this.parentContainerEl.querySelector(".rs-widget"),this.rsBackdrop=this.parentContainerEl.querySelector(".remotestorage-widget-modal-backdrop"),this.rsInitial=this.parentContainerEl.querySelector(".rs-box-initial"),this.rsChoose=this.parentContainerEl.querySelector(".rs-box-choose"),this.rsConnected=this.parentContainerEl.querySelector(".rs-box-connected"),this.rsSignIn=this.parentContainerEl.querySelector(".rs-box-sign-in"),this.rsConnectedLabel=this.parentContainerEl.querySelector(".rs-box-connected .rs-sub-headline"),this.rsChooseRemoteStorageButton=this.parentContainerEl.querySelector("button.rs-choose-rs"),this.rsChooseDropboxButton=this.parentContainerEl.querySelector("button.rs-choose-dropbox"),this.rsChooseGoogleDriveButton=this.parentContainerEl.querySelector("button.rs-choose-googledrive"),this.rsErrorBox=this.parentContainerEl.querySelector(".rs-box-error .rs-error-message"),this.rs.apiKeys.hasOwnProperty("googledrive")||this.rsChooseGoogleDriveButton.parentNode.removeChild(this.rsChooseGoogleDriveButton),this.rs.apiKeys.hasOwnProperty("dropbox")||this.rsChooseDropboxButton.parentNode.removeChild(this.rsChooseDropboxButton),this.rsSignInForm=this.parentContainerEl.querySelector(".rs-sign-in-form"),this.rsAddressInput=this.rsSignInForm.querySelector("input[name=rs-user-address]"),this.rsConnectButton=this.parentContainerEl.querySelector(".rs-connect"),this.rsDisconnectButton=this.parentContainerEl.querySelector(".rs-disconnect"),this.rsSyncButton=this.parentContainerEl.querySelector(".rs-sync"),this.rsLogo=this.parentContainerEl.querySelector(".rs-widget-icon"),this.rsErrorReconnectLink=this.parentContainerEl.querySelector(".rs-box-error a.rs-reconnect"),this.rsErrorDisconnectButton=this.parentContainerEl.querySelector(".rs-box-error button.rs-disconnect"),this.rsConnectedUser=this.parentContainerEl.querySelector(".rs-connected-text h1.rs-user")}},{key:"setupHandlers",value:function(){var t=this;this.rs.on("connected",function(){return t.eventHandler("connected")}),this.rs.on("ready",function(){return t.eventHandler("ready")}),this.rs.on("disconnected",function(){return t.eventHandler("disconnected")}),this.rs.on("network-online",function(){return t.eventHandler("network-online")}),this.rs.on("network-offline",function(){return t.eventHandler("network-offline")}),this.rs.on("error",function(e){return t.eventHandler("error",e)}),this.setEventListeners(),this.setClickHandlers()}},{key:"attach",value:function(t){var e=this.createHtmlTemplate(t);if(this.parentContainerEl,t instanceof HTMLElement)this.parentContainerEl=t;else if("string"==typeof t){if(this.parentContainerEl=document.getElementById(t),!this.parentContainerEl)throw new Error('Failed to find target DOM element with id="'+t+'"')}else{if(t)throw new Error("Unknown element type. Expected instance of HTMLElement or type of string.");this.parentContainerEl=document.body}this.parentContainerEl.appendChild(e),this.setupElements(),this.setupHandlers(),this.setInitialState(),this.setModalClass()}},{key:"setEventListeners",value:function(){var t=this;this.rsSignInForm.addEventListener("submit",function(e){e.preventDefault();var n=t.parentContainerEl.querySelector("input[name=rs-user-address]").value.trim();t.disableConnectButton(),t.rs.connect(n)})}},{key:"showChooseOrSignIn",value:function(){this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.style.display="block",this.rsBackdrop.classList.add("visible")),this.rs.apiKeys&&Object.keys(this.rs.apiKeys).length>0?this.setState("choose"):this.setState("sign-in")}},{key:"setClickHandlers",value:function(){var t=this;this.rsInitial.addEventListener("click",function(){return t.showChooseOrSignIn()}),this.rsChooseRemoteStorageButton.addEventListener("click",function(){t.setState("sign-in"),t.rsAddressInput.focus()}),this.rsChooseDropboxButton.addEventListener("click",function(){return t.rs.dropbox.connect()}),this.rsChooseGoogleDriveButton.addEventListener("click",function(){return t.rs.googledrive.connect()}),this.rsDisconnectButton.addEventListener("click",function(){return t.rs.disconnect()}),this.rsErrorReconnectLink.addEventListener("click",function(){return t.rs.reconnect()}),this.rsErrorDisconnectButton.addEventListener("click",function(){return t.rs.disconnect()}),this.rs.hasFeature("Sync")&&this.rsSyncButton.addEventListener("click",function(){t.rsSyncButton.classList.contains("rs-rotate")?(t.rs.stopSync(),t.rsSyncButton.classList.remove("rs-rotate")):(t.rsConnectedLabel.textContent="Synchronizing",t.rs.startSync(),t.rsSyncButton.classList.add("rs-rotate"))}),document.addEventListener("click",function(){return t.close()}),this.rsWidget.addEventListener("click",function(t){return t.stopPropagation()}),this.rsLogo.addEventListener("click",function(){return t.toggle()})}},{key:"toggle",value:function(){this.closed?this.open():"initial"===this.state?this.showChooseOrSignIn():this.close()}},{key:"open",value:function(){this.closed=!1,this.rsWidget.classList.remove("rs-closed"),this.shouldCloseWhenSyncDone=!1;var t=this.parentContainerEl.querySelector(".rs-box.rs-selected");t&&t.setAttribute("aria-hidden","false")}},{key:"close",value:function(){var t=this;if("error"!==this.state){if(!this.leaveOpen&&this.active){this.closed=!0,this.rsWidget.classList.add("rs-closed");var e=this.parentContainerEl.querySelector(".rs-box.rs-selected");e&&e.setAttribute("aria-hidden","true")}else this.active?this.setState("connected"):this.setInitialState();this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.classList.remove("visible"),setTimeout(function(){t.rsBackdrop.style.display="none"},300))}}},{key:"disableConnectButton",value:function(){this.rsConnectButton.disabled=!0,this.rsConnectButton.classList.add("rs-connecting"),this.rsConnectButton.innerHTML="Connecting ".concat('\n \n \n \n \n \n \n\n')}},{key:"enableConnectButton",value:function(){this.rsConnectButton.disabled=!1,this.rsConnectButton.textContent="Connect",this.rsConnectButton.classList.remove("rs-connecting")}},{key:"setOffline",value:function(){this.online&&(this.rsWidget.classList.add("rs-offline"),this.rsConnectedLabel.textContent="Offline",this.online=!1)}},{key:"setOnline",value:function(){this.online||(this.rsWidget.classList.remove("rs-offline"),this.active&&(this.rsConnectedLabel.textContent="Connected")),this.online=!0}},{key:"setBackendClass",value:function(t){this.rsWidget.classList.remove("rs-backend-remotestorage"),this.rsWidget.classList.remove("rs-backend-dropbox"),this.rsWidget.classList.remove("rs-backend-googledrive"),t&&this.rsWidget.classList.add("rs-backend-".concat(t))}},{key:"showErrorBox",value:function(t){this.rsErrorBox.innerHTML=t,this.setState("error")}},{key:"hideErrorBox",value:function(){this.rsErrorBox.innerHTML="",this.close()}},{key:"handleSyncStarted",value:function(){var t=this;this.syncInProgress=!0,this.rsSyncButton.classList.add("rs-rotate"),setTimeout(function(){t.syncInProgress&&(t.rsConnectedLabel.textContent="Synchronizing")},1e3)}},{key:"handleDiscoveryError",value:function(t){var e=this.parentContainerEl.querySelector(".rs-sign-in-error");e.innerHTML=t.message,e.classList.remove("rs-hidden"),e.classList.add("rs-visible"),this.enableConnectButton()}},{key:"handleSyncError",value:function(){this.setOffline()}},{key:"handleUnauthorized",value:function(t){t.code&&"access_denied"===t.code?this.rs.disconnect():(this.open(),this.showErrorBox(t.message+" "),this.rsErrorBox.appendChild(this.rsErrorReconnectLink),this.rsErrorReconnectLink.classList.remove("rs-hidden"))}},{key:"updateLastSyncedStatus",value:function(){var t=new Date;this.online?(this.lastSynced=t,this.rsConnectedLabel.textContent="Synced"):this.rsWidget.classList.contains("rs-state-unauthorized")||(this.rsConnectedLabel.textContent="Offline")}},{key:"isSmallScreen",value:function(){return window.innerWidth<421}}],e&&function(t,e){for(var n=0;n{n?this.updated.push(this.wrapRecord(t)):(this.added.push(this.wrapRecord(t)),n=!0)}),this.recordCaches.set(t,e)}return e}constructor(t,e,n,r,i,s){this.wrapRecord=i,this.release=s,this.recordArrayCache=$e(()=>{let s=new Set;De(on(t,"[]")),fj(t,t=>{qe(this.getCacheForItem(t)),s.add(t)}),He(()=>{this.recordCaches.forEach((t,e)=>{s.has(e)||(this.removed.push(i(e)),this.recordCaches.delete(e))})}),this.added.length>0&&(e(this.added),this.added=[]),this.updated.length>0&&(n(this.updated),this.updated=[]),this.removed.length>0&&(r(this.removed),this.removed=[])})}revalidate(){qe(this.recordArrayCache)}}class mj{constructor(t,e,n){this.release=n;let r=!1;this.cache=$e(()=>{fj(t,()=>{}),De(on(t,"[]")),!0===r?Sa(e):r=!0}),this.release=n}revalidate(){qe(this.cache)}}class yj extends Mu{releaseMethods=sd();recordsWatchers=new Map;typeWatchers=new Map;flushWatchers=null;constructor(t){super(t),this.containerDebugAdapter=ui(this).lookup("container-debug-adapter:main")}attributeLimit=3;acceptsModelName=!0;getFilters(){return sd()}watchModelTypes(t,e){let n,r=this.getModelTypes(),i=sd();n=r.map(t=>{let n=t.klass,r=this.wrapModelType(n,t.name);return i.push(this.observeModelType(t.name,e)),r}),t(n);let s=()=>{i.forEach(t=>t()),this.releaseMethods.removeObject(s)};return this.releaseMethods.pushObject(s),s}_nameToClass(t){if("string"==typeof t){let e=ui(this).factoryFor(`model:${t}`);t=e&&e.class}return t}watchRecords(t,e,n,r){let i=this._nameToClass(t),s=this.getRecords(i,t),{recordsWatchers:o}=this,a=o.get(s);return a||(a=new gj(s,e,n,r,t=>this.wrapRecord(t),()=>{o.delete(s),this.updateFlushWatchers()}),o.set(s,a),this.updateFlushWatchers(),a.revalidate()),a.release}updateFlushWatchers(){null===this.flushWatchers?(this.typeWatchers.size>0||this.recordsWatchers.size>0)&&(this.flushWatchers=()=>{this.typeWatchers.forEach(t=>t.revalidate()),this.recordsWatchers.forEach(t=>t.revalidate())},ma.on("end",this.flushWatchers)):0===this.typeWatchers.size&&0===this.recordsWatchers.size&&(ma.off("end",this.flushWatchers),this.flushWatchers=null)}willDestroy(){this._super(...arguments),this.typeWatchers.forEach(t=>t.release()),this.recordsWatchers.forEach(t=>t.release()),this.releaseMethods.forEach(t=>t()),this.flushWatchers&&ma.off("end",this.flushWatchers)}detect(t){return!1}columnsForType(t){return sd()}observeModelType(t,e){let n=this._nameToClass(t),r=this.getRecords(n,t),{typeWatchers:i}=this,s=i.get(r);return s||(s=new mj(r,()=>{e([this.wrapModelType(n,t)])},()=>{i.delete(r),this.updateFlushWatchers()}),i.set(r,s),this.updateFlushWatchers(),s.revalidate()),s.release}wrapModelType(t,e){return{name:e,count:Cs(this.getRecords(t,e),"length"),columns:this.columnsForType(t),object:t}}getModelTypes(){let t=this.containerDebugAdapter,e=(t.canCatalogEntriesByType("model")?t.catalogEntriesByType("model"):this._getObjectsOnNamespaces()).map(t=>({klass:this._nameToClass(t),name:t}));return e.filter(t=>this.detect(t.klass))}_getObjectsOnNamespaces(){let t=Z_.NAMESPACES,e=[];return t.forEach(t=>{for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!this.detect(t[n]))continue;let r=Ff(n);e.push(r)}}),e}getRecords(t,e){return sd()}wrapRecord(t){return{object:t,columnValues:this.getRecordColumnValues(t),searchKeywords:this.getRecordKeywords(t),filterValues:this.getRecordFilterValues(t),color:this.getRecordColor(t)}}getRecordColumnValues(t){return{}}getRecordKeywords(t){return sd()}getRecordFilterValues(t){return{}}getRecordColor(t){return null}}const vj={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function bj(t,e){return"[]"===e?(t._revalidate(),t._arrTag):"length"===e?(t._revalidate(),t._lengthTag):on(t,e)}class wj extends Mu{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(t){super.init(t),lr(this,bj)}[rs](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(t){return di(Cs(this,"arrangedContent"),t)}replace(t,e,n){this.replaceContent(t,e,n)}replaceContent(t,e,n){Hs(Cs(this,"content"),t,e,n)}objectAt(t){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&t>=this._objectsDirtyIndex){let t=Cs(this,"arrangedContent");if(t){let e=this._objects.length=Cs(t,"length");for(let t=this._objectsDirtyIndex;ti)&&(this._objectsDirtyIndex=i),this._lengthDirty=!0,Vs(this,e,n,r,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!de(this._arrangedContentTag,this._arrangedContentRevision))){let t=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(t):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(t),this._arrangedContentIsUpdating=!1);let e=this._arrangedContentTag=on(this,"arrangedContent");this._arrangedContentRevision=he(this._arrangedContentTag),G(t)?(this._lengthTag=ke([e,fi(t,"length")]),this._arrTag=ke([e,fi(t,"[]")])):this._lengthTag=this._arrTag=e}}}wj.reopen(nd,{arrangedContent:Ns("content")});const _j=Object.freeze(Object.defineProperty({__proto__:null,default:wj},Symbol.toStringTag,{value:"Module"}));class xj extends ih{}xj.PrototypeMixin.reopen(tc);const Cj=Object.freeze(Object.defineProperty({__proto__:null,default:xj},Symbol.toStringTag,{value:"Module"})),Sj=ql.create({reason:null,isPending:ps("isSettled",function(){return!Cs(this,"isSettled")}).readOnly(),isSettled:ps("isRejected","isFulfilled",function(){return Cs(this,"isRejected")||Cs(this,"isFulfilled")}).readOnly(),isRejected:!1,isFulfilled:!1,promise:ps({get(){throw new Error("PromiseProxy's promise must be set")},set(t,e){return function(t,e){return Qs(t,{isFulfilled:!1,isRejected:!1}),e.then(e=>(t.isDestroyed||t.isDestroying||Qs(t,{content:e,isFulfilled:!0}),e),e=>{throw t.isDestroyed||t.isDestroying||Qs(t,{reason:e,isRejected:!0}),e},"Ember: PromiseProxy")}(this,e)}}),then:kj("then"),catch:kj("catch"),finally:kj("finally")});function kj(t){return function(...e){return Cs(this,"promise")[t](...e)}}const Ej=Object.freeze(Object.defineProperty({__proto__:null,default:Sj},Symbol.toStringTag,{value:"Module"}));function Tj(t,e,n){return t.lookup(`controller:${e}`,n)}let Rj;!function(t){function e(){}t.isNamespace=!0,t.toString=function(){return"Ember"},t.Container=gl,t.Registry=El,t._setComponentManager=pj,t._componentManagerCapabilities=jr,t._modifierManagerCapabilities=Vr,t.meta=ae,t._createCache=$e,t._cacheGetValue=qe,t._cacheIsConst=Ve,t._descriptor=Ci,t._getPath=ks,t._setClassicDecorator=Ai,t._tracked=Is,t.beginPropertyChanges=os,t.changeProperties=ls,t.endPropertyChanges=as,t.hasListeners=Ui,t.libraries=Rs,t._ContainerProxyMixin=Zl,t._ProxyMixin=tc,t._RegistryProxyMixin=Gl,t.ActionHandler=Xl,t.Comparable=Yl,t.ComponentLookup=ex,t.EventDispatcher=eh,t._Cache=si,t.GUID_KEY=Q,t.canInvoke=K_,t.generateGuid=tt,t.guidFor=et,t.uuid=Z,t.wrap=mt,t.getOwner=cx,t.onLoad=pl,t.runLoadHooks=fl,t.setOwner=ux,t.Application=hx,t.ApplicationInstance=H_,t.Namespace=Z_,t.A=sd,t.Array=ed,t.NativeArray=rd,t.isArray=Jh,t.makeArray=mu,t.MutableArray=nd,t.ArrayProxy=wj,t.FEATURES={isEnabled:oj,...sj},t._Input=qb,t.Component=Ew,t.Helper=Mw,t.Controller=cd,t.ControllerMixin=ld,t._captureRenderTree=A,t.assert=y,t.warn=z,t.debug=D,t.deprecate=V,t.deprecateFunc=q,t.runInDebug=B,t.inspect=L,t.Debug={registerDeprecationHandler:v,registerWarnHandler:x,isComputed:gs},t.ContainerDebugAdapter=tx,t.DataAdapter=yj,t._assertDestroyablesDestroyed=Nt,t._associateDestroyableChild=Wt,t._enableDestroyableTracking=Dt,t._isDestroying=Zt,t._isDestroyed=Yt,t._registerDestructor=_x,t._unregisterDestructor=xx,t.destroy=Gt,t.Engine=ox,t.EngineInstance=fd,t.Enumerable=ec,t.MutableEnumerable=nc,t.instrument=lh,t.subscribe=dh,t.Instrumentation={instrument:lh,subscribe:dh,unsubscribe:ph,reset:fh},t.Object=Mu,t._action=Pu,t.computed=ps,t.defineProperty=ms,t.get=Cs,t.getProperties=Js,t.notifyPropertyChange=ss,t.observer=Au,t.set=Fs,t.trySet=Ds,t.setProperties=Qs,t.cacheFor=Os,t._dependentKeyCompat=md,t.ComputedProperty=us,t.expandProperties=Fi,t.CoreObject=Su,t.Evented=nh,t.on=$i,t.addListener=Ni,t.removeListener=ji,t.sendEvent=Bi,t.Mixin=ql,t.mixin=Ul,t.Observable=Tu,t.addObserver=Hi,t.removeObserver=Gi,t.PromiseProxyMixin=Sj,t.ObjectProxy=xj,t.RouterDSL=Fp,t.controllerFor=Tj,t.generateController=fp,t.generateControllerFactory=pp,t.HashLocation=bf,t.HistoryLocation=xf,t.NoneLocation=Cf,t.Route=kp,t.Router=af,t.run=ya,t.Service=qf,t.compare=jh,t.isBlank=aj,t.isEmpty=kf,t.isEqual=cj,t.isNone=Sf,t.isPresent=lj,t.typeOf=zh,t.VERSION=oi,t.ViewUtils={getChildViews:Ku,getElementView:Uu,getRootViews:Du,getViewBounds:Yu,getViewBoundingClientRect:Qu,getViewClientRects:Ju,getViewElement:$u,isSimpleClick:Fu,isSerializationFirstNode:hb},t._getComponentTemplate=Jr,t._helperManagerCapabilities=vr,t._setComponentTemplate=Xr,t._setHelperManager=Kr,t._setModifierManager=Gr,t._templateOnlyComponent=Ny,t._invokeHelper=gv,t._hash=dv,t._array=av,t._concat=cv,t._get=hv,t._on=wv,t._fn=uv,t._Backburner=ha,t.inject=e,e.controller=ud,e.service=$f,t.__loader={get require(){return globalThis.require},get define(){return globalThis.define},get registry(){let t=globalThis;return t.requirejs?.entries??t.require.entries}}}(Rj||(Rj={})),Reflect.set(Rj,"RSVP",pu),Object.defineProperty(Rj,"ENV",{get:m,enumerable:!1}),Object.defineProperty(Rj,"lookup",{get:p,set:f,enumerable:!1}),Object.defineProperty(Rj,"onerror",{get:ko,set:function(t){Co=t},enumerable:!1}),Object.defineProperty(Rj,"testing",{get:w,set:_,enumerable:!1}),Object.defineProperty(Rj,"BOOTED",{configurable:!1,enumerable:!1,get:mo,set:yo}),Object.defineProperty(Rj,"TEMPLATES",{get:dj,set:hj,configurable:!1,enumerable:!1}),Object.defineProperty(Rj,"TEMPLATES",{get:dj,set:hj,configurable:!1,enumerable:!1}),Object.defineProperty(Rj,"testing",{get:w,set:_,enumerable:!1}),fl("Ember.Application",hx);let Mj={template:em,Utils:{}},Lj={template:em};function Ij(t){Object.defineProperty(Rj,t,{configurable:!0,enumerable:!0,get:()=>"Handlebars"===t?Mj:Lj})}function Pj(t){Object.defineProperty(Rj,t,{configurable:!0,enumerable:!0,get(){}})}Ij("HTMLBars"),Ij("Handlebars"),Pj("Test"),Pj("setupForTesting"),fl("Ember"),new Proxy(Rj,{get:(t,e,n)=>("string"==typeof e&&Uf(`importing ${e} from the 'ember' barrel file is deprecated.`,Bf.DEPRECATE_IMPORT_EMBER(e)),Reflect.get(t,e,n)),getOwnPropertyDescriptor:(t,e)=>("string"==typeof e&&Uf(`importing ${e} from the 'ember' barrel file is deprecated.`,Bf.DEPRECATE_IMPORT_EMBER(e)),Object.getOwnPropertyDescriptor(t,e))});const Aj=new WeakMap;function Oj(t,e,...n){if(t[e],t.isDestroying)return;"boolean"==typeof n[n.length-1]&&n[n.length-2];let r=Aj.get(t);var i;let s;r||(r=new Map,Aj.set(t,r),_x(t,(i=r,function(){0!==i.size&&i.forEach(t=>ka(t.cancelId))}))),s=r.has(e)?r.get(e).debouncedTask:(...n)=>{r.delete(e),t[e](...n)};let o=Ea(t,s,...n);r.set(e,{debouncedTask:s,cancelId:o})}class Fj extends qf{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");rs;widget;static{dF(this.prototype,"placesInView",[Is],function(){return[]})}#ut=void fF(this,"placesInView");static{dF(this.prototype,"savedPlaces",[Is],function(){return[]})}#ht=void fF(this,"savedPlaces");static{dF(this.prototype,"loadedPrefixes",[Is],function(){return[]})}#dt=void fF(this,"loadedPrefixes");static{dF(this.prototype,"currentBbox",[Is],function(){return null})}#pt=void fF(this,"currentBbox");static{dF(this.prototype,"lists",[Is],function(){return[]})}#ft=void fF(this,"lists");static{dF(this.prototype,"version",[Is],function(){return 0})}#gt=void fF(this,"version");static{dF(this.prototype,"initialSyncDone",[Is],function(){return!1})}#mt=void fF(this,"initialSyncDone");static{dF(this.prototype,"connected",[Is],function(){return!1})}#yt=void fF(this,"connected");static{dF(this.prototype,"userAddress",[Is],function(){return null})}#vt=void fF(this,"userAddress");static{dF(this.prototype,"isWidgetOpen",[Is],function(){return!1})}#bt=void fF(this,"isWidgetOpen");constructor(){super(...arguments),this.rs=new WN({modules:[QN]}),this.rs.access.claim("places","rw"),this.rs.caching.enable("/places/"),window.remoteStorage=this.rs,this.widget=new ij(this.rs,{leaveOpen:!0,skipInitial:!0}),this.rs.on("ready",()=>{}),this.rs.on("error",t=>{t&&(console.info("[rs] Error —",`${t.name}: ${t.message}`),"Unauthorized"===t.name&&this.showConnectWidget())}),this.rs.on("connected",()=>{this.connected=!0,this.userAddress=this.rs.remote.userAddress,this.loadLists()}),this.rs.on("not-connected",()=>{this.loadLists()}),this.rs.on("disconnected",()=>{this.connected=!1,this.userAddress=null,this.placesInView=[],this.savedPlaces=[],this.loadedPrefixes=[],this.lists=[],this.initialSyncDone=!1}),this.rs.on("sync-done",()=>{this.initialSyncDone||(this.initialSyncDone=!0,this.loadLists())}),this.rs.scope("/places/").on("change",t=>{t.relativePath.startsWith("_lists/")?this.loadLists():(this.handlePlaceChange(t),Oj(this,"reloadCurrentView",200))})}handlePlaceChange(t){const{newValue:e,relativePath:n}=t,r=n.split("/"),i=r[r.length-1];if(e){const t={...e,id:i},n=this.savedPlaces.findIndex(t=>t.id===i);if(-1!==n){const e=[...this.savedPlaces];e[n]=t,this.savedPlaces=e}else this.savedPlaces=[...this.savedPlaces,t]}else this.savedPlaces=this.savedPlaces.filter(t=>t.id!==i)}get places(){return this.rs.places}notifyChange(){this.version++,Oj(this,"reloadCurrentView",200)}reloadCurrentView(){if(!this.currentBbox)return;const t=ND(this.currentBbox);console.debug("Reloading view due to changes, prefixes:",t),this.loadAllPlaces(t)}async loadLists(){try{if(!this.places.lists)return;await this.places.lists.initDefaults();const t=await this.places.lists.getAll();this.lists=t||[],this.lists.forEach(t=>{"to-go"===t.id?t.icon="bookmark":"to-do"===t.id&&(t.icon="check-square")}),this.refreshPlaceListAssociations()}catch(ej){console.error("Failed to load lists:",ej)}}refreshPlaceListAssociations(){const t=new Map;this.lists.forEach(e=>{e.placeRefs&&Array.isArray(e.placeRefs)&&e.placeRefs.forEach(n=>{n.id&&(t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(e.id))})});const e=e=>{const n=t.get(e.id)||[];return e._listIds=n,e};this.savedPlaces=this.savedPlaces.map(t=>e({...t})),this.placesInView=this.placesInView.map(t=>e({...t}))}async togglePlaceList(t,e,n){if(!t)return;let r=t;if(!t.id||!t.geohash){if(!n)return;r=await this.storePlace(t)}try{return n?await this.places.lists.addPlace(e,r.id,r.geohash):await this.places.lists.removePlace(e,r.id),await this.loadLists(),this.findPlaceById(r.id)}catch(ej){throw console.error("Failed to toggle place in list:",ej),ej}}async loadPlacesInBounds(t){const e=ND(t).filter(t=>!this.loadedPrefixes.includes(t));0!==e.length&&(console.debug("Loading new prefixes:",e),await this.loadAllPlaces(e),this.loadedPrefixes=[...this.loadedPrefixes,...e],this.currentBbox=t)}async loadAllPlaces(t=null){try{const e=await this.places.getPlaces(t);if(e&&Array.isArray(e)){if(t){const n=new Set(t),r=this.placesInView.filter(t=>{if(!t.lat||!t.lon)return!1;try{const e=DD.encode(t.lat,t.lon,4);return!n.has(e)}catch{return!0}});this.placesInView=[...r,...e]}else this.placesInView=e;this.refreshPlaceListAssociations()}else t||(this.placesInView=[]);console.debug("Loaded saved places:",this.placesInView.length)}catch(ej){console.error("Failed to load places:",ej)}}findPlaceById(t){if(!t)return;const e=String(t);let n=this.savedPlaces.find(t=>t.id&&String(t.id)===e);return n||(n=this.placesInView.find(t=>t.id&&String(t.id)===e),n||(n=this.savedPlaces.find(t=>t.osmId&&String(t.osmId)===e),n||(n=this.placesInView.find(t=>t.osmId&&String(t.osmId)===e),n)))}isPlaceSaved(t){return!!this.findPlaceById(t)}async storePlace(t){const e=await this.places.store(t);return this.savedPlaces.some(t=>t.id===e.id)?this.savedPlaces=this.savedPlaces.map(t=>t.id===e.id?e:t):this.savedPlaces=[...this.savedPlaces,e],this.placesInView.some(t=>t.id===e.id)?this.placesInView=this.placesInView.map(t=>t.id===e.id?e:t):this.placesInView=[...this.placesInView,e],e}async updatePlace(t){const e=await this.places.store(t),n=this.savedPlaces.findIndex(t=>t.id===e.id);if(-1!==n){const t=[...this.savedPlaces];t[n]=e,this.savedPlaces=t}return this.placesInView=this.placesInView.map(t=>t.id===e.id?e:t),e}async removePlace(t){await this.places.remove(t.id,t.geohash),this.savedPlaces=this.savedPlaces.filter(e=>e.id!==t.id),this.placesInView.length>0&&(this.placesInView=this.placesInView.filter(e=>e.id!==t.id))}async refreshPlace(t){if(!(t&&t.id&&t.osmId&&t.osmType))return null;try{console.debug(`Checking for updates for ${t.title} (${t.osmId})`);const e=await this.osm.fetchOsmObject(t.osmId,t.osmType);if(!e)return console.warn("Could not fetch fresh data for",t.osmId),null;let n=!1;const r={},i=Math.abs(t.lat-e.lat),s=Math.abs(t.lon-e.lon);(i>1e-5||s>1e-5)&&(n=!0,r.lat=e.lat,r.lon=e.lon);const o=t.osmTags||{},a=e.osmTags||{},l=new Set([...Object.keys(o),...Object.keys(a)]);for(const t of l)if(o[t]!==a[t]){n=!0,r.osmTags=a;break}if(!n)return console.debug("No changes detected for",t.title),null;console.debug("Changes detected:",r);const c={...t,...r},u=RN(o),h=RN(a);return t.title===u&&u!==h&&(c.title=h),await this.updatePlace(c)}catch(ej){return console.error("Failed to refresh place:",ej),null}}showConnectWidget(){this.isWidgetOpen=!0,document.querySelector(".rs-widget")||this.widget.attach("rs-widget-container")}static{pF(this.prototype,"showConnectWidget",[Pu])}closeWidget(){this.isWidgetOpen=!1}static{pF(this.prototype,"closeWidget",[Pu])}disconnect(){this.rs.disconnect(),this.isWidgetOpen=!1}static{pF(this.prototype,"disconnect",[Pu])}}const zj=Object.freeze(Object.defineProperty({__proto__:null,default:Fj},Symbol.toStringTag,{value:"Module"}));class Dj extends qf{static{dF(this.prototype,"message",[Is],function(){return null})}#wt=void fF(this,"message");static{dF(this.prototype,"isVisible",[Is],function(){return!1})}#_t=void fF(this,"isVisible");timeoutId=null;show(t,e=3e3){this.message=t,this.isVisible=!0,this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isVisible=!1},e)}}const Nj=Object.freeze(Object.defineProperty({__proto__:null,default:Dj},Symbol.toStringTag,{value:"Module"}));function jj(t,e,n,r){const i=t*Math.PI/180,s=n*Math.PI/180,o=(n-t)*Math.PI/180,a=(r-e)*Math.PI/180,l=Math.sin(o/2)*Math.sin(o/2)+Math.cos(i)*Math.cos(s)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3}const Bj=Object.freeze(Object.defineProperty({__proto__:null,getDistance:jj},Symbol.toStringTag,{value:"Module"})),Uj={activity:'',angelfish:'\n \n',"arrow-left":'',barbell:'\n \n',banknote:'\n \n',"badge-shield-with-fire":'\n \n',"beach-umbrella-in-ground":'\n \n',"beer-mug-with-foam":'\n \n',bookmark:'',"boxing-glove-up":'\n \n',"burger-and-drink-cup-with-straw":'\n \n',bus:'\n \n',camera:'',"check-square":'',"chevron-left":'',"chevron-right":'',"cigarette-with-smoke-curl":'\n \n',climbing_wall:'\n \n',check:'',"alert-circle":'',"classical-building":'\n \n',"classical-building-with-dome-and-flag":'\n \n',"classical-building-with-flag":'\n \n',"commercial-building":'\n \n',"clothes-hanger":'\n \n',cleaver:'\n \n',cloth:'\n \n',cocktail:'\n \n',clock:'',"coffee-bean":'\n \n',"comedy-mask-and-tragedy-mask":'\n \n',croissant:'\n \n',"cup-and-saucer":'\n \n',database:'',donut:'\n \n',edit:'',eyeglasses:'\n \n',facebook:'',"fancy-mirror-with-reflection-and-stars":'\n \n',"family-restroom-symbol":'\n \n',film:'\n \n',"fingernail-polished":'\n \n',fish:'\n \n',"flag-checkered":'\n \n',"flower-bouquet":'\n \n',"fork-and-knife":'\n \n',fort:'\n \n',gift:'',globe:'',gravestone:'\n \n',"grecian-vase":'\n \n',"greek-cross":'\n \n',heart:'',home:'',"ice-cream-on-cone":'\n \n',info:'',instagram:'',jewel:'\n \n',"log-in":'',"log-out":'',"lowrise-building":'\n \n',mail:'',map:'',"map-pin":'',"market-stall":'\n \n',"memorial-stone-with-inscription":'\n \n',menu:'',"mobile-phone-with-keypad-and-antenna":'\n \n',"molar-tooth":'\n \n',navigation:'',"needle-and-spool-of-thread":'\n \n',nostrich:'\n \n\n',"open-book":'\n \n',palace:'\n \n',"person-cricket-batting-at-cricket-ball":'\n \n',"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track":'\n \n',"person-jockeying-racehorse":'\n \n',"person-playing-tennis":'\n \n',"person-running":'\n \n',"person-sleeping-in-bed":'\n \n',"person-swimming-in-water":'\n \n',"person-swinging-golf-club":'\n \n',phone:'',"plane-top-right":'\n \n',"plant-in-raised-planter":'\n \n',"place-of-worship-building":'\n \n',"play-structure-with-slide":'\n \n',"police-officer-with-stop-arm":'\n \n',plus:'',"round-structure-with-flag":'\n \n',remotestorage:'\n\x3c!-- Creator: CorelDRAW X7 --\x3e\n\n \n',"sailing-ship-in-water":'\n \n',"scissors-open":'\n \n',"shipwreck-in-water":'\n \n',"shopping-bag":'\n \n',search:'',server:'',settings:'',"shopping-basket":'\n \n',"shopping-cart":'\n \n',"table-tennis-paddle":'\n \n',"tattoo-machine":'\n \n',toolbox:'\n \n',target:'',"trash-2":'',"upload-cloud":'',"tree-and-bench-with-backrest":'\n \n',user:'',"village-buildings":'\n \n',"wall-hanging-with-mountains-and-sun":'\n \n',"womens-and-mens-restroom-symbol":'\n \n',whatsapp:'\n\n \n\n',wikipedia:'\n\n\n',parking_p:'\n \n',car:'\n \n',x:'',zap:'',"loading-ring":''},$j=["fork-and-knife","wikipedia","whatsapp","cup-and-saucer","coffee-bean","shopping-basket","person-sleeping-in-bed","loading-ring","nostrich"];function qj(t){return Uj[t]}function Vj(t){return $j.includes(t)}const Wj=Object.freeze(Object.defineProperty({__proto__:null,getIcon:qj,isIconFilled:Vj},Symbol.toStringTag,{value:"Module"})),Hj=[{tags:{cuisine:"donut"},icon:"donut"},{tags:{cuisine:"doughnut"},icon:"donut"},{tags:{cuisine:"coffee_shop"},icon:"coffee-bean"},{tags:{cuisine:"coffee"},icon:"coffee-bean"},{tags:{amenity:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{cuisine:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{shop:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{amenity:"cafe"},icon:"cup-and-saucer"},{tags:{amenity:"restaurant"},icon:"fork-and-knife"},{tags:{amenity:"fast_food"},icon:"burger-and-drink-cup-with-straw"},{tags:{amenity:"pub"},icon:"beer-mug-with-foam"},{tags:{amenity:"bar"},icon:"cocktail"},{tags:{amenity:"food_court"},icon:"fork-and-knife"},{tags:{amenity:"childcare"},icon:"family-restroom-symbol"},{tags:{amenity:"community_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_facility"},icon:"family-restroom-symbol"},{tags:{amenity:"bank"},icon:"banknote"},{tags:{amenity:"place_of_worship"},icon:"place-of-worship-building"},{tags:{amenity:"fire_station"},icon:"badge-shield-with-fire"},{tags:{amenity:"police"},icon:"police-officer-with-stop-arm"},{tags:{amenity:"toilets"},icon:"womens-and-mens-restroom-symbol"},{tags:{amenity:"school"},icon:"open-book"},{tags:{amenity:"driving_school"},icon:"car"},{tags:{shop:"coffee"},icon:"coffee-bean"},{tags:{shop:"tea"},icon:"coffee-bean"},{tags:{shop:"pastry"},icon:"donut"},{tags:{shop:"supermarket"},icon:"shopping-cart"},{tags:{shop:"convenience"},icon:"shopping-basket"},{tags:{shop:"grocery"},icon:"shopping-basket"},{tags:{shop:"greengrocer"},icon:"shopping-basket"},{tags:{shop:"bakery"},icon:"croissant"},{tags:{shop:"butcher"},icon:"cleaver"},{tags:{shop:"seafood"},icon:"fish"},{tags:{shop:"deli"},icon:"shopping-basket"},{tags:{shop:"clothes"},icon:"clothes-hanger"},{tags:{shop:"clothing"},icon:"clothes-hanger"},{tags:{shop:"hairdresser"},icon:"scissors-open"},{tags:{shop:"optician"},icon:"eyeglasses"},{tags:{shop:"fabric"},icon:"cloth"},{tags:{shop:"flea_market"},icon:"market-stall"},{tags:{shop:"kiosk"},icon:"shopping-basket"},{tags:{shop:"leather"},icon:"shopping-bag"},{tags:{shop:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{shop:"jewelry"},icon:"jewel"},{tags:{shop:"jewellery"},icon:"jewel"},{tags:{shop:"tobacco"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"cannabis"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"florist"},icon:"flower-bouquet"},{tags:{shop:"garden_centre"},icon:"plant-in-raised-planter"},{tags:{shop:"estate_agent"},icon:"village-buildings"},{tags:{shop:"mobile_phone"},icon:"mobile-phone-with-keypad-and-antenna"},{tags:{beauty:"nails"},icon:"fingernail-polished"},{tags:{shop:"tattoo"},icon:"tattoo-machine"},{tags:{shop:"beauty"},icon:"fancy-mirror-with-reflection-and-stars"},{tags:{craft:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{office:"estate_agent"},icon:"village-buildings"},{tags:{office:!0},icon:"commercial-building"},{tags:{craft:!0},icon:"toolbox"},{tags:{shop:!0},icon:"shopping-bag"},{tags:{natural:"beach"},icon:"beach-umbrella-in-ground"},{tags:{leisure:"park"},icon:"tree-and-bench-with-backrest"},{tags:{leisure:"playground"},icon:"play-structure-with-slide"},{tags:{aeroway:"aerodrome"},icon:"plane-top-right"},{tags:{aeroway:"heliport"},icon:"plane-top-right"},{tags:{aeroway:"helipad"},icon:"plane-top-right"},{tags:{highway:"bus_stop"},icon:"bus"},{tags:{bus:!0},icon:"bus"},{tags:{railway:"tram_stop"},icon:"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track"},{tags:{tourism:"museum"},icon:"classical-building"},{tags:{tourism:"gallery"},icon:"wall-hanging-with-mountains-and-sun"},{tags:{tourism:"aquarium"},icon:"angelfish"},{tags:{tourism:"theme_park"},icon:"camera"},{tags:{tourism:"attraction"},icon:"camera"},{tags:{tourism:"viewpoint"},icon:"camera"},{tags:{tourism:"zoo"},icon:"camera"},{tags:{tourism:"artwork"},icon:"camera"},{tags:{amenity:"cinema"},icon:"film"},{tags:{amenity:"theatre"},icon:"camera"},{tags:{amenity:"arts_centre"},icon:"comedy-mask-and-tragedy-mask"},{tags:{amenity:"arts_center"},icon:"comedy-mask-and-tragedy-mask"},{tags:{historic:"fort"},icon:"fort"},{tags:{historic:"castle"},icon:"palace"},{tags:{historic:"building"},icon:"classical-building-with-flag"},{tags:{historic:"archaeological_site"},icon:"grecian-vase"},{tags:{historic:"memorial"},icon:"memorial-stone-with-inscription"},{tags:{historic:"tomb"},icon:"gravestone"},{tags:{historic:"monument"},icon:"classical-building-with-dome-and-flag"},{tags:{historic:"ship"},icon:"sailing-ship-in-water"},{tags:{historic:"wreck"},icon:"shipwreck-in-water"},{tags:{historic:"ruins"},icon:"camera"},{tags:{historic:"ruin"},icon:"camera"},{tags:{historic:"yes"},icon:"camera"},{tags:{tourism:"hotel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"hostel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"motel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"guest_house"},icon:"person-sleeping-in-bed"},{tags:{sport:"motor"},icon:"flag-checkered"},{tags:{sport:"karting"},icon:"flag-checkered"},{tags:{sport:"motocross"},icon:"flag-checkered"},{tags:{sport:"cricket"},icon:"person-cricket-batting-at-cricket-ball"},{tags:{sport:"boxing"},icon:"boxing-glove-up"},{tags:{sport:"martial_arts"},icon:"boxing-glove-up"},{tags:{sport:"tennis"},icon:"person-playing-tennis"},{tags:{sport:"squash"},icon:"person-playing-tennis"},{tags:{sport:"padel"},icon:"person-playing-tennis"},{tags:{sport:"table_tennis"},icon:"table-tennis-paddle"},{tags:{sport:"climbing"},icon:"climbing_wall"},{tags:{leisure:"water_park"},icon:"person-swimming-in-water"},{tags:{sport:"swimming"},icon:"person-swimming-in-water"},{tags:{sport:"golf"},icon:"person-swinging-golf-club"},{tags:{leisure:"golf_course"},icon:"person-swinging-golf-club"},{tags:{sport:"horse_racing"},icon:"person-jockeying-racehorse"},{tags:{sport:"fitness"},icon:"barbell"},{tags:{sport:"fitness_centre"},icon:"barbell"},{tags:{leisure:"fitness_centre"},icon:"barbell"},{tags:{sport:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"sports_centre"},icon:"person-running"},{tags:{leisure:"pitch"},icon:"person-running"},{tags:{sport:!0},icon:"person-running"},{tags:{amenity:"dentist"},icon:"molar-tooth"},{tags:{healthcare:"dentist"},icon:"molar-tooth"},{tags:{healthcare:!0},icon:"greek-cross"},{tags:{amenity:"parking"},icon:"parking_p"},{tags:{building:"commercial"},icon:"commercial-building"},{tags:{building:"apartments"},icon:"lowrise-building"}];function Gj(t){if(!t)return null;for(const e of Hj){let n=!0;for(const[r,i]of Object.entries(e.tags)){const e=t[r];if(!e){n=!1;break}const s=e.split(";").map(t=>t.trim());if(!0!==i&&!s.includes(i)){n=!1;break}}if(n)return e.icon}return null}const Kj=Object.freeze(Object.defineProperty({__proto__:null,POI_ICON_RULES:Hj,getIconNameForTags:Gj,getIconSvgForTags:function(t){const e=Gj(t);return e?qj(e):null}},Symbol.toStringTag,{value:"Module"}));function Zj(t){return{title:t.title||RN(t.osmTags,"Untitled Place"),lat:t.lat,lon:t.lon,tags:[],url:t.osmTags?.website,osmId:String(t.osmId||t.id),osmType:t.osmType,osmTags:t.osmTags||{},description:t.description}}const Yj=Object.freeze(Object.defineProperty({__proto__:null,mapToStorageSchema:Zj},Symbol.toStringTag,{value:"Module"}));function Xj(t,e){if(!t)return null;const n=`${e}.com`,r=((t,...e)=>{for(const n of e)if(t[n])return t[n];return null})(t,`contact:${e}`,e);if(!r)return null;if(r.startsWith("http"))try{const t=new URL(r);return"facebook"===e&&"/profile.php"===t.pathname&&t.searchParams.has("id")?{url:r,username:t.searchParams.get("id")}:{url:r,username:t.pathname.replace(/^\/|\/$/g,"")||r}}catch{return{url:r,username:r}}const i=r.replace(/^@/,"");return{url:`https://${n}/${i}`,username:i}}const Jj=Object.freeze(Object.defineProperty({__proto__:null,getSocialInfo:Xj},Symbol.toStringTag,{value:"Module"}));var Qj=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","$","%","*","+",",","-",".",":",";","=","?","@","[","]","^","_","{","|","}","~"],tB=t=>{let e=0;for(let n=0;n{var n="";for(let r=1;r<=e;r++){let i=Math.floor(t)/Math.pow(83,e-r)%83;n+=Qj[Math.floor(i)]}return n},nB=t=>{let e=t/255;return e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)},rB=t=>{let e=Math.max(0,Math.min(1,t));return e<=.0031308?Math.trunc(12.92*e*255+.5):Math.trunc(255*(1.055*Math.pow(e,.4166666666666667)-.055)+.5)},iB=(t,e)=>(t=>t<0?-1:1)(t)*Math.pow(Math.abs(t),e),sB=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t}},oB=t=>{let e=t>>8&255,n=255&t;return[nB(t>>16),nB(e),nB(n)]},aB=(t,e)=>{let n=Math.floor(t/361),r=Math.floor(t/19)%19,i=t%19;return[iB((n-9)/9,2)*e,iB((r-9)/9,2)*e,iB((i-9)/9,2)*e]},lB=(t,e,n,r)=>{let i=0,s=0,o=0,a=4*e;for(let c=0;c{if("PROCESS_IMAGE"!==t.data?.type)return;const{id:e,file:n,targetWidth:r,targetHeight:i,quality:s,computeBlurhash:o}=t.data;try{let t,c;try{const e=await createImageBitmap(n,{resizeWidth:r,resizeHeight:i,resizeQuality:"high"});if(t=new OffscreenCanvas(r,i),c=t.getContext("2d"),!c)throw new Error("Failed to get 2d context from OffscreenCanvas");c.drawImage(e,0,0,r,i),e.close()}catch(a){console.warn("Hardware resize failed, falling back to stepped software scaling:",a);const e=await n.arrayBuffer(),s=new Blob([e],{type:n.type}),o=await createImageBitmap(s);let l=o.width,u=o.height,h=new OffscreenCanvas(l,u),d=h.getContext("2d");for(d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(o,0,0);.5*h.width>r&&.5*h.height>i;){const t=new OffscreenCanvas(Math.floor(.5*h.width),Math.floor(.5*h.height)),e=t.getContext("2d");e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.drawImage(h,0,0,t.width,t.height),h=t}t=new OffscreenCanvas(r,i),c=t.getContext("2d"),c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(h,0,0,r,i),o.close()}let u=null;if(o)try{u=((t,e,n)=>{if(e*n*4!==t.length)throw new sB("Width and height must match the pixels array");let r=[];for(let l=0;l<3;l++)for(let i=0;i<4;i++){let s=0==i&&0==l?1:2,o=lB(t,e,n,(t,r)=>s*Math.cos(Math.PI*i*t/e)*Math.cos(Math.PI*l*r/n));r.push(o)}let i,s=r[0],o=r.slice(1),a="";if(a+=eB(21,1),o.length>0){let t=Math.max(...o.map(t=>Math.max(...t))),e=Math.floor(Math.max(0,Math.min(82,Math.floor(166*t-.5))));i=(e+1)/166,a+=eB(e,1)}else i=1,a+=eB(0,1);return a+=eB((t=>(rB(t[0])<<16)+(rB(t[1])<<8)+rB(t[2]))(s),4),o.forEach(t=>{a+=eB(((t,e)=>19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[0]/e,.5)+9.5))))*19+19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[1]/e,.5)+9.5))))+Math.floor(Math.max(0,Math.min(18,Math.floor(9*iB(t[2]/e,.5)+9.5)))))(t,i),2)}),a})(c.getImageData(0,0,r,i).data,r,i)}catch(l){console.warn("Could not generate blurhash (possible canvas fingerprinting protection):",l)}const h=await t.convertToBlob({type:"image/jpeg",quality:s}),d=`${r}x${i}`;self.postMessage({id:e,success:!0,blob:h,dim:d,blurhash:u})}catch(v5){self.postMessage({id:e,success:!1,error:v5.message})}};const cB=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function uB(t,e,n){return(e=function(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function hB(t,e,n,r){n&&Object.defineProperty(t,e,{enumerable:n.enumerable,configurable:n.configurable,writable:n.writable,value:n.initializer?n.initializer.call(r):void 0})}function dB(t,e,n,r){var i={};return Object.keys(r).forEach(function(t){i[t]=r[t]}),i.enumerable=!!i.enumerable,i.configurable=!!i.configurable,("value"in i||i.initializer)&&(i.writable=!0),void 0===(i=n.slice().reverse().reduce(function(n,r){return r(t,e,n)||n},i)).initializer&&(Object.defineProperty(t,e,i),i=null),i}var pB,fB,gB,mB,yB;const vB="undefined"!=typeof FastBoot,bB="routeDidChange",wB=["separator","prepend","replace"];let _B=(pB=$f("router"),fB=$f("-document"),gB=class extends qf{constructor(t){if(super(t),hB(this,"router",mB,this),hB(this,"document",yB,this),uB(this,"tokens",[]),uB(this,"_defaultConfig",{separator:" | ",prepend:!0,replace:null}),uB(this,"scheduleTitleUpdate",()=>{Ca("afterRender",this,this._updateTitle)}),this._validateExistingTitleElement(),function(t){return"resolveRegistration"in t}(t)){const n=t.resolveRegistration("config:environment");"object"==typeof(e=n)&&null!==e&&"pageTitle"in e&&wB.forEach(t=>{if(!kf(n.pageTitle[t])){const e=n.pageTitle[t];this._defaultConfig[t]=e}})}var e;this.router.on(bB,this.scheduleTitleUpdate)}applyTokenDefaults(t){const e=this._defaultConfig.separator,n=this._defaultConfig.prepend,r=this._defaultConfig.replace;t.previous??=null,t.next??=null,null==t.separator&&(t.separator=e),null==t.prepend&&null!=n&&(t.prepend=n),null==t.replace&&null!=r&&(t.replace=r)}inheritFromPrevious(t){const e=t.previous;e&&(null==t.separator&&(t.separator=e.separator),null==t.prepend&&(t.prepend=e.prepend))}push(t){const e=this._findTokenById(t.id);if(e){const n=this.tokens.indexOf(e),r=[...this.tokens],i=e.previous;return t.previous=i,t.next=e.next,this.inheritFromPrevious(t),this.applyTokenDefaults(t),r.splice(n,1,t),void(this.tokens=r)}const n=this.tokens.slice(-1)[0];n&&(t.previous=n??null,n.next=t,this.inheritFromPrevious(t)),this.applyTokenDefaults(t),this.tokens=[...this.tokens,t]}remove(t){const e=this._findTokenById(t);if(!e)return;const{next:n,previous:r}=e;n&&(n.previous=r),r&&(r.next=n),e.previous=e.next=null;const i=[...this.tokens];i.splice(i.indexOf(e),1),this.tokens=i}get visibleTokens(){const t=this.tokens;let e=t?t.length:0;const n=[];for(;e--;){const r=t[e];if(r){if(r.replace){n.unshift(r);break}n.unshift(r)}}return n}get sortedTokens(){const t=this.visibleTokens;if(!t)return[];let e=!0,n=[];const r=[n],i=[];return t.forEach(t=>{t.front?i.unshift(t):t.prepend?(e&&(e=!1,n=[],r.push(n)),n.unshift(t)):(e||(e=!0,n=[],r.push(n)),n.push(t))}),i.concat(r.reduce((t,e)=>t.concat(e),[]))}toString(){const t=this.sortedTokens,e=[];for(let n=0,r=t.length;ne.id===t)}updateFastbootTitle(t){if(!vB)return;const e=this.document.head,n=e.childNodes;for(let s=0;snew MB(t),LB);const IB=Object.freeze(Object.defineProperty({__proto__:null,default:LB},Symbol.toStringTag,{value:"Module"})),PB=Gr,AB=uv;function OB(t){return"object"==typeof t&&t&&"isTruthy"in t&&"boolean"==typeof t.isTruthy?t.isTruthy:Jh(t)?0!==t.length:!!t}class FB extends Mw{compute(t){for(let e=0,n=t.length;e[zw],isStrictMode:!0}),this)}}class NB extends LB{static{dF(this.prototype,"title",[Is],function(){return""})}#xt=void fF(this,"title");static{dF(this.prototype,"description",[Is],function(){return""})}#Ct=void fF(this,"description");constructor(){super(...arguments),this.title=this.args.place?.title||"",this.description=this.args.place?.description||""}get shouldAutofocus(){return"undefined"!=typeof window&&window.innerWidth>768}handleSubmit(t){t.preventDefault(),this.args.onSave&&this.args.onSave({title:this.title,description:this.description})}static{pF(this.prototype,"handleSubmit",[Pu])}updateTitle(t){this.title=t.target.value}static{pF(this.prototype,"updateTitle",[Pu])}updateDescription(t){this.description=t.target.value}static{pF(this.prototype,"updateDescription",[Pu])}static{Xr(em({id:null,block:'[[[11,"form"],[24,0,"edit-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-title"],[12],[1,"Title"],[13],[1,"\\n"],[1," "],[11,"input"],[24,1,"edit-title"],[16,2,[30,0,["title"]]],[24,0,"form-control"],[24,"placeholder","Name of the place"],[16,"autofocus",[30,0,["shouldAutofocus"]]],[24,4,"text"],[4,[32,0],["input",[30,0,["updateTitle"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-desc"],[12],[1,"Description"],[13],[1,"\\n "],[11,"textarea"],[24,1,"edit-desc"],[16,2,[30,0,["description"]]],[24,0,"form-control"],[24,"rows","3"],[24,"placeholder","Add some details..."],[4,[32,0],["input",[30,0,["updateDescription"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"edit-actions"],[12],[1,"\\n "],[10,"button"],[14,0,"btn btn-blue"],[14,4,"submit"],[12],[1,"Save"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"Cancel"],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onCancel"],[]]',moduleName:"/home/basti/src/marco/app/components/place-edit-form.gjs",scope:()=>[Sb],isStrictMode:!0}),this)}}class jB{capabilities=Vr();constructor(t){this.owner=t}createModifier(t,e){return{instance:new t(this.owner,e),element:null}}installModifier(t,e,n){const r=function(t,e){const n=t;return n.element=e,n}(t,e);r.instance.modify(e,n.positional,n.named)}updateModifier(t,e){t.instance.modify(t.element,e.positional,e.named)}destroyModifier({instance:t}){Gt(t)}}PB(t=>new jB(t),class{constructor(t,e){ux(this,t)}modify(t,e,n){}});const BB=new class{capabilities=Vr();createModifier(t){return{element:null,instance:t}}installModifier(t,e,n){const r=function(t,e){const n=t;return n.element=e,n}(t,e),{positional:i,named:s}=n,o=t.instance(e,i,s);"function"==typeof o&&(r.teardown=o)}updateModifier(t,e){"function"==typeof t.teardown&&t.teardown();const n=t.instance(t.element,e.positional,e.named);"function"==typeof n&&(t.teardown=n)}destroyModifier(t){"function"==typeof t.teardown&&t.teardown()}getDebugName(t){return t.instance.toString()}getDebugInstance(t){return t}};function UB(t){return t.toString=()=>t.name,PB(()=>BB,t)}const $B=UB((t,[e])=>{const n=n=>{t&&!t.contains(n.target)&&e(n)},r=setTimeout(()=>{document.addEventListener("click",n)},0);return()=>{clearTimeout(r),document.removeEventListener("click",n)}});class qB extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"_forceClear",[Is],function(){return!1})}#Et=void fF(this,"_forceClear");get isSaved(){return this.args.isSaved}get placeListIds(){return this._forceClear?[]:this.args.place._listIds||[]}styleFor(t){return zw(`background-color: ${t}`)}isInList(t){return!!this.placeListIds&&this.placeListIds.includes(t.id)}static{pF(this.prototype,"isInList",[Pu])}async toggleSaved(){if(this.isSaved){const{osmId:t,osmType:e}=this.args.place;if(await this.storage.removePlace(this.args.place),this.args.place&&(this.args.place.id=null,this.args.place.createdAt=null,this.args.place._listIds=[],this._forceClear=!0),t&&e){const t={...this.args.place};delete t.id,delete t.createdAt,delete t._listIds,this.router.transitionTo("place",t)}else this.router.transitionTo("index");this.args.onClose&&this.args.onClose()}else await this.storage.storePlace(this.args.place)}static{pF(this.prototype,"toggleSaved",[Pu])}async toggleList(t){const e=!this.placeListIds.includes(t.id);e&&!this.isSaved&&await this.storage.storePlace(this.args.place);try{await this.storage.togglePlaceList(this.args.place,t.id,e)}catch(ej){console.error(ej),alert("Failed to update list: "+ej.message)}}static{pF(this.prototype,"toggleList",[Pu])}static{Xr(em({id:null,block:'[[[11,0],[24,0,"place-lists-manager"],[4,[32,0],[[30,1]],null],[12],[1,"\\n "],[10,0],[14,0,"list-item master-toggle"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[30,0,["isSaved"]]],[24,4,"checkbox"],[4,[32,1],["change",[30,0,["toggleSaved"]]],null],[12],[13],[1,"\\n "],[10,1],[14,0,"list-color"],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,"Saved places"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"divider"],[12],[13],[1,"\\n\\n "],[10,0],[14,0,"lists-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["storage","lists"]]],null]],null],null,[[[1," "],[10,0],[14,0,"list-item"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[28,[30,0,["isInList"]],[[30,2]],null]],[16,"disabled",[52,[51,[30,0,["isSaved"]]],true]],[24,4,"checkbox"],[4,[32,1],["change",[28,[32,2],[[30,0,["toggleList"]],[30,2]],null]],null],[12],[13],[1,"\\n"],[1," "],[10,1],[14,0,"list-color"],[15,5,[28,[30,0,["styleFor"]],[[30,2,["color"]]],null]],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,[30,2,["title"]]],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n"],[13]],["@onClose","list"],["each","-track-array","unless"]]',moduleName:"/home/basti/src/marco/app/components/place-lists-manager.gjs",scope:()=>[$B,Sb,AB],isStrictMode:!0}),this)}}class VB{assert(){}async(t){Promise.resolve().then(t)}reportUncaughtRejection(){this.async(t=>{throw t})}defer(){let t={promise:null,resolve:null,reject:null},e=new Promise((e,n)=>{t.resolve=e,t.reject=n});return t.promise=e,t}globalDebuggingEnabled(){return!1}}const WB=new VB;class HB{constructor(t){this.maxConcurrency=t||1}}const GB="CANCELLED",KB="STARTED",ZB="QUEUED",YB={type:KB},XB={type:ZB},JB=t=>({type:GB,reason:t}),QB=JB("it belongs to a 'drop' Task that was already running");class tU{constructor(t){this.remainingSlots=t}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):QB}}class eU extends HB{makeReducer(){return new tU(this.maxConcurrency)}}class nU{constructor(t){this.remainingSlots=t}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):XB}}class rU extends HB{makeReducer(){return new nU(this.maxConcurrency)}}const iU=JB("it belongs to a 'keepLatest' Task that was already running");class sU{constructor(t,e){this.remainingSlots=t,this.numToCancel=e}step(){return this.remainingSlots>0?(this.remainingSlots--,YB):this.numToCancel>0?(this.numToCancel--,iU):XB}}class oU extends HB{makeReducer(t,e){let n=t+e;return new sU(this.maxConcurrency,n-this.maxConcurrency-1)}}const aU=JB("it belongs to a 'restartable' Task that was .perform()ed again");class lU{constructor(t){this.numToCancel=t}step(){return this.numToCancel>0?(this.numToCancel--,aU):YB}}class cU extends HB{makeReducer(t,e){return new lU(t+e-this.maxConcurrency)}}const uU=new class{step(){return YB}};class hU{makeReducer(){return uU}}const dU=new Map;class pU{constructor(t,e,n){this.stateTracker=e,this.schedulerPolicy=t,this.initialTaskInstances=n,this.startingInstances=[]}process(){let[t,e,n]=this.filterFinishedTaskInstances(),r=this.schedulerPolicy.makeReducer(e,n),i=t.filter(t=>this.setTaskInstanceExecutionState(t,r.step()));return this.stateTracker.computeFinalStates(t=>this.applyState(t)),this.startingInstances.forEach(t=>t.start()),i}filterFinishedTaskInstances(){let t=0,e=0;return[this.initialTaskInstances.filter(n=>{let r=this.stateTracker.stateFor(n.task),i=n.executor.state;return i.isFinished?(r.onCompletion(n),!1):(i.hasStarted?t+=1:e+=1,!0)}),t,e]}setTaskInstanceExecutionState(t,e){let n=this.stateTracker.stateFor(t.task);switch(t.executor.counted||(t.executor.counted=!0,n.onPerformed(t)),e.type){case GB:return t.cancel(e.reason),!1;case KB:return t.executor.state.hasStarted||(this.startingInstances.push(t),n.onStart(t)),n.onRunning(t),!0;case ZB:return n.onQueued(t),!0}}applyState(t){let{taskable:e}=t;if(!e.onState)return;const{guid:n}=e;if(dU.has(n)&&t.tagt(e))}forEachState(t){this.states.forEach(e=>t(e))}}const yU=new class{onCompletion(){}onPerformed(){}onStart(){}onRunning(){}onQueued(){}};class vU{stateFor(){return yU}computeFinalStates(){}}class bU{constructor(t,e){this.schedulerPolicy=t,this.stateTrackingEnabled=e,this.taskInstances=[]}cancelAll(t,e){let n=this.taskInstances.map(n=>{n.task.guids[t]&&n.executor.cancel(e)}).filter(t=>!!t);return Promise.all(n)}perform(t){t.onFinalize(()=>this.scheduleRefresh()),this.taskInstances.push(t),this.refresh()}scheduleRefresh(){Promise.resolve().then(()=>this.refresh())}refresh(){let t=this.stateTrackingEnabled?new mU:new vU,e=new pU(this.schedulerPolicy,t,this.taskInstances);this.taskInstances=e.process()}}class wU{constructor(t,e,n){this.value=t,this.done=e,this.errored=n}}class _U{constructor(t){this.done=!1,this.generatorFactory=t,this.iterator=null}step(t,e){try{let n=this.getIterator(),{value:r,done:i}=n[e](t);return i?this.finalize(r,!1):new wU(r,!1,!1)}catch(ej){return this.finalize(ej,!0)}}getIterator(){return this.iterator||this.done||(this.iterator=this.generatorFactory()),this.iterator}finalize(t,e){return this.done=!0,this.iterator=null,new wU(t,!0,e)}}const xU="__ec_cancel__",CU="__ec_yieldable__",SU="next",kU="throw",EU="return",TU="cancel";class RU{constructor(t,e){this._taskInstance=t,this._resumeIndex=e}getTaskInstance(){return this._taskInstance}cancel(){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,TU)}next(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,SU,t)}return(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,EU,t)}throw(t){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,kU,t)}}class MU{constructor(){this[CU]=this[CU].bind(this)}onYield(){}_deferable(){let t={resolve:void 0,reject:void 0};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}_toPromise(){let t=this._deferable(),e={proceed(e,n,r){n==SU||n==EU?t.resolve(r):t.reject(r)}},n=this[CU](e,0);return t.promise[xU]=n,t.promise}then(...t){return this._toPromise().then(...t)}catch(...t){return this._toPromise().catch(...t)}finally(...t){return this._toPromise().finally(...t)}[CU](t,e){let n=new RU(t,e);return this.onYield(n)}}new class extends MU{onYield(){}};const LU={completionState:0,value:null,error:null,isSuccessful:!1,isError:!1,isCanceled:!1,hasStarted:!1,isFinished:!1},IU="TaskCancelation",PU="explicit",AU="lifespan_end";class OU{constructor(t,e){this.kind=t,this.reason=e,this.promise=new Promise(t=>{this.finalize=t})}}const FU="PERFORM_TYPE_DEFAULT",zU="PERFORM_TYPE_UNLINKED",DU="PERFORM_TYPE_LINKED",NU={};let jU=[];class BU{constructor({generatorFactory:t,env:e,debug:n}){this.generatorState=new _U(t),this.state=Object.assign({},LU),this.index=1,this.disposers=[],this.finalizeCallbacks=[],this.env=e,this.debug=n,this.cancelRequest=null}start(){this.state.hasStarted||this.cancelRequest||(this.setState({hasStarted:!0}),this.proceedSync(SU,void 0))}cancel(t){return this.requestCancel(t)?(this.state.hasStarted?this.proceedWithCancelAsync():this.finalizeWithCancel(),this.cancelRequest.promise):(t.finalize(),t.promise)}setState(t){Object.assign(this.state,t),this.taskInstance.setState(this.state)}proceedChecked(t,e,n){this.state.isFinished||this.advanceIndex(t)&&(e===TU?(this.requestCancel(new OU("yielded"),n),this.proceedWithCancelAsync()):this.proceedAsync(e,n))}proceedWithCancelAsync(){this.proceedAsync(EU,NU)}proceedAsync(t,e){this.advanceIndex(this.index),this.env.async(()=>this.proceedSync(t,e))}proceedSync(t,e){this.state.isFinished||(this.dispose(),this.generatorState.done?this.handleResolvedReturnedValue(t,e):this.handleResolvedContinueValue(t,e))}handleResolvedContinueValue(t,e){let n=this.index,r=this.generatorStep(e,t);this.advanceIndex(n)&&(r.errored?this.finalize(r.value,2):this.handleYieldedValue(r))}handleResolvedReturnedValue(t,e){switch(t){case SU:case EU:this.finalize(e,1);break;case kU:this.finalize(e,2)}}handleYieldedUnknownThenable(t){let e=this.index;t.then(t=>{this.proceedChecked(e,SU,t)},t=>{this.proceedChecked(e,kU,t)})}advanceIndex(t){if(this.index===t)return++this.index}handleYieldedValue(t){let e=t.value;e?(this.addDisposer(e[xU]),e[CU]?this.invokeYieldable(e):"function"==typeof e.then?this.handleYieldedUnknownThenable(e):this.proceedWithSimpleValue(e)):this.proceedWithSimpleValue(e)}proceedWithSimpleValue(t){this.proceedAsync(SU,t)}addDisposer(t){"function"==typeof t&&this.disposers.push(t)}dispose(){let t=this.disposers;0!==t.length&&(this.disposers=[],t.forEach(t=>t()))}generatorStep(t,e){jU.push(this);let n=this.generatorState.step(t,e);if(jU.pop(),this._expectsLinkedYield){let t=n.value;t&&t.performType===DU||console.warn("You performed a .linked() task without immediately yielding/returning it. This is currently unsupported (but might be supported in future version of ember-concurrency)."),this._expectsLinkedYield=!1}return n}maybeResolveDefer(){this.defer&&this.state.isFinished&&(1===this.state.completionState?this.defer.resolve(this.state.value):this.defer.reject(this.state.error))}onFinalize(t){this.finalizeCallbacks.push(t),this.state.isFinished&&this.runFinalizeCallbacks()}runFinalizeCallbacks(){this.finalizeCallbacks.forEach(t=>t()),this.finalizeCallbacks=[],this.maybeResolveDefer(),this.maybeThrowUnhandledTaskErrorLater()}promise(){return this.defer||(this.defer=this.env.defer(),this.asyncErrorsHandled=!0,this.maybeResolveDefer()),this.defer.promise}maybeThrowUnhandledTaskErrorLater(){this.asyncErrorsHandled||2!==this.state.completionState||function(t){return t&&t.name===IU}(this.state.error)||this.env.async(()=>{this.asyncErrorsHandled||this.env.reportUncaughtRejection(this.state.error)})}requestCancel(t){return!this.cancelRequest&&!this.state.isFinished&&(this.cancelRequest=t,!0)}finalize(t,e){if(this.cancelRequest)return this.finalizeWithCancel();let n={completionState:e};1===e?(n.isSuccessful=!0,n.value=t):2===e?(n.isError=!0,n.error=t):3===e&&(n.error=t),this.finalizeShared(n)}finalizeWithCancel(){let t=this.taskInstance.formatCancelReason(this.cancelRequest.reason),e=new Error(t);this.debugEnabled()&&console.log(t),e.name=IU,this.finalizeShared({isCanceled:!0,completionState:3,error:e,cancelReason:t}),this.cancelRequest.finalize()}debugEnabled(){return this.debug||this.env.globalDebuggingEnabled()}finalizeShared(t){this.index++,t.isFinished=!0,this.setState(t),this.runFinalizeCallbacks()}invokeYieldable(t){try{let e=t[CU](this.taskInstance,this.index);this.addDisposer(e)}catch(ej){this.env.reportUncaughtRejection(ej)}}onYielded(t,e){this.asyncErrorsHandled=!0,this.onFinalize(()=>{let n=this.state.completionState;1===n?t.proceed(e,SU,this.state.value):2===n?t.proceed(e,kU,this.state.error):3===n&&t.proceed(e,TU,null)});let n=this.getPerformType();if(n!==zU)return()=>{this.detectSelfCancelLoop(n,t),this.cancel(new OU("parent_cancel"))}}getPerformType(){return this.taskInstance.performType||FU}detectSelfCancelLoop(t,e){if(t!==FU)return;let n=e.executor&&e.executor.cancelRequest;!n||n.kind!==AU||this.cancelRequest||this.state.isFinished||this.taskInstance.selfCancelLoopWarning(e)}}const UU={last:null,lastRunning:null,lastPerformed:null,lastSuccessful:null,lastComplete:null,lastErrored:null,lastCanceled:null,lastIncomplete:null,performCount:0};Object.freeze(UU);let $U=0;class qU{constructor(t){this.context=t.context,this.debug=t.debug||!1,this.enabledModifiers=t.enabledModifiers,this.env=t.env,this.group=t.group,this.hasEnabledEvents=t.hasEnabledEvents,this.modifierOptions=t.modifierOptions,this.name=t.name,this.onStateCallback=t.onStateCallback,this.scheduler=t.scheduler,this.guid="ec_"+$U++,this.guids={},this.guids[this.guid]=!0,this.group&&Object.assign(this.guids,this.group.guids)}cancelAll(t){let{reason:e,cancelRequestKind:n,resetState:r}=t||{};e=e||".cancelAll() was explicitly called on the Task";let i=new OU(n||PU,e);return this.scheduler.cancelAll(this.guid,i).then(()=>{r&&this._resetState()})}get _isAlive(){return!0}_resetState(){this.setState(UU)}setState(){}}Object.assign(qU.prototype,UU),Object.assign(qU.prototype,{numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"});class VU{constructor(t,e,n){this.task=t,this.performType=e,this.linkedObject=n}perform(...t){return this.task._performShared(t,this.performType,this.linkedObject)}}let WU=class t extends qU{constructor(t){super(t),this.generatorFactory=t.generatorFactory,this.perform=this._perform.bind(this)}linked(){let t=jU[jU.length-1];if(!t)throw new Error("You can only call .linked() from within a task.");return new VU(this,DU,t)}unlinked(){return new VU(this,zU,null)}toString(){return``}_clone(){return new t({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}_curry(...t){let e=this._clone();return e._curryArgs=[...this._curryArgs||[],...t],e}_perform(...t){return this._performShared(t,FU,null)}_performShared(t,e,n){let r=this._curryArgs?[...this._curryArgs,...t]:t,i=this._taskInstanceFactory(r,e,n);return e===DU&&(n._expectsLinkedYield=!0),this._isAlive||i.cancel(),this.scheduler.perform(i),i}_taskInstanceOptions(t,e,n){return{args:t,executor:new BU({generatorFactory:()=>this.generatorFactory(t),env:this.env,debug:this.debug}),performType:e,hasEnabledEvents:this.hasEnabledEvents}}};const HU={enqueue:(t,e)=>e&&t.setBufferPolicy(rU),debug:(t,e)=>e&&t.setDebug(e),drop:(t,e)=>e&&t.setBufferPolicy(eU),keepLatest:(t,e)=>e&&t.setBufferPolicy(oU),maxConcurrency:(t,e)=>t.setMaxConcurrency(e),onState:(t,e)=>t.setOnState(e),restartable:(t,e)=>e&&t.setBufferPolicy(cU)};let GU=class{env=WB;_debug=null;_enabledModifiers=[];_hasSetConcurrencyConstraint=!1;_hasSetBufferPolicy=!1;_hasEnabledEvents=!1;_maxConcurrency=null;_onStateCallback=(t,e)=>e.setState(t);_schedulerPolicyClass=hU;constructor(t="",e=null,n={}){this.name=t,this.taskDefinition=e,this.options=n,this._processModifierOptions(n)}createTask(t){let e=this.getTaskOptions(t);return new WU(Object.assign({generatorFactory:e=>this.taskDefinition.apply(t,e)},e))}getModifier(t){if(function(t){return t in HU}(t))return HU[t].bind(null,this)}getOptions(){return this.options}getScheduler(t,e){return new bU(t,e)}getTaskOptions(t){let e,n=this._onStateCallback,r=new this._schedulerPolicyClass(this._maxConcurrency);return e=this.getScheduler(r,n&&"function"==typeof n),{context:t,debug:this._debug,env:this.env,name:this.name,group:void 0,scheduler:e,hasEnabledEvents:this._hasEnabledEvents,onStateCallback:n,enabledModifiers:this._enabledModifiers,modifierOptions:this.getOptions()}}setBufferPolicy(t){return function(t){if(t._hasSetBufferPolicy)throw new Error(`Cannot set multiple buffer policies on a task. ${t._schedulerPolicyClass} has already been set for task '${t.name}'`)}(this),this._hasSetBufferPolicy=!0,this._hasSetConcurrencyConstraint=!0,this._schedulerPolicyClass=t,this}setDebug(t){return this._debug=t,this}setEvented(t){return this._hasEnabledEvents=t,this}setMaxConcurrency(t){return this._hasSetConcurrencyConstraint=!0,this._maxConcurrency=t,this}setName(t){return this.name=t,this}setOnState(t){return this._onStateCallback=t,this}setTaskDefinition(t){return this.taskDefinition=t,this}_processModifierOptions(t){if(t)for(let e of Object.keys(t)){let n=t[e],r=this.getModifier(e);"function"==typeof r&&r(n)&&this._enabledModifiers.push(e)}}};const KU=new class extends VB{assert(...t){}async(t){va(()=>wa("actions",t))}reportUncaughtRejection(t){Sa(null,function(){const e=ko();if(!e)throw t;e(t)})}defer(){return $c()}globalDebuggingEnabled(){return!1}};class ZU extends bU{scheduleRefresh(){xa(this,this.refresh)}}class YU{constructor({task:t,args:e,executor:n,performType:r,hasEnabledEvents:i}){this.task=t,this.args=e,this.performType=r,this.executor=n,this.executor.taskInstance=this,this.hasEnabledEvents=i}setState(){}formatCancelReason(){}selfCancelLoopWarning(){}onFinalize(t){this.executor.onFinalize(t)}proceed(t,e,n){this.executor.proceedChecked(t,e,n)}[CU](t,e){return this.executor.onYielded(t,e)}cancel(t=".cancel() was explicitly called"){this.executor.cancel(new OU(PU,t))}then(...t){return this.executor.promise().then(...t)}catch(...t){return this.executor.promise().catch(...t)}finally(...t){return this.executor.promise().finally(...t)}toString(){return`${this.task} TaskInstance`}start(){return this.executor.start(),this}}function XU(t,e){return Object.keys(t).reduce((e,n)=>function(t,e,n){const r=Object.getOwnPropertyDescriptor(t,n);r.initializer=r.initializer||(()=>t[n]),delete r.value;const i=Is(e,n,r);return e[n]=i,e}(t,e,n),e)}let JU,QU;Object.assign(YU.prototype,LU),Object.assign(YU.prototype,{state:"waiting",isDropped:!1,isRunning:!0}),JU=XU(UU,{}),JU=XU({numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"},JU),QU=XU(LU,{}),QU=XU({state:"waiting",isDropped:!1,isRunning:!1},QU),Object.freeze(JU),Object.freeze(QU);class t$ extends YU{setState(t){let e=this._recomputeState(t);Object.assign(this,{...t,isRunning:!t.isFinished,isDropped:"dropped"===e,state:e})}_recomputeState(t){return t.isDropped?"dropped":t.isCanceled?t.hasStarted?"canceled":"dropped":t.isFinished?"finished":t.hasStarted?"running":"waiting"}formatCancelReason(t){return`TaskInstance '${this.getName()}' was canceled because ${t}. For more information, see: http://ember-concurrency.com/docs/task-cancelation-help`}getName(){return this.name||(this.name=this.task&&this.task.name||""),this.name}selfCancelLoopWarning(t){let e=`\`${t.getName()}\``,n=`\`${this.getName()}\``;console.warn(`ember-concurrency detected a potentially hazardous "self-cancel loop" between parent task ${e} and child task ${n}. If you want child task ${n} to be canceled when parent task ${e} is canceled, please change \`.perform()\` to \`.linked().perform()\`. If you want child task ${n} to keep running after parent task ${e} is canceled, change it to \`.unlinked().perform()\``)}triggerEvent(...t){if(!this.hasEnabledEvents)return;let e=this.task,n=e.context,r=e&&e.name;if(n&&n.trigger&&r){let[e,...i]=t;n.trigger(`${r}:${e}`,...i)}}}QU&&Object.defineProperties(t$.prototype,QU);const e$={_performCount:0,setState(t){this._performCount=this._performCount+(t.numPerformedInc||0);let e=t.numRunning>0,n=t.numQueued>0,r=Object.assign({},t,{performCount:this._performCount,isRunning:e,isQueued:n,isIdle:!e&&!n,state:e?"running":"idle"});Object.assign(this,r)},onState(t,e){e.onStateCallback&&e.onStateCallback(t,e)}};class n$ extends WU{constructor(t){super(t),Zt(this.context)||_x(this.context,()=>{this.cancelAll({reason:"the object it lives on was destroyed or unrendered",cancelRequestKind:AU})})}get _isAlive(){return!Zt(this.context)}_taskInstanceFactory(t,e,n){let r=this._taskInstanceOptions(t,e,n);return r.task=this,new t$(r)}_clone(){return new n$({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}}JU&&Object.defineProperties(n$.prototype,JU),Object.assign(n$.prototype,e$);class r$ extends GU{env=KU;createTask(t){this.taskDefinition;let e=this.getTaskOptions(t);return new n$(Object.assign({generatorFactory:e=>this.taskDefinition.apply(t,e)},e))}getModifier(t){return super.getModifier(t)}getScheduler(t,e){return new ZU(t,e)}get taskFn(){return this.taskDefinition}set taskFn(t){this.setTaskDefinition(t)}}function i$(t,e,n){let r=e;const i=t();return new r$(n||"",i.generator,r).createTask(i.context)}class s$ extends LB{renderBlurhash=UB((t,[e,n,r])=>{if(!e||!t)return;const i=n||32,s=r||18;t.width=i,t.height=s;const o=t.getContext("2d");if(o)try{const t=((t,e,n)=>{(t=>{if(!t||t.length<6)throw new sB("The blurhash string must be at least 6 characters");let e=tB(t[0]),n=Math.floor(e/9)+1,r=e%9+1;if(t.length!==4+2*r*n)throw new sB(`blurhash length mismatch: length is ${t.length} but it should be ${4+2*r*n}`)})(t);let r=tB(t[0]),i=Math.floor(r/9)+1,s=r%9+1,o=(tB(t[1])+1)/166,a=new Array(s*i);for(let u=0;u({context:this,generator:function*(t){this.error="";try{const e=yield this.imageProcessor.process(t,1920,.94,!0);this.blurhash=e.blurhash;const n=yield this.imageProcessor.process(t,350,.9,!1);let r,i;if(bz())r=yield this.blossom.upload(e.blob,{sequential:!0}),i=yield this.blossom.upload(n.blob,{sequential:!0});else{const t=this.blossom.upload(e.blob),s=this.blossom.upload(n.blob);[r,i]=yield Promise.all([t,s])}this.args.onSuccess&&this.args.onSuccess({file:t,url:r.url,fallbackUrls:r.fallbackUrls,thumbUrl:i.url,blurhash:e.blurhash,type:"image/jpeg",dim:e.dim,hash:r.hash,thumbHash:i.hash})}catch(ej){this.error=ej.message}}}),null,"uploadTask");static{Xr(em({id:null,block:'[[[10,0],[15,0,[29,["photo-upload-item\\n ",[52,[30,0,["uploadTask","isRunning"]],"is-uploading"],"\\n ",[52,[30,0,["error"]],"has-error"]]]],[12],[1,"\\n"],[41,[30,0,["blurhash"]],[[[1," "],[8,[32,0],[[24,0,"place-header-photo-blur"]],[["@hash"],[[30,0,["blurhash"]]]],null],[1,"\\n"]],[]],null],[1," "],[10,"img"],[15,"src",[30,0,["thumbnailUrl"]]],[14,"alt","thumbnail"],[12],[13],[1,"\\n\\n"],[41,[30,0,["uploadTask","isRunning"]],[[[1," "],[10,0],[14,0,"overlay"],[12],[1,"\\n "],[8,[32,1],[[24,0,"spin-animation"]],[["@name","@size","@color"],["loading-ring",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["error"]],[[[1," "],[11,"button"],[24,0,"overlay error-overlay"],[16,"title",[30,0,["error"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["showErrorToast"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["alert-circle",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[11,"button"],[24,0,"btn-remove-photo"],[24,"title","Remove photo"],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,1],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",16,"white"]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onRemove","@file"],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload-item.gjs",scope:()=>[s$,DB,Sb,AB],isStrictMode:!0}),this)}}class a$ extends Mw{compute(t){for(let e=0,n=t.length;e!OB(t))}class c$ extends LB{static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrRelay",[$f])}#W=void fF(this,"nostrRelay");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"blossom",[$f])}#Tt=void fF(this,"blossom");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");static{dF(this.prototype,"file",[Is],function(){return null})}#At=void fF(this,"file");static{dF(this.prototype,"uploadedPhoto",[Is],function(){return null})}#Ot=void fF(this,"uploadedPhoto");static{dF(this.prototype,"status",[Is],function(){return""})}#Ft=void fF(this,"status");static{dF(this.prototype,"error",[Is],function(){return""})}#Pt=void fF(this,"error");static{dF(this.prototype,"isPublishing",[Is],function(){return!1})}#zt=void fF(this,"isPublishing");static{dF(this.prototype,"isDragging",[Is],function(){return!1})}#Dt=void fF(this,"isDragging");get place(){return this.args.place||{}}get title(){return this.place.title||"this place"}get allUploaded(){return this.file&&this.uploadedPhoto&&this.file===this.uploadedPhoto.file}handleFileSelect(t){this.addFile(t.target.files[0]),t.target.value=""}static{pF(this.prototype,"handleFileSelect",[Pu])}handleDragOver(t){t.preventDefault(),this.isDragging=!0}static{pF(this.prototype,"handleDragOver",[Pu])}handleDragLeave(t){t.preventDefault(),this.isDragging=!1}static{pF(this.prototype,"handleDragLeave",[Pu])}handleDrop(t){t.preventDefault(),this.isDragging=!1,t.dataTransfer.files.length>0&&this.addFile(t.dataTransfer.files[0])}static{pF(this.prototype,"handleDrop",[Pu])}addFile(t){t&&t.type.startsWith("image/")?(this.error="",this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=t,this.uploadedPhoto=null):this.error="Please select a valid image file."}handleUploadSuccess(t){this.uploadedPhoto=t}static{pF(this.prototype,"handleUploadSuccess",[Pu])}removeFile(){this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=null,this.uploadedPhoto=null}static{pF(this.prototype,"removeFile",[Pu])}deletePhotoTask=i$(()=>({context:this,generator:function*(t){try{t.hash&&(yield this.blossom.delete(t.hash)),t.thumbHash&&(yield this.blossom.delete(t.thumbHash))}catch(ej){this.toast.show(`Failed to delete photo from server: ${ej.message}`,5e3)}}}),null,"deletePhotoTask");async publish(){if(!this.nostrAuth.isConnected)return void(this.error="You must connect Nostr first.");if(!this.allUploaded)return void(this.error="Please wait for all photos to finish uploading.");const{osmId:t,lat:e,lon:n}=this.place,r=this.place.osmType||"node";if(t){this.status="Publishing event...",this.error="",this.isPublishing=!0;try{const i=new kO({signer:this.nostrAuth.signer}),s=[["i",`osm:${r}:${t}`]];e&&n&&(s.push(["g",DD.encode(e,n,4)]),s.push(["g",DD.encode(e,n,6)]),s.push(["g",DD.encode(e,n,7)]),s.push(["g",DD.encode(e,n,9)]));const o=this.uploadedPhoto,a=["imeta",`url ${o.url}`];if(a.push(`m ${o.type}`),o.dim&&a.push(`dim ${o.dim}`),a.push("alt A photo of a place"),o.fallbackUrls&&o.fallbackUrls.length>0)for(const t of o.fallbackUrls)a.push(`fallback ${t}`);o.thumbUrl&&a.push(`thumb ${o.thumbUrl}`),o.blurhash&&a.push(`blurhash ${o.blurhash}`),s.push(a);const l={kind:360,content:"",tags:s};l.created_at||(l.created_at=Math.floor(Date.now()/1e3));const c=await i.sign(l);await this.nostrRelay.publish(this.nostrData.activeWriteRelays,c),this.nostrData.store.add(c),this.toast.show("Photo published successfully"),this.status="",this.file=null,this.uploadedPhoto=null,this.args.onClose&&this.args.onClose(c.id)}catch(ej){this.error="Failed to publish: "+ej.message,this.status=""}finally{this.isPublishing=!1}}else this.error="This place does not have a valid OSM ID."}static{pF(this.prototype,"publish",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"place-photo-upload"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Add Photo for "],[1,[30,0,["title"]]],[13],[1,"\\n\\n"],[41,[30,0,["error"]],[[[1," "],[10,0],[14,0,"alert alert-error"],[12],[1,"\\n "],[1,[30,0,["error"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["status"]],[[[1," "],[10,0],[14,0,"alert alert-info"],[12],[1,"\\n "],[1,[30,0,["status"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["file"]],[[[1," "],[10,0],[14,0,"photo-grid"],[12],[1,"\\n "],[8,[32,0],null,[["@file","@onSuccess","@onRemove"],[[30,0,["file"]],[30,0,["handleUploadSuccess"]],[30,0,["removeFile"]]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"button"],[24,0,"btn btn-primary btn-publish"],[16,"disabled",[28,[32,1],[[28,[32,2],[[30,0,["allUploaded"]]],null],[30,0,["isPublishing"]]],null]],[24,4,"button"],[4,[32,3],["click",[30,0,["publish"]]],null],[12],[1,"\\n"],[41,[30,0,["isPublishing"]],[[[1," Publishing...\\n"]],[]],[[[1," Publish Photo\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],[[[1," "],[11,0],[16,0,[29,["dropzone ",[52,[30,0,["isDragging"]],"is-dragging"]]]],[4,[32,3],["dragover",[30,0,["handleDragOver"]]],null],[4,[32,3],["dragleave",[30,0,["handleDragLeave"]]],null],[4,[32,3],["drop",[30,0,["handleDrop"]]],null],[12],[1,"\\n "],[10,"label"],[14,"for","photo-upload-input"],[14,0,"dropzone-label"],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size","@color"],["upload-cloud",48,"#ccc"]],null],[1,"\\n "],[10,2],[12],[1,"Drag and drop a photo here, or click to browse"],[13],[1,"\\n "],[13],[1,"\\n "],[11,"input"],[24,1,"photo-upload-input"],[24,"accept","image/*"],[24,0,"file-input-hidden"],[16,"disabled",[30,0,["isPublishing"]]],[24,4,"file"],[4,[32,3],["change",[30,0,["handleFileSelect"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload.gjs",scope:()=>[o$,FB,l$,Sb,DB],isStrictMode:!0}),this)}}var u$,h$,d$={};function p$(){return h$?u$:(h$=1,u$=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then})}var f$,g$={},m$={};function y$(){if(f$)return m$;let t;f$=1;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return m$.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17},m$.getSymbolTotalCodewords=function(t){return e[t]},m$.getBCHDigit=function(t){let e=0;for(;0!==t;)e++,t>>>=1;return e},m$.setToSJISFunction=function(e){if("function"!=typeof e)throw new Error('"toSJISFunc" is not a valid function.');t=e},m$.isKanjiModeEnabled=function(){return void 0!==t},m$.toSJIS=function(e){return t(e)},m$}var v$,b$,w$,_$,x$,C$={};function S$(){return v$||(v$=1,(t=C$).L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2},t.isValid=function(t){return t&&void 0!==t.bit&&t.bit>=0&&t.bit<4},t.from=function(e,n){if(t.isValid(e))return e;try{return function(e){if("string"!=typeof e)throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+e)}}(e)}catch(ej){return n}}),C$;var t}var k$,E$,T$,R$,M$={},L$={},I$={},P$={};function A$(){if(R$)return P$;R$=1;const t=S$(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return P$.getBlocksCount=function(n,r){switch(r){case t.L:return e[4*(n-1)+0];case t.M:return e[4*(n-1)+1];case t.Q:return e[4*(n-1)+2];case t.H:return e[4*(n-1)+3];default:return}},P$.getTotalCodewordsCount=function(e,r){switch(r){case t.L:return n[4*(e-1)+0];case t.M:return n[4*(e-1)+1];case t.Q:return n[4*(e-1)+2];case t.H:return n[4*(e-1)+3];default:return}},P$}var O$,F$,z$,D$,N$,j$={},B$={},U$={},$$={},q$={};function V$(){return N$||(N$=1,q$.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),q$}var W$,H$,G$,K$={};function Z$(){if(W$)return K$;W$=1;const t="[0-9]+";let e="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";e=e.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+e+")(?:.|[\r\n]))+";K$.KANJI=new RegExp(e,"g"),K$.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),K$.BYTE=new RegExp(n,"g"),K$.NUMERIC=new RegExp(t,"g"),K$.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const r=new RegExp("^"+e+"$"),i=new RegExp("^"+t+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return K$.testKanji=function(t){return r.test(t)},K$.testNumeric=function(t){return i.test(t)},K$.testAlphanumeric=function(t){return s.test(t)},K$}function Y$(){return H$||(H$=1,function(t){const e=V$(),n=Z$();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(t,n){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!e.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?t.ccBits[0]:n<27?t.ccBits[1]:t.ccBits[2]},t.getBestModeForData=function(e){return n.testNumeric(e)?t.NUMERIC:n.testAlphanumeric(e)?t.ALPHANUMERIC:n.testKanji(e)?t.KANJI:t.BYTE},t.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")},t.isValid=function(t){return t&&t.bit&&t.ccBits},t.from=function(e,n){if(t.isValid(e))return e;try{return function(e){if("string"!=typeof e)throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+e)}}(e)}catch(ej){return n}}}($$)),$$}var X$,J$,Q$,tq,eq,nq,rq,iq,sq,oq,aq,lq,cq={},uq={},hq={exports:{}};function dq(){return oq||(oq=1,function(t){var e={single_source_shortest_paths:function(t,n,r){var i={},s={};s[n]=0;var o,a,l,c,u,h,d,p=e.PriorityQueue.make();for(p.push(n,0);!p.empty();)for(l in a=(o=p.pop()).value,c=o.cost,u=t[a]||{})u.hasOwnProperty(l)&&(h=c+u[l],d=s[l],(void 0===s[l]||d>h)&&(s[l]=h,p.push(l,h),i[l]=a));if(void 0!==r&&void 0===s[r]){var f=["Could not find a path from ",n," to ",r,"."].join("");throw new Error(f)}return i},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e;r;)n.push(r),t[r],r=t[r];return n.reverse(),n},find_path:function(t,n,r){var i=e.single_source_shortest_paths(t,n,r);return e.extract_shortest_path_from_predecessor_list(i,r)},PriorityQueue:{make:function(t){var n,r=e.PriorityQueue,i={};for(n in t=t||{},r)r.hasOwnProperty(n)&&(i[n]=r[n]);return i.queue=[],i.sorter=t.sorter||r.default_sorter,i},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};t.exports=e}(hq)),hq.exports}function pq(){if(lq)return g$;lq=1;const t=y$(),e=S$(),n=function(){if(w$)return b$;function t(){this.buffer=[],this.length=0}return w$=1,t.prototype={get:function(t){const e=Math.floor(t/8);return 1==(this.buffer[e]>>>7-t%8&1)},put:function(t,e){for(let n=0;n>>e-n-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}},b$=t}(),r=function(){if(x$)return _$;function t(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return x$=1,t.prototype.set=function(t,e,n,r){const i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)},t.prototype.get=function(t,e){return this.data[t*this.size+e]},t.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n},t.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]},_$=t}(),i=(k$||(k$=1,function(t){const e=y$().getSymbolSize;t.getRowColCoords=function(t){if(1===t)return[];const n=Math.floor(t/7)+2,r=e(t),i=145===r?26:2*Math.ceil((r-13)/(2*n-2)),s=[r-7];for(let e=1;e=0&&t<=7},t.from=function(e){return t.isValid(e)?parseInt(e,10):void 0},t.getPenaltyN1=function(t){const e=t.size;let n=0,r=0,i=0,s=null,o=null;for(let a=0;a=5&&(n+=r-5+3),s=e,r=1),e=t.get(l,a),e===o?i++:(i>=5&&(n+=i-5+3),o=e,i=1)}r>=5&&(n+=r-5+3),i>=5&&(n+=i-5+3)}return n},t.getPenaltyN2=function(t){const e=t.size;let n=0;for(let r=0;r=10&&(1488===r||93===r)&&n++,i=i<<1&2047|t.get(o,s),o>=10&&(1488===i||93===i)&&n++}return 40*n},t.getPenaltyN4=function(t){let e=0;const n=t.data.length;for(let r=0;r=0;){const t=r[0];for(let s=0;s0){const t=new Uint8Array(this.degree);return t.set(r,i),t}return r},z$=e}(),c=(G$||(G$=1,function(t){const e=y$(),n=A$(),r=S$(),i=Y$(),s=V$(),o=e.getBCHDigit(7973);function a(t,e){return i.getCharCountIndicator(t,e)+4}function l(t,e){let n=0;return t.forEach(function(t){const r=a(t.mode,e);n+=r+t.getBitsLength()}),n}t.from=function(t,e){return s.isValid(t)?parseInt(t,10):e},t.getCapacity=function(t,r,o){if(!s.isValid(t))throw new Error("Invalid QR Code version");void 0===o&&(o=i.BYTE);const l=8*(e.getSymbolTotalCodewords(t)-n.getTotalCodewordsCount(t,r));if(o===i.MIXED)return l;const c=l-a(o,t);switch(o){case i.NUMERIC:return Math.floor(c/10*3);case i.ALPHANUMERIC:return Math.floor(c/11*2);case i.KANJI:return Math.floor(c/13);case i.BYTE:default:return Math.floor(c/8)}},t.getBestVersionForData=function(e,n){let s;const o=r.from(n,r.M);if(Array.isArray(e)){if(e.length>1)return function(e,n){for(let r=1;r<=40;r++)if(l(e,r)<=t.getCapacity(r,n,i.MIXED))return r}(e,o);if(0===e.length)return 1;s=e[0]}else s=e;return function(e,n,r){for(let i=1;i<=40;i++)if(n<=t.getCapacity(i,r,e))return i}(s.mode,s.getLength(),o)},t.getEncodedBits=function(t){if(!s.isValid(t)||t<7)throw new Error("Invalid QR Code version");let n=t<<12;for(;e.getBCHDigit(n)-o>=0;)n^=7973<=0;)s^=1335<0&&(n=this.data.substr(e),r=parseInt(n,10),t.put(r,3*i+1))},J$=e}(),r=function(){if(eq)return tq;eq=1;const t=Y$(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(e){this.mode=t.ALPHANUMERIC,this.data=e}return n.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=45*e.indexOf(this.data[n]);r+=e.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(e.indexOf(this.data[n]),6)},tq=n}(),i=function(){if(rq)return nq;rq=1;const t=Y$();function e(e){this.mode=t.BYTE,this.data="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e)}return e.getBitsLength=function(t){return 8*t},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(t){for(let e=0,n=this.data.length;e=33088&&r<=40956)r-=33088;else{if(!(r>=57408&&r<=60351))throw new Error("Invalid SJIS character: "+this.data[n]+"\nMake sure your charset is UTF-8");r-=49472}r=192*(r>>>8&255)+(255&r),t.put(r,13)}},iq=n}(),o=Z$(),a=y$(),l=dq();function c(t){return unescape(encodeURIComponent(t)).length}function u(t,e,n){const r=[];let i;for(;null!==(i=t.exec(n));)r.push({data:i[0],index:i.index,mode:e,length:i[0].length});return r}function h(t){const n=u(o.NUMERIC,e.NUMERIC,t),r=u(o.ALPHANUMERIC,e.ALPHANUMERIC,t);let i,s;return a.isKanjiModeEnabled()?(i=u(o.BYTE,e.BYTE,t),s=u(o.KANJI,e.KANJI,t)):(i=u(o.BYTE_KANJI,e.BYTE,t),s=[]),n.concat(r,i,s).sort(function(t,e){return t.index-e.index}).map(function(t){return{data:t.data,mode:t.mode,length:t.length}})}function d(t,o){switch(o){case e.NUMERIC:return n.getBitsLength(t);case e.ALPHANUMERIC:return r.getBitsLength(t);case e.KANJI:return s.getBitsLength(t);case e.BYTE:return i.getBitsLength(t)}}function p(t,o){let l;const c=e.getBestModeForData(t);if(l=e.from(o,c),l!==e.BYTE&&l.bit=0?t[t.length-1]:null;return n&&n.mode===e.mode?(t[t.length-1].data+=e.data,t):(t.push(e),t)},[]))},t.rawSplit=function(e){return t.fromArray(h(e,a.isKanjiModeEnabled()))}}(uq)),uq);function p(t,e,n){const r=t.size,i=u.getEncodedBits(e,n);let s,o;for(s=0;s<15;s++)o=1==(i>>s&1),s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(r-15+s,8,o,!0),s<8?t.set(8,r-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(r-8,8,1,!0)}return g$.create=function(u,f){if(void 0===u||""===u)throw new Error("No input text");let g,m,y=e.M;return void 0!==f&&(y=e.from(f.errorCorrectionLevel,e.M),g=c.from(f.version),m=o.from(f.maskPattern),f.toSJISFunc&&t.setToSJISFunction(f.toSJISFunc)),function(e,u,f,g){let m;if(Array.isArray(e))m=d.fromArray(e);else{if("string"!=typeof e)throw new Error("Invalid data");{let t=u;if(!t){const n=d.rawSplit(e);t=c.getBestVersionForData(n,f)}m=d.fromString(e,t||40)}}const y=c.getBestVersionForData(m,f);if(!y)throw new Error("The amount of data is too big to be stored in a QR Code");if(u){if(u=0&&r<=6&&(0===i||6===i)||i>=0&&i<=6&&(0===r||6===r)||r>=2&&r<=4&&i>=2&&i<=4?t.set(e+r,s+i,!0,!0):t.set(e+r,s+i,!1,!0))}}(w,u),function(t){const e=t.size;for(let n=8;n=7&&function(t,e){const n=t.size,r=c.getEncodedBits(e);let i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+n-8-3,o=1==(r>>a&1),t.set(i,s,o,!0),t.set(s,i,o,!0)}(w,u),function(t,e){const n=t.size;let r=-1,i=n-1,s=7,o=0;for(let a=n-1;a>0;a-=2)for(6===a&&a--;;){for(let n=0;n<2;n++)if(!t.isReserved(i,a-n)){let r=!1;o>>s&1)),t.set(i,a-n,r),s--,-1===s&&(o++,s=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}(w,v),isNaN(g)&&(g=o.getBestMask(w,p.bind(null,w,f))),o.applyMask(g,w),p(w,f,g),{modules:w,version:u,errorCorrectionLevel:f,maskPattern:g,segments:m}}(u,g,y,m)},g$}var fq,gq,mq={},yq={};function vq(){return fq||(fq=1,function(t){function e(t){if("number"==typeof t&&(t=t.toString()),"string"!=typeof t)throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||5===e.length||e.length>8)throw new Error("Invalid hex color: "+t);3!==e.length&&4!==e.length||(e=Array.prototype.concat.apply([],e.map(function(t){return[t,t]}))),6===e.length&&e.push("F","F");const n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:255&n,hex:"#"+e.slice(0,6).join("")}}t.getOptions=function(t){t||(t={}),t.color||(t.color={});const n=void 0===t.margin||null===t.margin||t.margin<0?4:t.margin,r=t.width&&t.width>=21?t.width:void 0,i=t.scale||4;return{width:r,scale:r?4:i,margin:n,color:{dark:e(t.color.dark||"#000000ff"),light:e(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}},t.getScale=function(t,e){return e.width&&e.width>=t+2*e.margin?e.width/(t+2*e.margin):e.scale},t.getImageWidth=function(e,n){const r=t.getScale(e,n);return Math.floor((e+2*n.margin)*r)},t.qrToImageData=function(e,n,r){const i=n.modules.size,s=n.modules.data,o=t.getScale(i,r),a=Math.floor((i+2*r.margin)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let t=0;t=l&&n>=l&&t':"",h="0&&c>0&&t[l-1]||(i+=o?n("M",c+r,.5+u+r):n("m",s,0),s=0,o=!1),c+1',d='viewBox="0 0 '+c+" "+c+'"',p=''+u+h+"\n";return"function"==typeof s&&s(null,p),p},_q}();function i(n,r,i,s,o){const a=[].slice.call(arguments,1),l=a.length,c="function"==typeof a[l-1];if(!c&&!t())throw new Error("Callback required as last argument");if(!c){if(l<1)throw new Error("Too few arguments provided");return 1===l?(i=r,r=s=void 0):2!==l||r.getContext||(s=i,i=r,r=void 0),new Promise(function(t,o){try{const o=e.create(i,s);t(n(o,r,s))}catch(ej){o(ej)}})}if(l<2)throw new Error("Too few arguments provided");2===l?(o=i,i=r,r=s=void 0):3===l&&(r.getContext&&void 0===o?(o=s,s=void 0):(o=s,s=i,i=r,r=void 0));try{const t=e.create(i,s);o(null,n(t,r,s))}catch(ej){o(ej)}}return d$.create=e.create,d$.toCanvas=i.bind(null,n.render),d$.toDataURL=i.bind(null,n.renderToDataURL),d$.toString=i.bind(null,function(t,e,n){return r.render(t,n)}),d$}();const Cq=BA(xq),Sq=UB((t,[e])=>{e&&Cq.toCanvas(t,e,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).catch(t=>{console.error("Failed to generate QR code",t)})});class kq extends LB{static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");get hasExtension(){return"undefined"!=typeof window&&void 0!==window.nostr}async connectExtension(){try{await this.nostrAuth.connectWithExtension(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(ej){console.error(ej),alert(ej.message)}}static{pF(this.prototype,"connectExtension",[Pu])}async connectApp(){try{await this.nostrAuth.connectWithApp(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(ej){console.error(ej),alert(ej.message)}}static{pF(this.prototype,"connectApp",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"nostr-connect-modal"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Connect with Nostr"],[13],[1,"\\n\\n "],[10,0],[14,0,"nostr-connect-options"],[12],[1,"\\n"],[41,[30,0,["hasExtension"]],[[[1," "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectExtension"]]],null],[12],[1,"\\n Browser Extension (nos2x, Alby)\\n "],[13],[1,"\\n"]],[]],[[[1," "],[10,"button"],[14,0,"btn btn-outline"],[14,"disabled",""],[14,"title","No Nostr extension found in your browser."],[14,4,"button"],[12],[1,"\\n Browser Extension (Not Found)\\n "],[13],[1,"\\n"]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectApp"]]],null],[12],[1,"\\n Mobile Signer App (Amber, etc.)\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[28,[32,1],[[30,0,["nostrAuth","connectStatus"]],"waiting"],null],[[[1," "],[10,0],[14,0,"nostr-connect-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isMobile"]],[[[1," "],[10,2],[12],[1,"Waiting for you to approve the connection in your mobile signer\\n app..."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[12],[1,"Scan this QR code with a compatible Nostr signer app (like\\n Amber):"],[13],[1,"\\n "],[10,0],[14,0,"qr-code-container"],[12],[1,"\\n "],[11,"canvas"],[4,[32,2],[[30,0,["nostrAuth","connectUri"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],null],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/nostr-connect.gjs",scope:()=>[Sb,zB,Sq],isStrictMode:!0}),this)}}class Eq extends LB{stopProp(t){t.stopPropagation()}static{pF(this.prototype,"stopProp",[Pu])}close(){this.args.onClose&&this.args.onClose()}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[11,0],[24,0,"modal-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[11,0],[24,0,"modal-content"],[24,"role","document"],[24,"tabindex","0"],[4,[32,0],["click",[30,0,["stopProp"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"close-modal-btn btn-text"],[24,4,"button"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["x",24]],null],[1,"\\n "],[13],[1,"\\n "],[18,1,null],[1,"\\n "],[13],[1,"\\n"],[13]],["&default"],["yield"]]',moduleName:"/home/basti/src/marco/app/components/modal.gjs",scope:()=>[Sb,DB],isStrictMode:!0}),this)}}const Tq=UB((t,[e])=>{if(!e)return;let n;t.classList.remove("loaded"),t.classList.remove("loaded-instant");const r=()=>{t.classList.contains("loaded-instant")||t.classList.add("loaded")};return t.addEventListener("load",r),n=new IntersectionObserver((n,r)=>{n.forEach(n=>{if(n.isIntersecting){r.unobserve(t);const n=new Image;n.src=e,n.complete&&t.classList.add("loaded-instant");const i=t.parentElement;i&&"PICTURE"===i.tagName&&i.querySelectorAll("source").forEach(t=>{t.dataset.srcset&&(t.srcset=t.dataset.srcset)}),t.dataset.src?t.src=t.dataset.src:t.src=e}})},{root:null,rootMargin:"100px 100%",threshold:0}),n.observe(t),()=>{t.removeEventListener("load",r),n&&n.disconnect()}});class Rq extends LB{static{dF(this.prototype,"canScrollLeft",[Is],function(){return!1})}#Nt=void fF(this,"canScrollLeft");static{dF(this.prototype,"canScrollRight",[Is],function(){return!1})}#jt=void fF(this,"canScrollRight");carouselElement=null;get photos(){return this.args.photos||[]}get showChevrons(){return this.photos.length>1}get cannotScrollLeft(){return!this.canScrollLeft}get cannotScrollRight(){return!this.canScrollRight}lastResetKey=null;resetScrollPosition=UB((t,[e])=>{void 0!==e&&e!==this.lastResetKey&&(this.lastResetKey=e,t.scrollLeft=0,setTimeout(()=>this.updateScrollState(),50))});scrollToNewPhoto=UB((t,[e])=>{e&&e!==this.lastEventId&&(this.lastEventId=e,setTimeout(()=>{const n=t.querySelector(`[data-event-id="${e}"]`);n&&(t.scrollLeft=n.offsetLeft)},100))});setupCarousel=UB(t=>{let e;return this.carouselElement=t,setTimeout(()=>{this.updateScrollState()},50),window.ResizeObserver&&(e=new ResizeObserver(()=>this.updateScrollState()),e.observe(t)),()=>{e&&e.unobserve(t)}});updateScrollState(){if(!this.carouselElement)return;const{scrollLeft:t,scrollWidth:e,clientWidth:n}=this.carouselElement;this.canScrollLeft=t>1,this.canScrollRight=t+n[Sb,s$,Tq,DB],isStrictMode:!0}),this)}}class Mq extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isEditing",[Is],function(){return!1})}#Bt=void fF(this,"isEditing");static{dF(this.prototype,"showLists",[Is],function(){return!1})}#Ut=void fF(this,"showLists");static{dF(this.prototype,"isPhotoUploadModalOpen",[Is],function(){return!1})}#$t=void fF(this,"isPhotoUploadModalOpen");static{dF(this.prototype,"isNostrConnectModalOpen",[Is],function(){return!1})}#qt=void fF(this,"isNostrConnectModalOpen");static{dF(this.prototype,"newlyUploadedPhotoId",[Is],function(){return null})}#Vt=void fF(this,"newlyUploadedPhotoId");openPhotoUploadModal(t){t&&t.preventDefault(),this.nostrAuth.isConnected?this.isPhotoUploadModalOpen=!0:this.isNostrConnectModalOpen=!0}static{pF(this.prototype,"openPhotoUploadModal",[Pu])}closePhotoUploadModal(t){this.isPhotoUploadModalOpen=!1,"string"==typeof t&&(this.newlyUploadedPhotoId=t,setTimeout(()=>{const t=document.querySelector(".sidebar-content");t&&(t.scrollTop=0)},50))}static{pF(this.prototype,"closePhotoUploadModal",[Pu])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{pF(this.prototype,"closeNostrConnectModal",[Pu])}onNostrConnected(){this.isNostrConnectModalOpen=!1,this.isPhotoUploadModalOpen=!0}static{pF(this.prototype,"onNostrConnected",[Pu])}get isSaved(){return this.storage.isPlaceSaved(this.place.id||this.place.osmId)}get place(){return this.args.place||{}}get saveablePlace(){return this.place.createdAt?this.place:Zj(this.place)}get tags(){return this.place.osmTags||{}}get name(){return this.place.title||RN(this.tags)||"Unnamed Place"}get photos(){return OD(this.nostrData.placePhotos).map(t=>({...t,style:zw(`--slide-ratio: ${t.aspectRatio};`)}))}startEditing(){this.isSaved&&(this.isEditing=!0)}static{pF(this.prototype,"startEditing",[Pu])}cancelEditing(){this.isEditing=!1}static{pF(this.prototype,"cancelEditing",[Pu])}toggleLists(t){t&&t.stopPropagation(),this.showLists=!this.showLists}static{pF(this.prototype,"toggleLists",[Pu])}closeLists(){this.showLists=!1}static{pF(this.prototype,"closeLists",[Pu])}async saveChanges(t){this.args.onSave&&await this.args.onSave({...this.place,...t}),this.isEditing=!1}static{pF(this.prototype,"saveChanges",[Pu])}get type(){return LN(this.tags)}get address(){const t=this.tags,e=[],n=(...e)=>{for(const n of e)if(t[n])return t[n];return null};let r=n("addr:street","street");const i=n("addr:housenumber","housenumber");r&&(i&&(r=`${r} ${i}`),e.push(r));let s=n("addr:city","city");const o=n("addr:postcode","postcode");s&&(o&&(s=`${o} ${s}`),e.push(s));const a=n("addr:state","state"),l=n("addr:country","country");return a&&a!==s&&e.push(a),l&&e.push(l),0===e.length?null:e.join(", ")}formatMultiLine(t,e){if(!t)return null;const n=[...new Set(t.split(";").map(t=>t.trim()).filter(Boolean))];return 0===n.length?null:zw("phone"===e?n.map(t=>`${t}`).join("
"):"email"===e?n.map(t=>`${t}`).join("
"):"whatsapp"===e?n.map(t=>`${t}`).join("
"):"url"===e?n.map(t=>`${this.getDomain(t)}`).join("
"):n.join("
"))}get phone(){const t=[this.tags.phone,this.tags["contact:phone"],this.tags.mobile,this.tags["contact:mobile"]].filter(Boolean);return 0===t.length?null:this.formatMultiLine(t.join(";"),"phone")}get whatsapp(){const t=[this.tags.whatsapp,this.tags["contact:whatsapp"]].filter(Boolean);return 0===t.length?null:this.formatMultiLine(t.join(";"),"whatsapp")}get email(){const t=this.tags.email||this.tags["contact:email"];return this.formatMultiLine(t,"email")}get website(){const t=this.place.url||this.tags.website||this.tags["contact:website"];return this.formatMultiLine(t,"url")}getDomain(t){try{return new URL(t).hostname}catch{return t}}get openingHours(){const t=this.tags.opening_hours;return this.formatMultiLine(t)}get cuisine(){return this.tags.cuisine?this.tags.cuisine.split(";").map(t=>EN(t)).join(", "):null}get facebook(){return Xj(this.tags,"facebook")}get instagram(){return Xj(this.tags,"instagram")}get wikipedia(){const t=this.tags.wikipedia;return t?t.split(";").map(t=>t.trim()).filter(Boolean)[0]:null}get geoLink(){const t=this.place.lat,e=this.place.lon;return t&&e?`geo:${t},${e}?q=${t},${e}(${encodeURIComponent(this.name)})`:"#"}get visibleGeoLink(){const t=this.place.lat,e=this.place.lon;return t&&e?`${Number(t).toFixed(6)}, ${Number(e).toFixed(6)}`:""}get osmUrl(){const t=this.place.osmId;return t?`https://www.openstreetmap.org/${this.place.osmType||"node"}/${t}`:null}get gmapsUrl(){return this.place.gmapsId||this.place.osmId?`https://www.google.com/maps/search/?api=1&query=${this.name}&query=${this.place.lat},${this.place.lon}`:null}get showDescription(){return"photon"!==this.place.source&&!!this.place.description}static{Xr(em({id:null,block:'[[[10,0],[14,0,"place-details"],[12],[1,"\\n"],[41,[30,0,["isEditing"]],[[[1," "],[8,[32,0],null,[["@place","@onSave","@onCancel"],[[30,0,["place"]],[30,0,["saveChanges"]],[30,0,["cancelEditing"]]]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@photos","@name","@resetKey","@scrollToEventId"],[[30,0,["photos"]],[30,0,["name"]],[30,0,["place","osmId"]],[30,0,["newlyUploadedPhotoId"]]]],null],[1,"\\n "],[10,"h3"],[12],[1,[30,0,["name"]]],[13],[1,"\\n "],[10,2],[14,0,"place-type"],[12],[1,"\\n "],[1,[30,0,["type"]]],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["showDescription"]],[[[1," "],[10,2],[14,0,"place-description"],[12],[1,"\\n "],[1,[30,0,["place","description"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[]]],[1,"\\n "],[10,0],[14,0,"actions"],[12],[1,"\\n "],[10,0],[14,0,"save-button-wrapper"],[12],[1,"\\n "],[11,"button"],[16,0,[52,[30,0,["isSaved"]],"btn btn-secondary","btn btn-outline"]],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleLists"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["bookmark",[52,[30,0,["isSaved"]],"currentColor","var(--link-color)"]]],null],[1,"\\n "],[1,[52,[30,0,["isSaved"]],"Saved","Save"]],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["showLists"]],[[[1," "],[8,[32,4],null,[["@place","@onClose","@isSaved"],[[30,0,["saveablePlace"]],[30,0,["closeLists"]],[30,0,["isSaved"]]]],null],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isSaved"]],[[[1," "],[11,"button"],[24,0,"btn btn-outline"],[24,"title","Edit"],[16,"disabled",[30,0,["isEditing"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["startEditing"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["edit","var(--link-color)"]],null],[1,"\\n Edit\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["cuisine"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["fork-and-knife","Cuisine"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["cuisine"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["openingHours"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["clock","Opening hours"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["openingHours"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["phone"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["phone","Phone"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["phone"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["whatsapp"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["whatsapp","WhatsApp"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["whatsapp"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["website"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["globe","Website"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["website"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["email"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["mail","Email"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["email"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["facebook"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["facebook","Facebook"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["facebook","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["facebook","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["instagram"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["instagram","Instagram"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["instagram","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["instagram","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["wikipedia"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["wikipedia","Wikipedia"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[29,["https://wikipedia.org/wiki/",[30,0,["wikipedia"]]]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Wikipedia\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["address"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["home","Address"]],null],[1,"\\n "],[10,1],[12],[1,[30,0,["address"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["map-pin","Geo link"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["geoLink"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["visibleGeoLink"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["osmUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n OpenStreetMap\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["gmapsUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["gmapsUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Google Maps\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,0],[14,0,"meta-info"],[12],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["camera"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[11,"button"],[24,0,"btn-link"],[24,4,"button"],[4,[32,2],["click",[30,0,["openPhotoUploadModal"]]],null],[12],[1,"\\n Add a photo\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13],[1,"\\n\\n"],[41,[30,0,["isPhotoUploadModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closePhotoUploadModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,6],null,[["@place","@onClose"],[[30,0,["saveablePlace"]],[30,0,["closePhotoUploadModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,7],null,[["@onConnect"],[[30,0,["onNostrConnected"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-details.gjs",scope:()=>[NB,Rq,Sb,DB,qB,Eq,c$,kq],isStrictMode:!0}),this)}}const Lq=Ow(function([t]){return EN(t)});class Iq extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");createNewPlace(){const t=this.router.currentRoute.queryParams,e=t.lat,n=t.lon;e&&n?this.router.transitionTo("place.new",{queryParams:{lat:e,lon:n}}):this.router.transitionTo("place.new",{queryParams:{lat:0,lon:0}})}static{pF(this.prototype,"createNewPlace",[Pu])}selectPlace(t){this.args.onSelect&&this.args.onSelect(t)}static{pF(this.prototype,"selectPlace",[Pu])}clearSelection(){this.args.onSelect&&this.args.onSelect(null)}static{pF(this.prototype,"clearSelection",[Pu])}async toggleSave(t){if(t)if(t.createdAt)try{if(await this.storage.removePlace(t),console.debug("Place deleted:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate){const e={...t,id:void 0,geohash:void 0,createdAt:void 0};this.args.onUpdate(e)}this.args.onSelect&&this.args.onSelect(null),this.args.onClose&&this.args.onClose()}catch(ej){console.error("Failed to delete:",ej),alert("Failed to delete: "+ej.message)}else{const e={title:RN(t.osmTags,"Untitled Place"),lat:t.lat,lon:t.lon,tags:[],url:t.osmTags.website,osmId:String(t.osmId||t.id),osmType:t.osmType,osmTags:t.osmTags};try{const t=await this.storage.storePlace(e);console.debug("Place saved:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(t),this.args.onSelect&&this.args.onSelect(t)}catch(v5){console.error("Failed to save place:",v5),alert("Failed to save place: "+v5.message)}}}static{pF(this.prototype,"toggleSave",[Pu])}async updateBookmark(t){try{const e=await this.storage.updatePlace(t);console.debug("Place updated:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(e)}catch(ej){console.error("Failed to update place:",ej),alert("Failed to update place: "+ej.message)}}static{pF(this.prototype,"updateBookmark",[Pu])}get isNearbySearch(){const t=this.router.currentRoute.queryParams;return!t.q&&!t.category&&t.lat&&t.lon}get hasHeaderPhoto(){return this.args.selectedPlace&&this.nostrData.placePhotos&&this.nostrData.placePhotos.length>0}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[15,0,[29,["sidebar-header ",[52,[30,0,["hasHeaderPhoto"]],"no-border"]]]],[12],[1,"\\n"],[41,[30,1],[[[1," "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,0,["clearSelection"]]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["target",20,"#ea4335"]],null],[1,"\\n Nearby"],[13],[1,"\\n"]],[]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#333"]],null],[1," Results"],[13],[1,"\\n"]],[]]]],[]]],[1," "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n"],[41,[30,1],[[[1," "],[8,[32,2],null,[["@place","@onToggleSave","@onSave"],[[30,1],[30,0,["toggleSave"]],[30,0,["updateBookmark"]]]],null],[1,"\\n"]],[]],[[[41,[30,3],[[[1," "],[10,"ul"],[14,0,"places-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,3]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"place-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,3],[[30,0,["selectPlace"]],[30,4]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"place-name"],[12],[1,[28,[32,4],[[30,4,["title"]],[30,4,["osmTags","name"]],[30,4,["osmTags","name:en"]],"Unnamed Place"],null]],[13],[1,"\\n "],[10,0],[14,0,"place-type"],[12],[1,"\\n"],[41,[28,[32,5],[[30,4,["source"]],"osm"],null],[[[1," "],[1,[28,[32,6],[[30,4,["type"]]],null]],[1,"\\n"]],[]],[[[41,[28,[32,5],[[30,4,["source"]],"photon"],null],[[[1," "],[1,[30,4,["description"]]],[1,"\\n"]],[]],[[[41,[30,4,["osmTags"]],[[[1," "],[1,[28,[32,6],[[28,[32,7],[[30,4,["osmTags"]]],null]],null]],[1,"\\n"]],[]],[[[41,[30,4,["description"]],[[[1," "],[1,[30,4,["description"]]],[1,"\\n "]],[]],null]],[]]],[1," "]],[]]]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[4]],null],[1," "],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No places found nearby."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No results found."],[13],[1,"\\n"]],[]]]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline create-place"],[24,4,"button"],[4,[32,0],["click",[30,0,["createNewPlace"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["plus",18,"var(--link-color)"]],null],[1,"\\n Create new place\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"],[13]],["@selectedPlace","@onClose","@places","place"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/places-sidebar.gjs",scope:()=>[Sb,DB,Mq,AB,FB,zB,Lq,LN],isStrictMode:!0}),this)}}class Pq extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");selectPlace(t){t&&(this.mapUi.returnToSearch=!0,this.router.transitionTo("place",t))}static{pF(this.prototype,"selectPlace",[Pu])}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[8,[32,0],null,[["@places","@onSelect","@onClose"],[[30,1],[30,0,["selectPlace"]],[30,0,["close"]]]],null]],["@model"],[]]',moduleName:"/home/basti/src/marco/app/templates/search.gjs",scope:()=>[Iq],isStrictMode:!0}),this)}}const Aq=Object.freeze(Object.defineProperty({__proto__:null,default:Pq},Symbol.toStringTag,{value:"Module"})),Oq=Object.freeze(Object.defineProperty({__proto__:null,default:class extends cd{queryParams=["lat","lon","q","selected","category"];lat=null;lon=null;q=null;selected=null;category=null}},Symbol.toStringTag,{value:"Module"}));class Fq extends kp{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"photon",[$f])}#Ht=void fF(this,"photon");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0},q:{refreshModel:!0},selected:{refreshModel:!0},category:{refreshModel:!0}};async model(t){const e=t.lat?parseFloat(t.lat):null,n=t.lon?parseFloat(t.lon):null;let r=[],i=null,s=null;try{if(t.category&&e&&n){i="category",s=t.category,this.mapUi.startLoading(i,s);let o=this.mapUi.currentBounds;if(!o){const t=.01;o={minLat:e-t,maxLat:e+t,minLon:n-t,maxLon:n+t}}r=await this.osm.getCategoryPois(o,t.category,e,n),r=r.map(t=>({...t,_distance:jj(e,n,t.lat,t.lon)})).sort((t,e)=>t._distance-e._distance)}else if(t.q){i="text",s=t.q,this.mapUi.startLoading(i,s),r=await this.photon.search(t.q,e,n);const o=t.q.toLowerCase(),a=this.storage.savedPlaces.filter(t=>t.title?.toLowerCase().includes(o)||t.description?.toLowerCase().includes(o));a.forEach(t=>{r.find(e=>t.osmId&&e.osmId===t.osmId||e.id&&e.id===t.id)||r.push(t)})}else if(e&&n){const t=50;r=await this.osm.getNearbyPois(e,n,t);const i=this.storage.savedPlaces.filter(r=>jj(e,n,r.lat,r.lon)<=t);i.forEach(t=>{r.find(e=>t.osmId&&e.osmId===t.osmId||e.id&&e.id===t.id)||r.push(t)}),r=r.map(t=>({...t,_distance:jj(e,n,t.lat,t.lon)})).sort((t,e)=>t._distance-e._distance)}}finally{i&&s&&this.mapUi.stopLoading(i,s)}return r=r.map(t=>this.storage.findPlaceById(t.osmId)||t),r}afterModel(t,e){const{q:n,selected:r}=e.to.queryParams,i=r||n;if(i&&t.length>0){let e=null;if(e=t.find(t=>t.osmTags&&(t.osmTags.name===i||t.osmTags["name:en"]===i)),!e){const n=t[0];n._distance<=10&&(e=n)}if(e)return void this.router.replaceWith("place",e)}this.mapUi.stopSearch()}setupController(t,e){super.setupController(t,e),this.mapUi.stopSearch(),this.mapUi.setSearchResults(e);const{q:n,category:r,lat:i,lon:s}=this.paramsFor("search");this.mapUi.currentSearch={q:n,category:r,lat:i,lon:s}}error(t,e){return this.mapUi.stopSearch(),this.toast.show("Search request failed. Please try again."),e&&e.abort(),!1}static{pF(this.prototype,"error",[Pu])}}const zq=Object.freeze(Object.defineProperty({__proto__:null,default:Fq},Symbol.toStringTag,{value:"Module"}));var Dq,Nq,jq;let Bq=(Dq=$f("page-title"),Nq=class extends Mw{constructor(t){super(t),hB(this,"tokens",jq,this),uB(this,"tokenId",et(this)),this.tokens.push({id:this.tokenId})}compute(t,e){const n={...e,id:this.tokenId,title:t.join("")};return this.tokens.push(n),this.tokens.scheduleTitleUpdate(),""}willDestroy(){super.willDestroy(),this.tokens.remove(this.tokenId),this.tokens.scheduleTitleUpdate()}},jq=dB(Nq.prototype,"tokens",[Dq],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),Nq);const Uq="add",$q="remove",qq="propertychange",Vq="change",Wq="contextmenu",Hq="click",Gq="keydown",Kq="keypress",Zq="touchmove",Yq="wheel";class Xq{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}}function Jq(t,e){return t>e?1:te?-1:0}function tV(t,e,n){if(t[0]<=e)return 0;const r=t.length;if(e<=t[r-1])return r-1;if("function"==typeof n){for(let i=1;i0?i-1:i}return r-1}if(n>0){for(let n=1;n0)}removeEventListener(t,e){if(!this.listeners_)return;const n=this.listeners_[t];if(!n)return;const r=n.indexOf(e);-1!==r&&(this.pendingRemovals_&&t in this.pendingRemovals_?(n[r]=oV,++this.pendingRemovals_[t]):(n.splice(r,1),0===n.length&&delete this.listeners_[t]))}}function pV(t,e,n,r,i){if(i){const i=n;n=function(s){return t.removeEventListener(e,n),i.call(r??this,s)}}else r&&r!==t&&(n=n.bind(r));const s={target:t,type:e,listener:n};return t.addEventListener(e,n),s}function fV(t,e,n,r){return pV(t,e,n,r,!0)}function gV(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),cV(t))}class mV extends dV{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(Vq)}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const n=t.length,r=new Array(n);for(let i=0;i0;)this.pop()}extend(t){for(let e=0,n=t.length;ethis.getLength())throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e),this.array_.splice(t,0,e),this.updateLength_(),this.dispatchEvent(new CV(Uq,e,t))}pop(){return this.removeAt(this.getLength()-1)}push(t){const e=this.getLength();return this.insertAt(e,t),this.getLength()}remove(t){const e=this.array_;for(let n=0,r=e.length;n=this.getLength())return;const e=this.array_[t];return this.array_.splice(t,1),this.updateLength_(),this.dispatchEvent(new CV($q,e,t)),e}setAt(t,e){if(t>=this.getLength())return void this.insertAt(t,e);if(t<0)throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e,t);const n=this.array_[t];this.array_[t]=e,this.dispatchEvent(new CV($q,n,t)),this.dispatchEvent(new CV(Uq,e,t))}updateLength_(){this.set(xV,this.array_.length)}assertUnique_(t,e){const n=this.array_;for(let r=0,i=n.length;r{this.clickTimeoutId_=void 0;const e=new EV(TV.SINGLECLICK,this.map_,t);this.dispatchEvent(e)},250)}updateActivePointers_(t){const e=t,n=e.pointerId;if(e.type==TV.POINTERUP||e.type==TV.POINTERCANCEL){delete this.trackedTouches_[n];for(const t in this.trackedTouches_)if(this.trackedTouches_[t].target!==e.target){delete this.trackedTouches_[t];break}}else e.type!=TV.POINTERDOWN&&e.type!=TV.POINTERMOVE||(this.trackedTouches_[n]=e);this.activePointers_=Object.values(this.trackedTouches_)}handlePointerUp_(t){this.updateActivePointers_(t);const e=new EV(TV.POINTERUP,this.map_,t,void 0,void 0,this.activePointers_);this.dispatchEvent(e),this.emulateClicks_&&!e.defaultPrevented&&!this.dragging_&&this.isMouseActionButton_(t)&&this.emulateClick_(this.down_),0===this.activePointers_.length&&(this.dragListenerKeys_.forEach(gV),this.dragListenerKeys_.length=0,this.dragging_=!1,this.down_=null)}isMouseActionButton_(t){return 0===t.button}handlePointerDown_(t){this.emulateClicks_=0===this.activePointers_.length,this.updateActivePointers_(t);const e=new EV(TV.POINTERDOWN,this.map_,t,void 0,void 0,this.activePointers_);if(this.dispatchEvent(e),this.down_=new PointerEvent(t.type,t),Object.defineProperty(this.down_,"target",{writable:!1,value:t.target}),0===this.dragListenerKeys_.length){const t=this.map_.getOwnerDocument();this.dragListenerKeys_.push(pV(t,TV.POINTERMOVE,this.handlePointerMove_,this),pV(t,TV.POINTERUP,this.handlePointerUp_,this),pV(this.element_,TV.POINTERCANCEL,this.handlePointerUp_,this)),this.element_.getRootNode&&this.element_.getRootNode()!==t&&this.dragListenerKeys_.push(pV(this.element_.getRootNode(),TV.POINTERUP,this.handlePointerUp_,this))}}handlePointerMove_(t){if(this.isMoving_(t)){this.updateActivePointers_(t),this.dragging_=!0;const e=new EV(TV.POINTERDRAG,this.map_,t,this.dragging_,void 0,this.activePointers_);this.dispatchEvent(e)}}relayMoveEvent_(t){this.originalPointerMoveEvent_=t;const e=!(!this.down_||!this.isMoving_(t));this.dispatchEvent(new EV(TV.POINTERMOVE,this.map_,t,e))}handleTouchMove_(t){const e=this.originalPointerMoveEvent_;e&&!e.defaultPrevented||"boolean"==typeof t.cancelable&&!0!==t.cancelable||t.preventDefault()}isMoving_(t){return this.dragging_||Math.abs(t.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(t.clientY-this.down_.clientY)>this.moveTolerance_}disposeInternal(){this.relayedListenerKey_&&(gV(this.relayedListenerKey_),this.relayedListenerKey_=null),this.element_.removeEventListener(Zq,this.boundHandleTouchMove_),this.pointerdownListenerKey_&&(gV(this.pointerdownListenerKey_),this.pointerdownListenerKey_=null),this.dragListenerKeys_.forEach(gV),this.dragListenerKeys_.length=0,this.element_=null,super.disposeInternal()}}const NV="postrender",jV="loadstart",BV="loadend",UV="layergroup",$V="size",qV="target",VV="view";function WV(t,e){if(!t)throw new Error(e)}const HV=1/0;class GV{constructor(t,e){this.priorityFunction_=t,this.keyFunction_=e,this.elements_=[],this.priorities_=[],this.queuedElements_={}}clear(){this.elements_.length=0,this.priorities_.length=0,cV(this.queuedElements_)}dequeue(){const t=this.elements_,e=this.priorities_,n=t[0];1==t.length?(t.length=0,e.length=0):(t[0]=t.pop(),e[0]=e.pop(),this.siftUp_(0));const r=this.keyFunction_(n);return delete this.queuedElements_[r],n}enqueue(t){WV(!(this.keyFunction_(t)in this.queuedElements_),"Tried to enqueue an `element` that was already added to the queue");const e=this.priorityFunction_(t);return e!=HV&&(this.elements_.push(t),this.priorities_.push(e),this.queuedElements_[this.keyFunction_(t)]=!0,this.siftDown_(0,this.elements_.length-1),!0)}getCount(){return this.elements_.length}getLeftChildIndex_(t){return 2*t+1}getRightChildIndex_(t){return 2*t+2}getParentIndex_(t){return t-1>>1}heapify_(){let t;for(t=(this.elements_.length>>1)-1;t>=0;t--)this.siftUp_(t)}isEmpty(){return 0===this.elements_.length}isKeyQueued(t){return t in this.queuedElements_}isQueued(t){return this.isKeyQueued(this.keyFunction_(t))}siftUp_(t){const e=this.elements_,n=this.priorities_,r=e.length,i=e[t],s=n[t],o=t;for(;t>1;){const i=this.getLeftChildIndex_(t),s=this.getRightChildIndex_(t),o=st;){const t=this.getParentIndex_(e);if(!(r[t]>s))break;n[e]=n[t],r[e]=r[t],e=t}n[e]=i,r[e]=s}reprioritize(){const t=this.priorityFunction_,e=this.elements_,n=this.priorities_;let r=0;const i=e.length;let s,o,a;for(o=0;ot.apply(null,e),t=>t[0].getKey()),this.boundHandleTileChange_=this.handleTileChange.bind(this),this.tileChangeCallback_=e,this.tilesLoading_=0,this.tilesLoadingKeys_={}}enqueue(t){const e=super.enqueue(t);return e&&t[0].addEventListener(Vq,this.boundHandleTileChange_),e}getTilesLoading(){return this.tilesLoading_}handleTileChange(t){const e=t.target,n=e.getState();if(2===n||3===n||4===n){3!==n&&e.removeEventListener(Vq,this.boundHandleTileChange_);const t=e.getKey();t in this.tilesLoadingKeys_&&(delete this.tilesLoadingKeys_[t],--this.tilesLoading_),this.tileChangeCallback_()}}loadMoreTiles(t,e){let n=0;for(;this.tilesLoading_0;){const t=this.dequeue()[0],e=t.getKey();0!==t.getState()||e in this.tilesLoadingKeys_||(this.tilesLoadingKeys_[e]=!0,++this.tilesLoading_,++n,t.load())}}}const ZV={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};function YV(t,e,n){return Math.min(Math.max(t,e),n)}function XV(t,e,n,r,i,s){const o=i-n,a=s-r;if(0!==o||0!==a){const l=((t-n)*o+(e-r)*a)/(o*o+a*a);l>1?(n=i,r=s):l>0&&(n+=o*l,r+=a*l)}return JV(t,e,n,r)}function JV(t,e,n,r){const i=n-t,s=r-e;return i*i+s*s}function QV(t){return 180*t/Math.PI}function tW(t){return t*Math.PI/180}function eW(t,e){const n=t%e;return n*e<0?n+e:n}function nW(t,e,n){return t+n*(e-t)}function rW(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}function iW(t,e){return Math.floor(rW(t,e))}function sW(t,e){return Math.ceil(rW(t,e))}function oW(t,e,n){if(t>=e&&tp&&(d=(p+d)/2,p=d),f>g&&(f=(g+f)/2,g=f);let m=YV(r[0],d,p),y=YV(r[1],f,g);if(o&&n&&i){const t=30*i;m+=-t*Math.log(1+Math.max(0,d-r[0])/t)+t*Math.log(1+Math.max(0,r[0]-p)/t),y+=-t*Math.log(1+Math.max(0,f-r[1])/t)+t*Math.log(1+Math.max(0,r[1]-g)/t)}return[m,y]}}function lW(t){return t}function cW(t){const e=[1/0,1/0,-1/0,-1/0];for(let n=0,r=t.length;ni&&(l|=4),as&&(l|=2),0===l&&(l=1),l}function yW(t,e,n,r,i){return i?(i[0]=t,i[1]=e,i[2]=n,i[3]=r,i):[t,e,n,r]}function vW(t){return yW(1/0,1/0,-1/0,-1/0,t)}function bW(t,e){const n=t[0],r=t[1];return yW(n,r,n,r,e)}function wW(t,e,n,r,i){return SW(vW(i),t,e,n,r)}function _W(t,e){return t[0]==e[0]&&t[2]==e[2]&&t[1]==e[1]&&t[3]==e[3]}function xW(t,e){return e[0]t[2]&&(t[2]=e[2]),e[1]t[3]&&(t[3]=e[3]),t}function CW(t,e){e[0]t[2]&&(t[2]=e[0]),e[1]t[3]&&(t[3]=e[1])}function SW(t,e,n,r,i){for(;ne[0]?r[0]=t[0]:r[0]=e[0],t[1]>e[1]?r[1]=t[1]:r[1]=e[1],t[2]=e[0]&&t[1]<=e[3]&&t[3]>=e[1]}function BW(t){return t[2]1){const e=t[2]-t[0],n=t[3]-t[1];for(let s=0;s=n[2])){const e=NW(n),i=Math.floor((r[0]-n[0])/e)*e;t[0]-=i,t[2]-=i}return t}function qW(t,e,n){if(e.canWrapX()){const r=e.getExtent();if(!isFinite(t[0])||!isFinite(t[2]))return[[r[0],t[1],r[2],t[3]]];$W(t,e);const i=NW(r);if(NW(t)>i&&!n)return[[r[0],t[1],r[2],t[3]]];if(t[0]r[2])return[[t[0],t[1],r[2],t[3]],[r[0],t[1],t[2]-i,t[3]]]}return[t]}function VW(t,e){let n=!0;for(let r=t.length-1;r>=0;--r)if(t[r]!=e[r]){n=!1;break}return n}function WW(t,e){const n=Math.cos(e),r=Math.sin(e),i=t[0]*n-t[1]*r,s=t[1]*n+t[0]*r;return t[0]=i,t[1]=s,t}function HW(t,e){if(e.canWrapX()){const n=NW(e.getExtent()),r=function(t,e,n){const r=e.getExtent();let i=0;return e.canWrapX()&&(t[0]r[2])&&(n=n||NW(r),i=Math.floor((t[0]-r[0])/n)),i}(t,e,n);r&&(t[0]-=r*n)}return t}function GW(t){return Math.pow(t,3)}function KW(t){return 1-GW(1-t)}function ZW(t){return 3*t*t-2*t*t*t}function YW(t){return t}const XW=6371008.8;function JW(t,e,n){n=n||XW;const r=tW(t[1]),i=tW(e[1]),s=(i-r)/2,o=tW(e[0]-t[0])/2,a=Math.sin(s)*Math.sin(s)+Math.sin(o)*Math.sin(o)*Math.cos(r)*Math.cos(i);return 2*n*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function QW(t,e,n,r){r=r||XW;const i=tW(t[1]),s=tW(t[0]),o=e/r,a=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(n));return[QV(s+Math.atan2(Math.sin(n)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(a))),QV(a)]}function tH(...t){console.warn(...t)}const eH={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};class nH{constructor(t){this.code_=t.code,this.units_=t.units,this.extent_=void 0!==t.extent?t.extent:null,this.worldExtent_=void 0!==t.worldExtent?t.worldExtent:null,this.axisOrientation_=void 0!==t.axisOrientation?t.axisOrientation:"enu",this.global_=void 0!==t.global&&t.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=t.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=t.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||eH[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(t){this.global_=t,this.canWrapX_=!(!t||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(t){this.defaultTileGrid_=t}setExtent(t){this.extent_=t,this.canWrapX_=!(!this.global_||!t)}setWorldExtent(t){this.worldExtent_=t}setGetPointResolution(t){this.getPointResolutionFunc_=t}getPointResolutionFunc(){return this.getPointResolutionFunc_}}const rH=6378137,iH=Math.PI*rH,sH=[-iH,-iH,iH,iH],oH=[-180,-85,180,85],aH=rH*Math.log(Math.tan(Math.PI/2));class lH extends nH{constructor(t){super({code:t,units:"m",extent:sH,global:!0,worldExtent:oH,getPointResolution:function(t,e){return t/Math.cosh(e[1]/rH)}})}}const cH=[new lH("EPSG:3857"),new lH("EPSG:102100"),new lH("EPSG:102113"),new lH("EPSG:900913"),new lH("http://www.opengis.net/def/crs/EPSG/0/3857"),new lH("http://www.opengis.net/gml/srs/epsg.xml#3857")],uH=[-180,-90,180,90],hH=6378137*Math.PI/180;class dH extends nH{constructor(t,e){super({code:t,units:"degrees",extent:uH,axisOrientation:e,global:!0,metersPerUnit:hH,worldExtent:uH})}}const pH=[new dH("CRS:84"),new dH("EPSG:4326","neu"),new dH("urn:ogc:def:crs:OGC:1.3:CRS84"),new dH("urn:ogc:def:crs:OGC:2:84"),new dH("http://www.opengis.net/def/crs/OGC/1.3/CRS84"),new dH("http://www.opengis.net/gml/srs/epsg.xml#4326","neu"),new dH("http://www.opengis.net/def/crs/EPSG/0/4326","neu")];let fH={},gH={};function mH(t,e,n){const r=t.getCode(),i=e.getCode();r in gH||(gH[r]={}),gH[r][i]=n}function yH(t,e){return t in gH&&e in gH[t]?gH[t][e]:null}const vH=.9996,bH=.00669438,wH=bH*bH,_H=wH*bH,xH=bH/(1-bH),CH=Math.sqrt(1-bH),SH=(1-CH)/(1+CH),kH=SH*SH,EH=kH*SH,TH=EH*SH,RH=TH*SH,MH=.9983242984503243,LH=15*wH/256+45*_H/1024,IH=35*_H/3072,PH=1.5*SH-27/32*EH+269/512*RH,AH=21/16*kH-55/32*TH,OH=151/96*EH-417/128*RH,FH=1097/512*TH,zH=6378137;function DH(t,e,n){const r=t-5e5,i=(n.north?e:e-1e7)/vH/(zH*MH),s=i+PH*Math.sin(2*i)+AH*Math.sin(4*i)+OH*Math.sin(6*i)+FH*Math.sin(8*i),o=Math.sin(s),a=o*o,l=Math.cos(s),c=o/l,u=c*c,h=u*u,d=1-bH*a,p=Math.sqrt(1-bH*a),f=xH*l**2,g=f*f,m=r/(zH/p*vH),y=m*m,v=y*m,b=v*m,w=b*m,_=s-c/((1-bH)/d)*(y/2-b/24*(5+3*u+10*f-4*g-9*xH))+w*m/720*(61+90*u+298*f+45*h-252*xH-3*g);let x=(m-v/6*(1+2*u+f)+w/120*(5-2*f+28*u-3*g+8*xH+24*h))/l;return x=oW(x+tW(jH(n.number)),-Math.PI,Math.PI),[QV(x),QV(_)]}function NH(t,e,n){t=oW(t,-180,180),e<-80?e=-80:e>84&&(e=84);const r=tW(e),i=Math.sin(r),s=Math.cos(r),o=i/s,a=o*o,l=a*a,c=tW(t),u=tW(jH(n.number)),h=zH/Math.sqrt(1-bH*i**2),d=xH*s**2,p=s*oW(c-u,-Math.PI,Math.PI),f=p*p,g=f*p,m=g*p,y=m*p,v=y*p,b=zH*(MH*r-.002514607064228144*Math.sin(2*r)+LH*Math.sin(4*r)-IH*Math.sin(6*r)),w=vH*h*(p+g/6*(1-a+d)+y/120*(5-18*a+l+72*d-58*xH))+5e5;let _=vH*(b+h*o*(f/2+m/24*(5-a+9*d+4*d**2)+v/720*(61-58*a+l+600*d-330*xH)));return n.north||(_+=1e7),[w,_]}function jH(t){return 6*(t-1)-180+3}const BH=[/^EPSG:(\d+)$/,/^urn:ogc:def:crs:EPSG::(\d+)$/,/^http:\/\/www\.opengis\.net\/def\/crs\/EPSG\/0\/(\d+)$/];function UH(t){let e=0;for(const i of BH){const n=t.match(i);if(n){e=parseInt(n[1]);break}}if(!e)return null;let n=0,r=!1;return e>32700&&e<32761?n=e-32700:e>32600&&e<32661&&(r=!0,n=e-32600),n?{number:n,north:r}:null}function $H(t,e){return function(n,r,i,s){const o=n.length;i=i>1?i:2,s=s??i,r||(r=i>2?n.slice():new Array(o));for(let a=0;a180)&&(e[0]=eW(n+180,360)-180),e}function nG(t,e){if(t===e)return!0;const n=t.getUnits()===e.getUnits();return(t.getCode()===e.getCode()||rG(t,e)===GH)&&n}function rG(t,e){const n=t.getCode(),r=e.getCode();let i=yH(n,r);if(i)return i;let s=null,o=null;for(const l of qH)s||(s=l(t)),o||(o=l(e));if(!s&&!o)return null;const a="EPSG:4326";if(o)if(s)i=iG(s.inverse,o.forward);else{const t=yH(n,a);t&&(i=iG(t,o.forward))}else{const t=yH(a,r);t&&(i=iG(s.inverse,t))}return i&&(ZH(t),ZH(e),mH(t,e,i)),i}function iG(t,e){return function(n,r,i,s){return r=t(n,r,i,s),e(r,r,i,s)}}function sG(t,e){return rG(YH(t),YH(e))}function oG(t,e,n){const r=sG(e,n);if(!r){const t=YH(e).getCode(),r=YH(n).getCode();throw new Error(`No transform available between ${t} and ${r}`)}return r(t,void 0,t.length)}function aG(t,e,n,r){return UW(t,sG(e,n),void 0,r)}function lG(t){return t}function cG(t){return WH&&!VW(t,[0,0])&&t[0]>=-180&&t[0]<=180&&t[1]>=-90&&t[1]<=90&&(WH=!1,tH("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),t}function uG(t){return t}var hG,dG,pG;JH(cH),JH(pH),hG=cH,dG=function(t,e,n,r){const i=t.length;n=n>1?n:2,r=r??n,void 0===e&&(e=n>2?t.slice():new Array(i));for(let s=0;saH?n=aH:n<-aH&&(n=-aH),e[s+1]=n}return e},pG=function(t,e,n,r){const i=t.length;n=n>1?n:2,r=r??n,void 0===e&&(e=n>2?t.slice():new Array(i));for(let s=0;s{if(!n)return this.getSimplifiedGeometry(e);const r=this.clone();return r.applyTransform(n),r.getSimplifiedGeometry(e)})}simplifyTransformed(t,e){return this.simplifyTransformedInternal(this.getRevision(),t,e)}clone(){return yV()}closestPointXY(t,e,n,r){return yV()}containsXY(t,e){return 0===this.closestPointXY(t,e,TG,Number.MIN_VALUE)}getClosestPoint(t,e){return e=e||[NaN,NaN],this.closestPointXY(t[0],t[1],e,1/0),e}intersectsCoordinate(t){return this.containsXY(t[0],t[1])}computeExtent(t){return yV()}getExtent(t){if(this.extentRevision_!=this.getRevision()){const t=this.computeExtent(this.extent_);(isNaN(t[0])||isNaN(t[1]))&&vW(t),this.extentRevision_=this.getRevision()}return function(t,e){return e?(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e):t}(this.extent_,t)}rotate(t,e){yV()}scale(t,e,n){yV()}simplify(t){return this.getSimplifiedGeometry(t*t)}getSimplifiedGeometry(t){return yV()}getType(){return yV()}applyTransform(t){yV()}intersectsExtent(t){return yV()}translate(t,e){yV()}transform(t,e){const n=YH(t),r="tile-pixels"==n.getUnits()?function(t,r,i){const s=n.getExtent(),o=n.getWorldExtent(),a=OW(o)/OW(s);wG(EG,o[0],o[3],a,-a,0,0,0);const l=SG(t,0,t.length,i,EG,r),c=sG(n,e);return c?c(l,l,i):l}:sG(n,e);return this.applyTransform(r),this}}class MG extends RG{constructor(){super(),this.layout="XY",this.stride=2,this.flatCoordinates}computeExtent(t){return wW(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,t)}getCoordinates(){return yV()}getFirstCoordinate(){return this.flatCoordinates.slice(0,this.stride)}getFlatCoordinates(){return this.flatCoordinates}getLastCoordinate(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)}getLayout(){return this.layout}getSimplifiedGeometry(t){if(this.simplifiedGeometryRevision!==this.getRevision()&&(this.simplifiedGeometryMaxMinSquaredTolerance=0,this.simplifiedGeometryRevision=this.getRevision()),t<0||0!==this.simplifiedGeometryMaxMinSquaredTolerance&&t<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;const e=this.getSimplifiedGeometryInternal(t);return e.getFlatCoordinates().length1)h=n;else{if(d>0){for(let i=0;ii&&(i=a),s=n,o=r}return i}function zG(t,e,n,r,i){for(let s=0,o=n.length;s0;){const n=c.pop(),s=c.pop();let o=0;const a=t[s],h=t[s+1],d=t[n],p=t[n+1];for(let e=s+r;eo&&(u=e,o=n)}o>i&&(l[(u-e)/r]=1,s+r0&&f>d)&&(p<0&&g0&&g>p)?(a=n,l=h):(s[o++]=a,s[o++]=l,c=a,u=l,a=n,l=h)}return s[o++]=a,s[o++]=l,o}function ZG(t,e,n,r,i,s,o,a){for(let l=0,c=n.length;ls&&(n-a)*(s-l)-(i-a)*(r-l)>0&&o++:r<=s&&(n-a)*(s-l)-(i-a)*(r-l)<0&&o--,a=n,l=r}return 0!==o}function tK(t,e,n,r,i,s){if(0===n.length)return!1;if(!QG(t,e,n[0],r,i,s))return!1;for(let o=1,a=n.length;oy&&(c=(u+h)/2,tK(t,e,n,r,c,f)&&(m=c,y=i)),u=h}return isNaN(m)&&(m=i[s]),o?(o.push(m,f,y),o):[m,f,y]}function nK(t,e,n,r,i){let s=[];for(let o=0,a=n.length;o=i[0]&&s[2]<=i[2]||s[1]>=i[1]&&s[3]<=i[3]||rK(t,e,n,r,function(t,e){return function(t,e,n){let r=!1;const i=mW(t,e),s=mW(t,n);if(1===i||1===s)r=!0;else{const o=t[0],a=t[1],l=t[2],c=t[3],u=e[0],h=e[1],d=n[0],p=n[1],f=(p-h)/(d-u);let g,m;2&s&&!(2&i)&&(g=d-(p-c)/f,r=g>=o&&g<=l),r||!(4&s)||4&i||(m=p-(d-l)*f,r=m>=a&&m<=c),r||!(8&s)||8&i||(g=d-(p-a)/f,r=g>=o&&g<=l),r||!(16&s)||16&i||(m=p-(d-o)*f,r=m>=a&&m<=c)}return r}(i,t,e)}))}function sK(t,e,n,r,i){return!!(iK(t,e,n,r,i)||QG(t,e,n,r,i[0],i[1])||QG(t,e,n,r,i[0],i[3])||QG(t,e,n,r,i[2],i[1])||QG(t,e,n,r,i[2],i[3]))}function oK(t,e,n,r,i){if(!sK(t,e,n[0],r,i))return!1;if(1===n.length)return!0;for(let s=1,o=n.length;s0}function cK(t,e,n,r,i){i=void 0!==i&&i;for(let s=0,o=n.length;su&&d1&&"function"==typeof arguments[n-1]&&(e=arguments[n-1],--n);let r=0;for(;r0}getInteracting(){return this.hints_[1]>0}cancelAnimations(){let t;this.setHint(0,-this.hints_[0]);for(let e=0,n=this.animations_.length;e=0;--n){const r=this.animations_[n];let i=!0;for(let n=0,s=r.length;n0?o/s.duration:1;a>=1?(s.complete=!0,a=1):i=!1;const l=s.easing(a);if(s.sourceCenter){const t=s.sourceCenter[0],e=s.sourceCenter[1],n=s.targetCenter[0],r=s.targetCenter[1];this.nextCenter_=s.targetCenter;const i=t+l*(n-t),o=e+l*(r-e);this.targetCenter_=[i,o]}if(s.sourceResolution&&s.targetResolution){const t=1===l?s.targetResolution:s.sourceResolution+l*(s.targetResolution-s.sourceResolution);if(s.anchor){const e=this.getViewportSize_(this.getRotation()),n=this.constraints_.resolution(t,0,e,!0);this.targetCenter_=this.calculateCenterZoom(n,s.anchor)}this.nextResolution_=s.targetResolution,this.targetResolution_=t,this.applyTargetState_(!0)}if(void 0!==s.sourceRotation&&void 0!==s.targetRotation){const t=1===l?eW(s.targetRotation+Math.PI,2*Math.PI)-Math.PI:s.sourceRotation+l*(s.targetRotation-s.sourceRotation);if(s.anchor){const e=this.constraints_.rotation(t,!0);this.targetCenter_=this.calculateCenterRotate(e,s.anchor)}this.nextRotation_=s.targetRotation,this.targetRotation_=t}if(this.applyTargetState_(!0),e=!0,!s.complete)break}if(i){this.animations_[n]=null,this.setHint(0,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const t=r[0].callback;t&&xK(t,!0)}}this.animations_=this.animations_.filter(Boolean),e&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(t,e){let n;const r=this.getCenterInternal();var i,s;return void 0!==r&&(n=[r[0]-e[0],r[1]-e[1]],WW(n,t-this.getRotation()),s=e,(i=n)[0]+=+s[0],i[1]+=+s[1]),n}calculateCenterZoom(t,e){let n;const r=this.getCenterInternal(),i=this.getResolution();return void 0!==r&&void 0!==i&&(n=[e[0]-t*(e[0]-r[0])/i,e[1]-t*(e[1]-r[1])/i]),n}getViewportSize_(t){const e=this.viewportSize_;if(t){const n=e[0],r=e[1];return[Math.abs(n*Math.cos(t))+Math.abs(r*Math.sin(t)),Math.abs(n*Math.sin(t))+Math.abs(r*Math.cos(t))]}return e}setViewportSize(t){this.viewportSize_=Array.isArray(t)?t.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const t=this.getCenterInternal();return t?lG(t,this.getProjection()):t}getCenterInternal(){return this.get(ZV.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(t){return void 0!==t?(t[0]=this.hints_[0],t[1]=this.hints_[1],t):this.hints_.slice()}calculateExtent(t){return e=this.calculateExtentInternal(t),this.getProjection(),e;var e}calculateExtentInternal(t){t=t||this.getViewportSizeMinusPadding_();const e=this.getCenterInternal();WV(e,"The view center is not defined");const n=this.getResolution();WV(void 0!==n,"The view resolution is not defined");const r=this.getRotation();return WV(void 0!==r,"The view rotation is not defined"),PW(e,n,r,t)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(t){this.applyOptions_(this.getUpdatedOptions_({maxZoom:t}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(t){this.applyOptions_(this.getUpdatedOptions_({minZoom:t}))}setConstrainResolution(t){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:t}))}getProjection(){return this.projection_}getResolution(){return this.get(ZV.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(t,e){return this.getResolutionForExtentInternal(uG(t,this.getProjection()),e)}getResolutionForExtentInternal(t,e){e=e||this.getViewportSizeMinusPadding_();const n=NW(t)/e[0],r=OW(t)/e[1];return Math.max(n,r)}getResolutionForValueFunction(t){t=t||2;const e=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,r=Math.log(e/n)/Math.log(t);return function(n){return e/Math.pow(t,n*r)}}getRotation(){return this.get(ZV.ROTATION)}getValueForResolutionFunction(t){const e=Math.log(t||2),n=this.getConstrainedResolution(this.maxResolution_),r=this.minResolution_,i=Math.log(n/r)/e;return function(t){return Math.log(n/t)/e/i}}getViewportSizeMinusPadding_(t){let e=this.getViewportSize_(t);const n=this.padding_;return n&&(e=[e[0]-n[1]-n[3],e[1]-n[0]-n[2]]),e}getState(){const t=this.getProjection(),e=this.getResolution(),n=this.getRotation();let r=this.getCenterInternal();const i=this.padding_;if(i){const t=this.getViewportSizeMinusPadding_();r=SK(r,this.getViewportSize_(),[t[0]/2+i[3],t[1]/2+i[0]],e,n)}return{center:r.slice(0),projection:void 0!==t?t:null,resolution:e,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:n,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let t;const e=this.getResolution();return void 0!==e&&(t=this.getZoomForResolution(e)),t}getZoomForResolution(t){let e,n,r=this.minZoom_||0;if(this.resolutions_){const i=tV(this.resolutions_,t,1);r=i,e=this.resolutions_[i],n=i==this.resolutions_.length-1?2:e/this.resolutions_[i+1]}else e=this.maxResolution_,n=this.zoomFactor_;return r+Math.log(e/t)/Math.log(n)}getResolutionForZoom(t){if(this.resolutions_?.length){if(1===this.resolutions_.length)return this.resolutions_[0];const e=YV(Math.floor(t),0,this.resolutions_.length-2),n=this.resolutions_[e]/this.resolutions_[e+1];return this.resolutions_[e]/Math.pow(n,YV(t-e,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,t-this.minZoom_)}fit(t,e){let n;if(WV(Array.isArray(t)||"function"==typeof t.getSimplifiedGeometry,"Invalid extent or geometry provided as `geometry`"),Array.isArray(t))WV(!BW(t),"Cannot fit empty extent provided as `geometry`"),n=gK(uG(t,this.getProjection()));else if("Circle"===t.getType()){const e=uG(t.getExtent(),this.getProjection());n=gK(e),n.rotate(this.getRotation(),LW(e))}else n=t;this.fitInternal(n,e)}rotatedExtentForGeometry(t){const e=this.getRotation(),n=Math.cos(e),r=Math.sin(-e),i=t.getFlatCoordinates(),s=t.getStride();let o=1/0,a=1/0,l=-1/0,c=-1/0;for(let u=0,h=i.length;ut.trim().replace(/^['"]|['"]$/g,"")),n};function AK(t,e,n,r){let i;return i=n&&n.length?n.shift():PV?new class extends OffscreenCanvas{style={}}(t??300,e??150):document.createElement("canvas"),t&&(i.width=t),e&&(i.height=e),i.getContext("2d",r)}let OK;function FK(){return OK||(OK=AK(1,1)),OK}function zK(t){const e=t.canvas;e.width=1,e.height=1,t.clearRect(0,0,1,1)}function DK(t){let e=t.offsetWidth;const n=getComputedStyle(t);return e+=parseInt(n.marginLeft,10)+parseInt(n.marginRight,10),e}function NK(t){let e=t.offsetHeight;const n=getComputedStyle(t);return e+=parseInt(n.marginTop,10)+parseInt(n.marginBottom,10),e}function jK(t,e){const n=e.parentNode;n&&n.replaceChild(t,e)}function BK(t){for(;t.lastChild;)t.lastChild.remove()}function UK(){const t=new Proxy({childNodes:[],appendChild:function(t){return this.childNodes.push(t),t},remove:function(){},removeChild:function(t){const e=this.childNodes.indexOf(t);if(-1===e)throw new Error("Node to remove was not found");return this.childNodes.splice(e,1),t},insertBefore:function(t,e){const n=this.childNodes.indexOf(e);if(-1===n)throw new Error("Reference node not found");return this.childNodes.splice(n,0,t),t},style:{}},{get:(t,e,n)=>"firstElementChild"===e?t.childNodes.length>0?t.childNodes[0]:null:Reflect.get(t,e,n)});return t}function $K(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}class qK extends _V{constructor(t){super();const e=t.element;!e||t.target||e.style.pointerEvents||(e.style.pointerEvents="auto"),this.element=e||null,this.target_=null,this.map_=null,this.listenerKeys=[],t.render&&(this.render=t.render),t.target&&this.setTarget(t.target)}disposeInternal(){this.element?.remove(),super.disposeInternal()}getMap(){return this.map_}setMap(t){this.map_&&this.element?.remove();for(let e=0,n=this.listenerKeys.length;ee.getAttributions(t)));if(void 0!==this.attributions_&&(Array.isArray(this.attributions_)?this.attributions_.forEach(t=>n.add(t)):n.add(this.attributions_)),!this.overrideCollapsible_){const t=!e.some(t=>!1===t.getSource()?.getAttributionsCollapsible());this.setCollapsible(t)}return Array.from(n)}async updateElement_(t){if(!t)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const e=await Promise.all(this.collectSourceAttributions_(t).map(t=>lV(()=>t))),n=e.length>0;if(this.renderedVisible_!=n&&(this.element.style.display=n?"":"none",this.renderedVisible_=n),!rV(e,this.renderedAttributions_)){BK(this.ulElement_);for(let t=0,n=e.length;t0&&e%(2*Math.PI)!=0?t.animate({rotation:0,duration:this.duration_,easing:KW}):t.setRotation(0))}render(t){const e=t.frameState;if(!e)return;const n=e.viewState.rotation;if(n!=this.rotation_){const t="rotate("+n+"rad)";if(this.autoHide_){const t=this.element.classList.contains(kK);t||0!==n?t&&0!==n&&this.element.classList.remove(kK):this.element.classList.add(kK)}this.label_.style.transform=t}this.rotation_=n}}class HK extends qK{constructor(t){t=t||{},super({element:document.createElement("div"),target:t.target});const e=void 0!==t.className?t.className:"ol-zoom",n=void 0!==t.delta?t.delta:1,r=void 0!==t.zoomInClassName?t.zoomInClassName:e+"-in",i=void 0!==t.zoomOutClassName?t.zoomOutClassName:e+"-out",s=void 0!==t.zoomInLabel?t.zoomInLabel:"+",o=void 0!==t.zoomOutLabel?t.zoomOutLabel:"–",a=void 0!==t.zoomInTipLabel?t.zoomInTipLabel:"Zoom in",l=void 0!==t.zoomOutTipLabel?t.zoomOutTipLabel:"Zoom out",c=document.createElement("button");c.className=r,c.setAttribute("type","button"),c.title=a,c.appendChild("string"==typeof s?document.createTextNode(s):s),c.addEventListener(Hq,this.handleClick_.bind(this,n),!1);const u=document.createElement("button");u.className=i,u.setAttribute("type","button"),u.title=l,u.appendChild("string"==typeof o?document.createTextNode(o):o),u.addEventListener(Hq,this.handleClick_.bind(this,-n),!1);const h=e+" "+EK+" "+TK,d=this.element;d.className=h,d.appendChild(c),d.appendChild(u),this.duration_=void 0!==t.duration?t.duration:250}handleClick_(t,e){e.preventDefault(),this.zoomByDelta_(t)}zoomByDelta_(t){const e=this.getMap().getView();if(!e)return;const n=e.getZoom();if(void 0!==n){const r=e.getConstrainedZoom(n+t);this.duration_>0?(e.getAnimating()&&e.cancelAnimations(),e.animate({zoom:r,duration:this.duration_,easing:KW})):e.setZoom(r)}}}function GK(t){t=t||{};const e=new SV;return(void 0===t.zoom||t.zoom)&&e.push(new HK(t.zoomOptions)),(void 0===t.rotate||t.rotate)&&e.push(new WK(t.rotateOptions)),(void 0===t.attribution||t.attribution)&&e.push(new VK(t.attributionOptions)),e}class KK{constructor(t,e,n){this.decay_=t,this.minVelocity_=e,this.delay_=n,this.points_=[],this.angle_=0,this.initialVelocity_=0}begin(){this.points_.length=0,this.angle_=0,this.initialVelocity_=0}update(t,e){this.points_.push(t,e,Date.now())}end(){if(this.points_.length<6)return!1;const t=Date.now()-this.delay_,e=this.points_.length-3;if(this.points_[e+2]0&&this.points_[n+2]>t;)n-=3;const r=this.points_[e+2]-this.points_[n+2];if(r<1e3/60)return!1;const i=this.points_[e]-this.points_[n],s=this.points_[e+1]-this.points_[n+1];return this.angle_=Math.atan2(s,i),this.initialVelocity_=Math.sqrt(i*i+s*s)/r,this.initialVelocity_>this.minVelocity_}getDistance(){return(this.minVelocity_-this.initialVelocity_)/this.decay_}getAngle(){return this.angle_}}const ZK="active";class YK extends _V{constructor(t){super(),this.on,this.once,this.un,t&&t.handleEvent&&(this.handleEvent=t.handleEvent),this.map_=null,this.setActive(!0)}getActive(){return this.get(ZK)}getMap(){return this.map_}handleEvent(t){return!0}setActive(t){this.set(ZK,t)}setMap(t){this.map_=t}}function XK(t,e,n,r){const i=t.getZoom();if(void 0===i)return;const s=t.getConstrainedZoom(i+e),o=t.getResolutionForZoom(s);t.getAnimating()&&t.cancelAnimations(),t.animate({resolution:o,anchor:n,duration:void 0!==r?r:250,easing:KW})}class JK extends YK{constructor(t){super(),t=t||{},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:250}handleEvent(t){let e=!1;if(t.type==TV.DBLCLICK){const n=t.originalEvent,r=t.map,i=t.coordinate,s=n.shiftKey?-this.delta_:this.delta_;XK(r.getView(),s,i,this.duration_),n.preventDefault(),e=!0}return!e}}function QK(t){const e=arguments;return function(t){let n=!0;for(let r=0,i=e.length;r0}}else if(t.type==TV.POINTERDOWN){const n=this.handleDownEvent(t);this.handlingDownUpSequence=n,e=this.stopDown(n)}else t.type==TV.POINTERMOVE&&this.handleMoveEvent(t);return!e}handleMoveEvent(t){}handleUpEvent(t){return!1}stopDown(t){return t}updateTrackedPointers_(t){t.activePointers&&(this.targetPointers=t.activePointers)}}function uZ(t){const e=t.length;let n=0,r=0;for(let i=0;i0&&this.condition_(t)){const e=t.map.getView();return this.lastCentroid=null,e.getAnimating()&&e.cancelAnimations(),this.kinetic_&&this.kinetic_.begin(),this.noKinetic_=this.targetPointers.length>1,!0}return!1}}class dZ extends cZ{constructor(t){t=t||{},super({stopDown:sV}),this.condition_=t.condition?t.condition:tZ,this.lastAngle_=void 0,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){if(!aZ(t))return;const e=t.map,n=e.getView();if(n.getConstraints().rotation===bK)return;const r=e.getSize(),i=t.pixel,s=Math.atan2(r[1]/2-i[1],i[0]-r[0]/2);if(void 0!==this.lastAngle_){const t=s-this.lastAngle_;n.adjustRotationInternal(-t)}this.lastAngle_=s}handleUpEvent(t){return!aZ(t)||(t.map.getView().endInteraction(this.duration_),!1)}handleDownEvent(t){return!(!aZ(t)||!rZ(t)||!this.condition_(t)||(t.map.getView().beginInteraction(),this.lastAngle_=void 0,0))}}class pZ extends Xq{constructor(t){super(),this.geometry_=null,this.element_=document.createElement("div"),this.element_.style.position="absolute",this.element_.style.pointerEvents="auto",this.element_.className="ol-box "+t,this.map_=null,this.startPixel_=null,this.endPixel_=null}disposeInternal(){this.setMap(null)}render_(){const t=this.startPixel_,e=this.endPixel_,n="px",r=this.element_.style;r.left=Math.min(t[0],e[0])+n,r.top=Math.min(t[1],e[1])+n,r.width=Math.abs(e[0]-t[0])+n,r.height=Math.abs(e[1]-t[1])+n}setMap(t){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);const t=this.element_.style;t.left="inherit",t.top="inherit",t.width="inherit",t.height="inherit"}this.map_=t,this.map_&&this.map_.getOverlayContainer().appendChild(this.element_)}setPixels(t,e){this.startPixel_=t,this.endPixel_=e,this.createOrUpdateGeometry(),this.render_()}createOrUpdateGeometry(){if(!this.map_)return;const t=this.startPixel_,e=this.endPixel_,n=[t,[t[0],e[1]],e,[e[0],t[1]]].map(this.map_.getCoordinateFromPixelInternal,this.map_);n[4]=n[0].slice(),this.geometry_?this.geometry_.setCoordinates([n]):this.geometry_=new fK([n])}getGeometry(){return this.geometry_}}const fZ="boxcancel";class gZ extends hV{constructor(t,e,n){super(t),this.coordinate=e,this.mapBrowserEvent=n}}class mZ extends cZ{constructor(t){super(),this.on,this.once,this.un,t=t??{},this.box_=new pZ(t.className||"ol-dragbox"),this.minArea_=t.minArea??64,t.onBoxEnd&&(this.onBoxEnd=t.onBoxEnd),this.startPixel_=null,this.condition_=t.condition??rZ,this.boxEndCondition_=t.boxEndCondition??this.defaultBoxEndCondition}defaultBoxEndCondition(t,e,n){const r=n[0]-e[0],i=n[1]-e[1];return r*r+i*i>=this.minArea_}getGeometry(){return this.box_.getGeometry()}handleDragEvent(t){this.startPixel_&&(this.box_.setPixels(this.startPixel_,t.pixel),this.dispatchEvent(new gZ("boxdrag",t.coordinate,t)))}handleUpEvent(t){if(!this.startPixel_)return!1;const e=this.boxEndCondition_(t,this.startPixel_,t.pixel);return e&&this.onBoxEnd(t),this.dispatchEvent(new gZ(e?"boxend":fZ,t.coordinate,t)),this.box_.setMap(null),this.startPixel_=null,!1}handleDownEvent(t){return!!this.condition_(t)&&(this.startPixel_=t.pixel,this.box_.setMap(t.map),this.box_.setPixels(this.startPixel_,this.startPixel_),this.dispatchEvent(new gZ("boxstart",t.coordinate,t)),!0)}onBoxEnd(t){}setActive(t){t||(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new gZ(fZ,this.startPixel_,null)),this.startPixel_=null)),super.setActive(t)}setMap(t){this.getMap()&&(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new gZ(fZ,this.startPixel_,null)),this.startPixel_=null)),super.setMap(t)}}class yZ extends mZ{constructor(t){super({condition:(t=t||{}).condition?t.condition:sZ,className:t.className||"ol-dragzoom",minArea:t.minArea}),this.duration_=void 0!==t.duration?t.duration:200,this.out_=void 0!==t.out&&t.out}onBoxEnd(t){const e=this.getMap().getView();let n=this.getGeometry();if(this.out_){const t=e.rotatedExtentForGeometry(n),r=e.getResolutionForExtentInternal(t),i=e.getResolution()/r;n=n.clone(),n.scale(i*i)}e.fitInternal(n,{duration:this.duration_,easing:KW})}}const vZ="ArrowLeft",bZ="ArrowRight",wZ="ArrowDown";class _Z extends YK{constructor(t){super(),t=t||{},this.defaultCondition_=function(t){return iZ(t)&&oZ(t)},this.condition_=void 0!==t.condition?t.condition:this.defaultCondition_,this.duration_=void 0!==t.duration?t.duration:100,this.pixelDelta_=void 0!==t.pixelDelta?t.pixelDelta:128}handleEvent(t){let e=!1;if(t.type==Gq){const n=t.originalEvent,r=n.key;if(this.condition_(t)&&(r==wZ||r==vZ||r==bZ||"ArrowUp"==r)){const i=t.map.getView(),s=i.getResolution()*this.pixelDelta_;let o=0,a=0;r==wZ?a=-s:r==vZ?o=-s:r==bZ?o=s:a=s;const l=[o,a];WW(l,i.getRotation()),function(t,e,n){const r=t.getCenterInternal();if(r){const i=[r[0]+e[0],r[1]+e[1]];t.animateInternal({duration:void 0!==n?n:250,easing:YW,center:t.getConstrainedCenter(i)})}}(i,l,this.duration_),n.preventDefault(),e=!0}}return!e}}class xZ extends YK{constructor(t){super(),t=t||{},this.condition_=t.condition?t.condition:function(t){return!function(t){const e=t.originalEvent;return LV?e.metaKey:e.ctrlKey}(t)&&oZ(t)},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:100}handleEvent(t){let e=!1;if(t.type==Gq||t.type==Kq){const n=t.originalEvent,r=n.key;if(this.condition_(t)&&("+"===r||"-"===r)){const i=t.map,s="+"===r?this.delta_:-this.delta_;XK(i.getView(),s,void 0,this.duration_),n.preventDefault(),e=!0}}return!e}}class CZ extends YK{constructor(t){super(t=t||{}),this.totalDelta_=0,this.lastDelta_=0,this.maxDelta_=void 0!==t.maxDelta?t.maxDelta:1,this.duration_=void 0!==t.duration?t.duration:250,this.timeout_=void 0!==t.timeout?t.timeout:80,this.useAnchor_=void 0===t.useAnchor||t.useAnchor,this.constrainResolution_=void 0!==t.constrainResolution&&t.constrainResolution;const e=t.condition?t.condition:nZ;this.condition_=t.onFocusOnly?QK(eZ,e):e,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_,this.mode_=void 0,this.trackpadEventGap_=400,this.trackpadTimeoutId_,this.deltaPerZoom_=300}endInteraction_(){this.trackpadTimeoutId_=void 0;const t=this.getMap();t&&t.getView().endInteraction(void 0,this.lastDelta_?this.lastDelta_>0?1:-1:0,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null)}handleEvent(t){if(!this.condition_(t))return!0;if(t.type!==Yq)return!0;const e=t.map,n=t.originalEvent;n.preventDefault(),this.useAnchor_&&(this.lastAnchor_=t.pixel);let r=n.deltaY;switch(n.deltaMode){case WheelEvent.DOM_DELTA_LINE:r*=40;break;case WheelEvent.DOM_DELTA_PAGE:r*=300}if(0===r)return!1;this.lastDelta_=r;const i=Date.now();void 0===this.startTime_&&(this.startTime_=i),(!this.mode_||i-this.startTime_>this.trackpadEventGap_)&&(this.mode_=Math.abs(r)<4?"trackpad":"wheel");const s=e.getView();if("trackpad"===this.mode_&&!s.getConstrainResolution()&&!this.constrainResolution_)return this.trackpadTimeoutId_?clearTimeout(this.trackpadTimeoutId_):(s.getAnimating()&&s.cancelAnimations(),s.beginInteraction()),this.trackpadTimeoutId_=setTimeout(this.endInteraction_.bind(this),this.timeout_),s.adjustZoom(-r/this.deltaPerZoom_,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null),this.startTime_=i,!1;this.totalDelta_+=r;const o=Math.max(this.timeout_-(i-this.startTime_),0);return clearTimeout(this.timeoutId_),this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,e),o),!1}handleWheelZoom_(t){const e=t.getView();e.getAnimating()&&e.cancelAnimations();let n=-YV(this.totalDelta_,-this.maxDelta_*this.deltaPerZoom_,this.maxDelta_*this.deltaPerZoom_)/this.deltaPerZoom_;(e.getConstrainResolution()||this.constrainResolution_)&&(n=n?n>0?1:-1:0),XK(e,n,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null,this.duration_),this.mode_=void 0,this.totalDelta_=0,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_=void 0}setMouseAnchor(t){this.useAnchor_=t,t||(this.lastAnchor_=null)}}class SZ extends cZ{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=sV),super(e),this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.threshold_=void 0!==t.threshold?t.threshold:.3,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){let e=0;const n=this.targetPointers[0],r=this.targetPointers[1],i=Math.atan2(r.clientY-n.clientY,r.clientX-n.clientX);if(void 0!==this.lastAngle_){const t=i-this.lastAngle_;this.rotationDelta_+=t,!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_&&(this.rotating_=!0),e=t}this.lastAngle_=i;const s=t.map,o=s.getView();o.getConstraints().rotation!==bK&&(this.anchor_=s.getCoordinateFromPixelInternal(s.getEventPixel(uZ(this.targetPointers))),this.rotating_&&(s.render(),o.adjustRotationInternal(e,this.anchor_)))}handleUpEvent(t){return!(this.targetPointers.length<2&&(t.map.getView().endInteraction(this.duration_),1))}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}}class kZ extends cZ{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=sV),super(e),this.anchor_=null,this.duration_=void 0!==t.duration?t.duration:400,this.lastDistance_=void 0,this.lastScaleDelta_=1}handleDragEvent(t){let e=1;const n=this.targetPointers[0],r=this.targetPointers[1],i=n.clientX-r.clientX,s=n.clientY-r.clientY,o=Math.sqrt(i*i+s*s);void 0!==this.lastDistance_&&(e=this.lastDistance_/o),this.lastDistance_=o;const a=t.map,l=a.getView();1!=e&&(this.lastScaleDelta_=e),this.anchor_=a.getCoordinateFromPixelInternal(a.getEventPixel(uZ(this.targetPointers))),a.render(),l.adjustResolutionInternal(e,this.anchor_)}handleUpEvent(t){if(this.targetPointers.length<2){const e=t.map.getView(),n=this.lastScaleDelta_>1?1:-1;return e.endInteraction(this.duration_,n),!1}return!0}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}}function EZ(t){t=t||{};const e=new SV,n=new KK(-.005,.05,100);return(void 0===t.altShiftDragRotate||t.altShiftDragRotate)&&e.push(new dZ),(void 0===t.doubleClickZoom||t.doubleClickZoom)&&e.push(new JK({delta:t.zoomDelta,duration:t.zoomDuration})),(void 0===t.dragPan||t.dragPan)&&e.push(new hZ({onFocusOnly:t.onFocusOnly,kinetic:n})),(void 0===t.pinchRotate||t.pinchRotate)&&e.push(new SZ),(void 0===t.pinchZoom||t.pinchZoom)&&e.push(new kZ({duration:t.zoomDuration})),(void 0===t.keyboard||t.keyboard)&&(e.push(new _Z),e.push(new xZ({delta:t.zoomDelta,duration:t.zoomDuration}))),(void 0===t.mouseWheelZoom||t.mouseWheelZoom)&&e.push(new CZ({onFocusOnly:t.onFocusOnly,duration:t.zoomDuration})),(void 0===t.shiftDragZoom||t.shiftDragZoom)&&e.push(new yZ({duration:t.zoomDuration})),e}const TZ="opacity",RZ="visible",MZ="extent",LZ="zIndex",IZ="maxResolution",PZ="minResolution",AZ="maxZoom",OZ="minZoom",FZ="source";class zZ extends _V{constructor(t){super(),this.on,this.once,this.un,this.background_=t.background;const e=Object.assign({},t);"object"==typeof t.properties&&(delete e.properties,Object.assign(e,t.properties)),e[TZ]=void 0!==t.opacity?t.opacity:1,WV("number"==typeof e[TZ],"Layer opacity must be a number"),e[RZ]=void 0===t.visible||t.visible,e[LZ]=t.zIndex,e[IZ]=void 0!==t.maxResolution?t.maxResolution:1/0,e[PZ]=void 0!==t.minResolution?t.minResolution:0,e[OZ]=void 0!==t.minZoom?t.minZoom:-1/0,e[AZ]=void 0!==t.maxZoom?t.maxZoom:1/0,this.className_=void 0!==e.className?e.className:"ol-layer",delete e.className,this.setProperties(e),this.state_=null}getBackground(){return this.background_}getClassName(){return this.className_}getLayerState(t){const e=this.state_||{layer:this,managed:void 0===t||t},n=this.getZIndex();return e.opacity=YV(Math.round(100*this.getOpacity())/100,0,1),e.visible=this.getVisible(),e.extent=this.getExtent(),e.zIndex=void 0!==n||e.managed?n:1/0,e.maxResolution=this.getMaxResolution(),e.minResolution=Math.max(this.getMinResolution(),0),e.minZoom=this.getMinZoom(),e.maxZoom=this.getMaxZoom(),this.state_=e,e}getLayersArray(t){return yV()}getLayerStatesArray(t){return yV()}getExtent(){return this.get(MZ)}getMaxResolution(){return this.get(IZ)}getMinResolution(){return this.get(PZ)}getMinZoom(){return this.get(OZ)}getMaxZoom(){return this.get(AZ)}getOpacity(){return this.get(TZ)}getSourceState(){return yV()}getVisible(){return this.get(RZ)}getZIndex(){return this.get(LZ)}setBackground(t){this.background_=t,this.changed()}setExtent(t){this.set(MZ,t)}setMaxResolution(t){this.set(IZ,t)}setMinResolution(t){this.set(PZ,t)}setMaxZoom(t){this.set(AZ,t)}setMinZoom(t){this.set(OZ,t)}setOpacity(t){WV("number"==typeof t,"Layer opacity must be a number"),this.set(TZ,t)}setVisible(t){this.set(RZ,t)}setZIndex(t){this.set(LZ,t)}disposeInternal(){this.state_&&(this.state_.layer=null,this.state_=null),super.disposeInternal()}}const DZ="addlayer",NZ="removelayer";class jZ extends hV{constructor(t,e){super(t),this.layer=e}}const BZ="layers";class UZ extends zZ{constructor(t){t=t||{};const e=Object.assign({},t);delete e.layers;let n=t.layers;super(e),this.on,this.once,this.un,this.layersListenerKeys_=[],this.listenerKeys_={},this.addChangeListener(BZ,this.handleLayersChanged_),n?Array.isArray(n)?n=new SV(n.slice(),{unique:!0}):WV("function"==typeof n.getArray,"Expected `layers` to be an array or a `Collection`"):n=new SV(void 0,{unique:!0}),this.setLayers(n)}handleLayerChange_(){this.changed()}handleLayersChanged_(){this.layersListenerKeys_.forEach(gV),this.layersListenerKeys_.length=0;const t=this.getLayers();this.layersListenerKeys_.push(pV(t,Uq,this.handleLayersAdd_,this),pV(t,$q,this.handleLayersRemove_,this));for(const n in this.listenerKeys_)this.listenerKeys_[n].forEach(gV);cV(this.listenerKeys_);const e=t.getArray();for(let n=0,r=e.length;n{this.dispatchEvent("sourceready")},0))),this.changed()}getFeatures(t){return this.renderer_?this.renderer_.getFeatures(t):Promise.resolve([])}getData(t){return this.renderer_&&this.rendered?this.renderer_.getData(t):null}isVisible(t){let e;const n=this.getMapInternal();let r;if(!t&&n&&(t=n.getView()),e=t instanceof _K?{viewState:t.getState(),extent:t.calculateExtent()}:t,!e.layerStatesArray&&n&&(e.layerStatesArray=n.getLayerGroup().getLayerStatesArray()),e.layerStatesArray){if(r=e.layerStatesArray.find(t=>t.layer===this),!r)return!1}else r=this.getLayerState();const i=this.getExtent();return GZ(r,e.viewState)&&(!i||jW(i,e.extent))}getAttributions(t){if(!this.isVisible(t))return[];const e=this.getSource()?.getAttributions();if(!e)return[];let n=e(t instanceof _K?t.getViewStateAndExtent():t);return Array.isArray(n)||(n=[n]),n}render(t,e){const n=this.getRenderer();return n.prepareFrame(t)?(this.rendered=!0,n.renderFrame(t,e)):null}unrender(){this.rendered=!1}getDeclutter(){}renderDeclutter(t,e){}renderDeferred(t){const e=this.getRenderer();e&&e.renderDeferred(t)}setMapInternal(t){t||this.unrender(),this.set("map",t)}getMapInternal(){return this.get("map")}setMap(t){this.mapPrecomposeKey_&&(gV(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),t||this.changed(),this.mapRenderKey_&&(gV(this.mapRenderKey_),this.mapRenderKey_=null),t&&(this.mapPrecomposeKey_=pV(t,VZ,this.handlePrecompose_,this),this.mapRenderKey_=pV(this,Vq,t.render,t),this.changed())}handlePrecompose_(t){const e=t.frameState.layerStatesArray,n=this.getLayerState(!1);WV(!e.some(t=>t.layer===n.layer),"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both."),e.push(n)}setSource(t){this.set(FZ,t)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}clearRenderer(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_)}disposeInternal(){this.clearRenderer(),this.setSource(null),super.disposeInternal()}}function GZ(t,e){if(!t.visible)return!1;const n=e.resolution;if(n=t.maxResolution)return!1;const r=e.zoom;return r>t.minZoom&&r<=t.maxZoom}function KZ(t,e,n=0,r=t.length-1,i=YZ){for(;r>n;){if(r-n>600){const s=r-n+1,o=e-n+1,a=Math.log(s),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(s-l)/s)*(o-s/2<0?-1:1);KZ(t,e,Math.max(n,Math.floor(e-o*l/s+c)),Math.min(r,Math.floor(e+(s-o)*l/s+c)),i)}const s=t[e];let o=n,a=r;for(ZZ(t,n,e),i(t[r],s)>0&&ZZ(t,n,r);o0;)a--}0===i(t[n],s)?ZZ(t,n,a):(a++,ZZ(t,a,r)),a<=e&&(n=a+1),e<=a&&(r=a-1)}}function ZZ(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function YZ(t,e){return te?1:0}let XZ=class{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const n=[];if(!cY(t,e))return n;const r=this.toBBox,i=[];for(;e;){for(let s=0;s=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}_split(t,e){const n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);const s=this._chooseSplitIndex(n,i,r),o=uY(n.children.splice(s,n.children.length-s));o.height=n.height,o.leaf=n.leaf,QZ(n,this.toBBox),QZ(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(n,o)}_splitRoot(t,e){this.data=uY([t,e]),this.data.height=t.height+1,this.data.leaf=!1,QZ(this.data,this.toBBox)}_chooseSplitIndex(t,e,n){let r,i=1/0,s=1/0;for(let o=e;o<=n-e;o++){const e=tY(t,0,o,this.toBBox),a=tY(t,o,n,this.toBBox),l=aY(e,a),c=iY(e)+iY(a);l=e;l--){const e=t.children[l];eY(o,t.leaf?i(e):e),a+=sY(o)}return a}_adjustParentBBoxes(t,e,n){for(let r=n;r>=0;r--)eY(e[r],t)}_condense(t){for(let e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children,e.splice(e.indexOf(t[n]),1)):this.clear():QZ(t[n],this.toBBox)}};function JZ(t,e,n){if(!n)return e.indexOf(t);for(let r=0;r=t.minX&&e.maxY>=t.minY}function uY(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function hY(t,e,n,r,i){const s=[e,n];for(;s.length;){if((n=s.pop())-(e=s.pop())<=r)continue;const o=e+Math.ceil((n-e)/r/2)*r;KZ(t,o,e,n,i),s.push(e,o,o,n)}}const dY=[NaN,NaN,NaN,0];let pY;const fY=/^rgba?\(\s*(\d+%?)\s+(\d+%?)\s+(\d+%?)(?:\s*\/\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,gY=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,mY=/^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,yY=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;function vY(t,e){return t.endsWith("%")?Number(t.substring(0,t.length-1))/e:Number(t)}function bY(t){throw new Error('failed to parse "'+t+'" as color')}function wY(t){if(t.toLowerCase().startsWith("rgb")){const e=t.match(gY)||t.match(fY)||t.match(mY);if(e){const t=e[4],n=100/255;return[YV(vY(e[1],n)+.5|0,0,255),YV(vY(e[2],n)+.5|0,0,255),YV(vY(e[3],n)+.5|0,0,255),void 0!==t?YV(vY(t,100),0,1):1]}bY(t)}if(t.startsWith("#")){if(yY.test(t)){const e=t.substring(1),n=e.length<=4?1:2,r=[0,0,0,255];for(let t=0,i=e.length;t.0031308?269.025*Math.pow(t,1/2.4)-14.025:3294.6*t}function kY(t){return t>.2068965?Math.pow(t,3):108/841*(t-4/29)}function EY(t){return t>10.314724?Math.pow((t+14.025)/269.025,2.4):t/3294.6}function TY(t){return t>.0088564?Math.pow(t,1/3):t/(108/841)+4/29}function RY(t){const e=EY(t[0]),n=EY(t[1]),r=EY(t[2]),i=TY(.222488403*e+.716873169*n+.06060791*r),s=500*(TY(.452247074*e+.399439023*n+.148375274*r)-i),o=200*(i-TY(.016863605*e+.117638439*n+.865350722*r)),a=Math.atan2(o,s)*(180/Math.PI);return[116*i-16,Math.sqrt(s*s+o*o),a<0?a+360:a,t[3]]}function MY(t){if("none"===t)return dY;if(_Y.hasOwnProperty(t))return _Y[t];if(xY>=1024){let t=0;for(const e in _Y)3&t++||(delete _Y[e],--xY)}const e=wY(t);4!==e.length&&bY(t);for(const n of e)isNaN(n)&&bY(t);return _Y[t]=e,++xY,e}function LY(t){return Array.isArray(t)?t:MY(t)}function IY(t){let e=t[0];e!=(0|e)&&(e=e+.5|0);let n=t[1];n!=(0|n)&&(n=n+.5|0);let r=t[2];return r!=(0|r)&&(r=r+.5|0),"rgba("+e+","+n+","+r+","+(void 0===t[3]?1:Math.round(1e3*t[3])/1e3)+")"}function PY(t){return t[0]>0&&t[1]>0}function AY(t,e){return Array.isArray(t)?t:(void 0===e?e=[t,t]:(e[0]=t,e[1]=t),e)}let OY=0;const FY=1<e)throw new Error(`expected ${e===1/0?`${t} or more`:`${t} to ${e}`} arguments for ${r}, got ${i}`)}}function ZX(t,e,n){const r=t.length-1,i=new Array(r);for(let s=0;s{for(let e=0;e{for(let i=0;i{const r=t.args;let i=n.properties[e];for(let t=1,e=r.length;tt.variables[e];case qX:return n=>{const r=t.args;if(!(e in n.properties))return!1;let i=n.properties[e];for(let t=1,e=r.length;tt.featureId;case tX:return t=>t.geometryType;case QY:{const e=t.args.map(t=>eJ(t));return t=>"".concat(...e.map(e=>e(t).toString()))}case sX:return t=>t.resolution;case nX:case rX:case LX:case OX:case"!":return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{for(let e=0;e{for(let e=0;e{const e=r[0](t),n=r[1](t),i=r[2](t);return e>=n&&e<=i};case OX:return t=>{const e=r[0](t);for(let i=1;i!r[0](t);default:throw new Error(`Unsupported logical operator ${e}`)}}(t);case lX:case cX:case"<":case pX:case">":case hX:return function(t){const e=t.operator,n=eJ(t.args[0]),r=eJ(t.args[1]);switch(e){case lX:return t=>n(t)===r(t);case cX:return t=>n(t)!==r(t);case"<":return t=>n(t)n(t)<=r(t);case">":return t=>n(t)>r(t);case hX:return t=>n(t)>=r(t);default:throw new Error(`Unsupported comparison operator ${e}`)}}(t);case"*":case"/":case"+":case"-":case vX:case"%":case"^":case _X:case xX:case CX:case SX:case kX:case EX:case TX:case RX:return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{let e=1;for(let i=0;ir[0](t)/r[1](t);case"+":return t=>{let e=0;for(let i=0;ir[0](t)-r[1](t);case vX:return t=>{const e=r[0](t),n=r[1](t);if(ei?i:e};case"%":return t=>r[0](t)%r[1](t);case"^":return t=>Math.pow(r[0](t),r[1](t));case _X:return t=>Math.abs(r[0](t));case xX:return t=>Math.floor(r[0](t));case CX:return t=>Math.ceil(r[0](t));case SX:return t=>Math.round(r[0](t));case kX:return t=>Math.sin(r[0](t));case EX:return t=>Math.cos(r[0](t));case TX:return 2===n?t=>Math.atan2(r[0](t),r[1](t)):t=>Math.atan(r[0](t));case RX:return t=>Math.sqrt(r[0](t));default:throw new Error(`Unsupported numeric operator ${e}`)}}(t);case AX:return function(t){const e=t.args.length,n=new Array(e);for(let r=0;r{for(let r=0;r{const r=n[0](t);for(let i=1;i{const r=n[0](t),i=n[1](t);let s,o;for(let a=2;a=i)return 2===a?l:c?rJ(r,i,s,o,e,l):nJ(r,i,s,o,e,l);s=e,o=l}return o}}(t);case $X:return function(t){const e=t.operator,n=t.args.length,r=new Array(n);for(let i=0;i{const n=r[0](e);return t.args[0].type===NY?IY(n):n.toString()};throw new Error(`Unsupported convert operator ${e}`)}(t);default:throw new Error(`Unsupported operator ${e}`)}}function nJ(t,e,n,r,i,s){const o=i-n;if(0===o)return r;const a=e-n;return r+(1===t?a/o:(Math.pow(t,a)-1)/(Math.pow(t,o)-1))*(s-r)}function rJ(t,e,n,r,i,s){if(0===i-n)return r;const o=RY(r),a=RY(s);let l=a[2]-o[2];return l>180?l-=360:l<-180&&(l+=360),function(t){const e=(t[0]+16)/116,n=t[1],r=t[2]*Math.PI/180,i=kY(e),s=kY(e+n/500*Math.cos(r)),o=kY(e-n/200*Math.sin(r)),a=SY(3.021973625*s-1.617392459*i-.404875592*o),l=SY(-.943766287*s+1.916279586*i+.027607165*o),c=SY(.069407491*s-.22898585*i+1.159737864*o);return[YV(a+.5|0,0,255),YV(l+.5|0,0,255),YV(c+.5|0,0,255),t[3]]}([nJ(t,e,n,o[0],i,a[0]),nJ(t,e,n,o[1],i,a[1]),o[2]+nJ(t,e,n,0,i,l),nJ(t,e,n,r[3],i,s[3])])}class iJ extends dV{constructor(t,e,n,r){super(),this.extent=t,this.pixelRatio_=n,this.resolution=e,this.state="function"==typeof r?0:r,this.image_=null,this.loader="function"==typeof r?r:null}changed(){this.dispatchEvent(Vq)}getExtent(){return this.extent}getImage(){return this.image_}getPixelRatio(){return this.pixelRatio_}getResolution(){return this.resolution}getState(){return this.state}load(){if(0==this.state&&this.loader){this.state=1,this.changed();const t=this.getResolution(),e=Array.isArray(t)?t[0]:t;lV(()=>this.loader(this.getExtent(),e,this.getPixelRatio())).then(t=>{"image"in t&&(this.image_=t.image),"extent"in t&&(this.extent=t.extent),"resolution"in t&&(this.resolution=t.resolution),"pixelRatio"in t&&(this.pixelRatio_=t.pixelRatio),(t instanceof HTMLImageElement||OV&&t instanceof ImageBitmap||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)&&(this.image_=t),this.state=2}).catch(t=>{this.state=3,console.error(t)}).finally(()=>this.changed())}}setImage(t){this.image_=t}setResolution(t){this.resolution=t}}function sJ(t,e,n){return e+":"+t+":"+(n?LY(n):"null")}const oJ=new class{constructor(){this.cache_={},this.patternCache_={},this.cacheSize_=0,this.maxCacheSize_=1024}clear(){this.cache_={},this.patternCache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let t=0;for(const e in this.cache_){const n=this.cache_[e];3&t++||n.hasListener()||(delete this.cache_[e],delete this.patternCache_[e],--this.cacheSize_)}}}get(t,e,n){const r=sJ(t,e,n);return r in this.cache_?this.cache_[r]:null}getPattern(t,e,n){const r=sJ(t,e,n);return r in this.patternCache_?this.patternCache_[r]:null}set(t,e,n,r,i){const s=sJ(t,e,n),o=s in this.cache_;this.cache_[s]=r,i&&(0===r.getImageState()&&r.load(),1===r.getImageState()?r.ready().then(()=>{this.patternCache_[s]=FK().createPattern(r.getImage(1),"repeat")}):this.patternCache_[s]=FK().createPattern(r.getImage(1),"repeat")),o||++this.cacheSize_}setSize(t){this.maxCacheSize_=t,this.expire()}};let aJ=null;class lJ extends dV{constructor(t,e,n,r,i){super(),this.hitDetectionImage_=null,this.image_=t,this.crossOrigin_=n,this.canvas_={},this.color_=i,this.imageState_=void 0===r?0:r,this.size_=t&&t.width&&t.height?[t.width,t.height]:null,this.src_=e,this.tainted_,this.ready_=null}initializeImage_(){this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)}isTainted_(){if(void 0===this.tainted_&&2===this.imageState_){aJ||(aJ=AK(1,1,void 0,{willReadFrequently:!0})),aJ.drawImage(this.image_,0,0);try{aJ.getImageData(0,0,1,1),this.tainted_=!1}catch{aJ=null,this.tainted_=!0}}return!0===this.tainted_}dispatchChangeEvent_(){this.dispatchEvent(Vq)}handleImageError_(){this.imageState_=3,this.dispatchChangeEvent_()}handleImageLoad_(){this.imageState_=2,this.size_=[this.image_.width,this.image_.height],this.dispatchChangeEvent_()}getImage(t){return this.image_||this.initializeImage_(),this.replaceColor_(t),this.canvas_[t]?this.canvas_[t]:this.image_}getPixelRatio(t){return this.replaceColor_(t),this.canvas_[t]?t:1}getImageState(){return this.imageState_}getHitDetectionImage(){if(this.image_||this.initializeImage_(),!this.hitDetectionImage_)if(this.isTainted_()){const t=this.size_[0],e=this.size_[1],n=AK(t,e);n.fillRect(0,0,t,e),this.hitDetectionImage_=n.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_}getSize(){return this.size_}getSrc(){return this.src_}load(){if(0===this.imageState_){this.image_||this.initializeImage_(),this.imageState_=1;try{void 0!==this.src_&&(this.image_.src=this.src_)}catch{this.handleImageError_()}this.image_ instanceof HTMLImageElement&&(t=this.image_,e=this.src_,e&&(t.src=e),t.src&&AV?new Promise((e,n)=>t.decode().then(()=>e(t)).catch(r=>t.complete&&t.width?e(t):n(r))):function(t){return new Promise((e,n)=>{function r(){s(),e(t)}function i(){s(),n(new Error("Image load error"))}function s(){t.removeEventListener("load",r),t.removeEventListener("error",i)}t.addEventListener("load",r),t.addEventListener("error",i)})}(t)).then(t=>{this.image_=t,this.handleImageLoad_()}).catch(this.handleImageError_.bind(this))}var t,e}replaceColor_(t){if(!this.color_||this.canvas_[t]||2!==this.imageState_)return;const e=this.image_,n=AK(Math.ceil(e.width*t),Math.ceil(e.height*t)),r=n.canvas;var i;n.scale(t,t),n.drawImage(e,0,0),n.globalCompositeOperation="multiply",n.fillStyle="string"==typeof(i=this.color_)?i:IY(i),n.fillRect(0,0,r.width/t,r.height/t),n.globalCompositeOperation="destination-in",n.drawImage(e,0,0),this.canvas_[t]=r}ready(){return this.ready_||(this.ready_=new Promise(t=>{if(2===this.imageState_||3===this.imageState_)t();else{const e=()=>{2!==this.imageState_&&3!==this.imageState_||(this.removeEventListener(Vq,e),t())};this.addEventListener(Vq,e)}})),this.ready_}}function cJ(t,e,n,r,i,s){let o=void 0===e?void 0:oJ.get(e,n,i);return o||(o=new lJ(t,t&&"src"in t?t.src||void 0:e,n,r,i),oJ.set(e,n,i,o,s)),s&&o&&!oJ.getPattern(e,n,i)&&oJ.set(e,n,i,o,s),o}function uJ(t){return t?Array.isArray(t)?IY(t):"object"==typeof t&&"src"in t?function(t){if(!t.offset||!t.size)return oJ.getPattern(t.src,"anonymous",t.color);const e=t.src+":"+t.offset,n=oJ.getPattern(e,void 0,t.color);if(n)return n;const r=oJ.get(t.src,"anonymous",null);if(2!==r.getImageState())return null;const i=AK(t.size[0],t.size[1]);return i.drawImage(r.getImage(1),t.offset[0],t.offset[1],t.size[0],t.size[1],0,0,t.size[0],t.size[1]),cJ(i.canvas,e,void 0,2,t.color,!0),oJ.getPattern(e,void 0,t.color)}(t):t:null}const hJ="10px sans-serif",dJ="#000",pJ="round",fJ=[],gJ="round",mJ="#000",yJ="center",vJ="middle",bJ=[0,0,0,0],wJ=new _V;let _J,xJ=null;const CJ={},SJ=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"]);function kJ(t,e,n){return`${t} ${e} 16px "${n}"`}const EJ=function(){const t=100;let e,n;async function r(t){await n.ready;const e=await n.load(t);if(0===e.length)return!1;const r=PK(t),i=r.families[0].toLowerCase(),s=r.weight;return e.some(t=>{const e=t.family.replace(/^['"]|['"]$/g,"").toLowerCase(),n=IK[t.weight]||t.weight;return e===i&&t.style===r.style&&n==s})}async function i(){await n.ready;let s=!0;const o=wJ.getProperties(),a=Object.keys(o).filter(e=>o[e]=0;--e){const n=a[e];let i=o[n];iMath.max(e,MJ(t,n)),0);return n[e]=r,r}class IJ{constructor(t){this.opacity_=t.opacity,this.rotateWithView_=t.rotateWithView,this.rotation_=t.rotation,this.scale_=t.scale,this.scaleArray_=AY(t.scale),this.displacement_=t.displacement,this.declutterMode_=t.declutterMode}clone(){const t=this.getScale();return new IJ({opacity:this.getOpacity(),scale:Array.isArray(t)?t.slice():t,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getOpacity(){return this.opacity_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getDisplacement(){return this.displacement_}getDeclutterMode(){return this.declutterMode_}getAnchor(){return yV()}getImage(t){return yV()}getHitDetectionImage(){return yV()}getPixelRatio(t){return 1}getImageState(){return yV()}getImageSize(){return yV()}getOrigin(){return yV()}getSize(){return yV()}setDisplacement(t){this.displacement_=t}setOpacity(t){this.opacity_=t}setRotateWithView(t){this.rotateWithView_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=AY(t)}listenImageChange(t){yV()}load(){yV()}unlistenImageChange(t){yV()}ready(){return Promise.resolve()}}class PJ extends IJ{constructor(t){super({opacity:1,rotateWithView:void 0!==t.rotateWithView&&t.rotateWithView,rotation:void 0!==t.rotation?t.rotation:0,scale:void 0!==t.scale?t.scale:1,displacement:void 0!==t.displacement?t.displacement:[0,0],declutterMode:t.declutterMode}),this.hitDetectionCanvas_=null,this.fill_=void 0!==t.fill?t.fill:null,this.origin_=[0,0],this.points_=t.points,this.radius=t.radius,this.radius2_=t.radius2,this.angle_=void 0!==t.angle?t.angle:0,this.stroke_=void 0!==t.stroke?t.stroke:null,this.size_,this.renderOptions_,this.imageState_=this.fill_&&this.fill_.loading()?1:2,1===this.imageState_&&this.ready().then(()=>this.imageState_=2),this.render()}clone(){const t=this.getScale(),e=new PJ({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return e.setOpacity(this.getOpacity()),e}getAnchor(){const t=this.size_,e=this.getDisplacement(),n=this.getScaleArray();return[t[0]/2-e[0]/n[0],t[1]/2+e[1]/n[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(t){this.fill_=t,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.createHitDetectionCanvas_(this.renderOptions_)),this.hitDetectionCanvas_}getImage(t){const e=this.fill_?.getKey(),n=`${t},${this.angle_},${this.radius},${this.radius2_},${this.points_},${e}`+Object.values(this.renderOptions_).join(",");let r=oJ.get(n,null,null)?.getImage(1);if(!r){const e=this.renderOptions_,i=Math.ceil(e.size*t),s=AK(i,i);this.draw_(e,s,t),r=s.canvas,oJ.set(n,null,null,new lJ(r,void 0,null,2,null))}return r}getPixelRatio(t){return t}getImageSize(){return this.size_}getImageState(){return this.imageState_}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t,this.render()}listenImageChange(t){}load(){}unlistenImageChange(t){}calculateLineJoinSize_(t,e,n){if(0===e||this.points_===1/0||"bevel"!==t&&"miter"!==t)return e;let r=this.radius,i=void 0===this.radius2_?r:this.radius2_;if(r{this.patternImage_=null}),0===e.getImageState()&&e.load(),1===e.getImageState()&&(this.patternImage_=e)}this.color_=t}getKey(){const t=this.getColor();return t?t instanceof CanvasPattern||t instanceof CanvasGradient?bV(t):"object"==typeof t&&"src"in t?t.src+":"+t.offset:LY(t).toString():""}loading(){return!!this.patternImage_}ready(){return this.patternImage_?this.patternImage_.ready():Promise.resolve()}}function FJ(t,e,n,r){return void 0!==n&&void 0!==r?[n/t,r/e]:void 0!==n?n/t:void 0!==r?r/e:1}class zJ extends IJ{constructor(t){const e=void 0!==(t=t||{}).opacity?t.opacity:1,n=void 0!==t.rotation?t.rotation:0,r=void 0!==t.scale?t.scale:1,i=void 0!==t.rotateWithView&&t.rotateWithView;super({opacity:e,rotation:n,scale:r,displacement:void 0!==t.displacement?t.displacement:[0,0],rotateWithView:i,declutterMode:t.declutterMode}),this.anchor_=void 0!==t.anchor?t.anchor:[.5,.5],this.normalizedAnchor_=null,this.anchorOrigin_=void 0!==t.anchorOrigin?t.anchorOrigin:"top-left",this.anchorXUnits_=void 0!==t.anchorXUnits?t.anchorXUnits:"fraction",this.anchorYUnits_=void 0!==t.anchorYUnits?t.anchorYUnits:"fraction",this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null;const s=void 0!==t.img?t.img:null;let o,a=t.src;if(WV(!(void 0!==a&&s),"`image` and `src` cannot be provided at the same time"),void 0!==a&&0!==a.length||!s||(a=s.src||bV(s)),WV(void 0!==a&&a.length>0,"A defined and non-empty `src` or `image` must be provided"),WV(!((void 0!==t.width||void 0!==t.height)&&void 0!==t.scale),"`width` or `height` cannot be provided together with `scale`"),void 0!==t.src?o=0:void 0!==s&&(o="complete"in s?s.complete?s.src?2:0:1:2),this.color_=void 0!==t.color?LY(t.color):null,this.iconImage_=cJ(s,a,this.crossOrigin_,o,this.color_),this.offset_=void 0!==t.offset?t.offset:[0,0],this.offsetOrigin_=void 0!==t.offsetOrigin?t.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==t.size?t.size:null,this.initialOptions_,void 0!==t.width||void 0!==t.height){let e,n;if(t.size)[e,n]=t.size;else{const r=this.getImage(1);if(r.width&&r.height)e=r.width,n=r.height;else if(r instanceof HTMLImageElement){this.initialOptions_=t;const e=()=>{if(this.unlistenImageChange(e),!this.initialOptions_)return;const n=this.iconImage_.getSize();this.setScale(FJ(n[0],n[1],t.width,t.height))};return void this.listenImageChange(e)}}void 0!==e&&this.setScale(FJ(e,n,t.width,t.height))}}clone(){let t,e,n;return this.initialOptions_?(e=this.initialOptions_.width,n=this.initialOptions_.height):(t=this.getScale(),t=Array.isArray(t)?t.slice():t),new zJ({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:t,width:e,height:n,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let t=this.normalizedAnchor_;if(!t){t=this.anchor_;const e=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!e)return null;t=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(t[0]*=e[0]),"fraction"==this.anchorYUnits_&&(t[1]*=e[1])}if("top-left"!=this.anchorOrigin_){if(!e)return null;t===this.anchor_&&(t=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[0]=-t[0]+e[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[1]=-t[1]+e[1])}this.normalizedAnchor_=t}const e=this.getDisplacement(),n=this.getScaleArray();return[t[0]-e[0]/n[0],t[1]+e[1]/n[1]]}setAnchor(t){this.anchor_=t,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(t){return this.iconImage_.getImage(t)}getPixelRatio(t){return this.iconImage_.getPixelRatio(t)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let t=this.offset_;if("top-left"!=this.offsetOrigin_){const e=this.getSize(),n=this.iconImage_.getSize();if(!e||!n)return null;t=t.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[0]=n[0]-e[0]-t[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[1]=n[1]-e[1]-t[1])}return this.origin_=t,this.origin_}getSrc(){return this.iconImage_.getSrc()}setSrc(t){this.iconImage_=cJ(null,t,this.crossOrigin_,0,this.color_)}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const t=this.getScaleArray();return this.size_?this.size_[0]*t[0]:2==this.iconImage_.getImageState()?this.iconImage_.getSize()[0]*t[0]:void 0}getHeight(){const t=this.getScaleArray();return this.size_?this.size_[1]*t[1]:2==this.iconImage_.getImageState()?this.iconImage_.getSize()[1]*t[1]:void 0}setScale(t){delete this.initialOptions_,super.setScale(t)}listenImageChange(t){this.iconImage_.addEventListener(Vq,t)}load(){this.iconImage_.load()}unlistenImageChange(t){this.iconImage_.removeEventListener(Vq,t)}ready(){return this.iconImage_.ready()}}class DJ{constructor(t){t=t||{},this.color_=void 0!==t.color?t.color:null,this.lineCap_=t.lineCap,this.lineDash_=void 0!==t.lineDash?t.lineDash:null,this.lineDashOffset_=t.lineDashOffset,this.lineJoin_=t.lineJoin,this.miterLimit_=t.miterLimit,this.width_=t.width}clone(){const t=this.getColor();return new DJ({color:Array.isArray(t)?t.slice():t||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(t){this.color_=t}setLineCap(t){this.lineCap_=t}setLineDash(t){this.lineDash_=t}setLineDashOffset(t){this.lineDashOffset_=t}setLineJoin(t){this.lineJoin_=t}setMiterLimit(t){this.miterLimit_=t}setWidth(t){this.width_=t}}class NJ{constructor(t){t=t||{},this.geometry_=null,this.geometryFunction_=UJ,void 0!==t.geometry&&this.setGeometry(t.geometry),this.fill_=void 0!==t.fill?t.fill:null,this.image_=void 0!==t.image?t.image:null,this.renderer_=void 0!==t.renderer?t.renderer:null,this.hitDetectionRenderer_=void 0!==t.hitDetectionRenderer?t.hitDetectionRenderer:null,this.stroke_=void 0!==t.stroke?t.stroke:null,this.text_=void 0!==t.text?t.text:null,this.zIndex_=t.zIndex}clone(){let t=this.getGeometry();return t&&"object"==typeof t&&(t=t.clone()),new NJ({geometry:t??void 0,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer()??void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(t){this.renderer_=t}setHitDetectionRenderer(t){this.hitDetectionRenderer_=t}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(t){this.fill_=t}getImage(){return this.image_}setImage(t){this.image_=t}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t}getText(){return this.text_}setText(t){this.text_=t}getZIndex(){return this.zIndex_}setGeometry(t){"function"==typeof t?this.geometryFunction_=t:"string"==typeof t?this.geometryFunction_=function(e){return e.get(t)}:t?void 0!==t&&(this.geometryFunction_=function(){return t}):this.geometryFunction_=UJ,this.geometry_=t}setZIndex(t){this.zIndex_=t}}let jJ=null;function BJ(){if(!jJ){const t=new OJ({color:"rgba(255,255,255,0.4)"}),e=new DJ({color:"#3399CC",width:1.25});jJ=[new NJ({image:new AJ({fill:t,stroke:e,radius:5}),fill:t,stroke:e})]}return jJ}function UJ(t){return t.getGeometry()}let $J=class t{constructor(t){t=t||{},this.font_=t.font,this.rotation_=t.rotation,this.rotateWithView_=t.rotateWithView,this.keepUpright_=t.keepUpright,this.scale_=t.scale,this.scaleArray_=AY(void 0!==t.scale?t.scale:1),this.text_=t.text,this.textAlign_=t.textAlign,this.justify_=t.justify,this.repeat_=t.repeat,this.textBaseline_=t.textBaseline,this.fill_=void 0!==t.fill?t.fill:new OJ({color:"#333"}),this.maxAngle_=void 0!==t.maxAngle?t.maxAngle:Math.PI/4,this.placement_=void 0!==t.placement?t.placement:"point",this.overflow_=!!t.overflow,this.stroke_=void 0!==t.stroke?t.stroke:null,this.offsetX_=void 0!==t.offsetX?t.offsetX:0,this.offsetY_=void 0!==t.offsetY?t.offsetY:0,this.backgroundFill_=t.backgroundFill?t.backgroundFill:null,this.backgroundStroke_=t.backgroundStroke?t.backgroundStroke:null,this.padding_=void 0===t.padding?null:t.padding,this.declutterMode_=t.declutterMode}clone(){const e=this.getScale();return new t({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),keepUpright:this.getKeepUpright(),scale:Array.isArray(e)?e.slice():e,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()instanceof OJ?this.getFill().clone():this.getFill(),stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0,declutterMode:this.getDeclutterMode()})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getKeepUpright(){return this.keepUpright_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}getDeclutterMode(){return this.declutterMode_}setOverflow(t){this.overflow_=t}setFont(t){this.font_=t}setMaxAngle(t){this.maxAngle_=t}setOffsetX(t){this.offsetX_=t}setOffsetY(t){this.offsetY_=t}setPlacement(t){this.placement_=t}setRepeat(t){this.repeat_=t}setRotateWithView(t){this.rotateWithView_=t}setKeepUpright(t){this.keepUpright_=t}setFill(t){this.fill_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=AY(void 0!==t?t:1)}setStroke(t){this.stroke_=t}setText(t){this.text_=t}setTextAlign(t){this.textAlign_=t}setJustify(t){this.justify_=t}setTextBaseline(t){this.textBaseline_=t}setBackgroundFill(t){this.backgroundFill_=t}setBackgroundStroke(t){this.backgroundStroke_=t}setPadding(t){this.padding_=t}};function qJ(){return!0}function VJ(t){const e=ZY(),n=function(t,e){const n=t.length,r=new Array(n);for(let i=0;inull;r=JJ(t,e+"fill-color",n)}if(!r)return null;const i=new OJ;return function(t){const e=r(t);return e===dY?null:(i.setColor(e),i)}}function KJ(t,e,n){const r=ZJ(t,e+"stroke-width",n),i=JJ(t,e+"stroke-color",n);if(!r&&!i)return null;const s=YJ(t,e+"stroke-line-cap",n),o=YJ(t,e+"stroke-line-join",n),a=QJ(t,e+"stroke-line-dash",n),l=ZJ(t,e+"stroke-line-dash-offset",n),c=ZJ(t,e+"stroke-miter-limit",n),u=new DJ;return function(t){if(i){const e=i(t);if(e===dY)return null;u.setColor(e)}if(r&&u.setWidth(r(t)),s){const e=s(t);if("butt"!==e&&"round"!==e&&"square"!==e)throw new Error("Expected butt, round, or square line cap");u.setLineCap(e)}if(o){const e=o(t);if("bevel"!==e&&"round"!==e&&"miter"!==e)throw new Error("Expected bevel, round, or miter line join");u.setLineJoin(e)}return a&&u.setLineDash(a(t)),l&&u.setLineDashOffset(l(t)),c&&u.setMiterLimit(c(t)),u}}function ZJ(t,e,n){if(!(e in t))return;const r=tJ(t[e],zY,n);return function(t){return cQ(r(t),e)}}function YJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],DY,n);return function(t){return lQ(r(t),e)}}function XJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],FY,n);return function(t){const n=r(t);if("boolean"!=typeof n)throw new Error(`Expected a boolean for ${e}`);return n}}function JJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],NY,n);return function(t){return uQ(r(t),e)}}function QJ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){return aQ(r(t),e)}}function tQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){const n=aQ(r(t),e);if(2!==n.length)throw new Error(`Expected two numbers for ${e}`);return n}}function eQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY,n);return function(t){return hQ(r(t),e)}}function nQ(t,e,n){if(!(e in t))return null;const r=tJ(t[e],jY|zY,n);return function(t){return function(t,e){return"number"==typeof t?t:hQ(t,e)}(r(t),e)}}function rQ(t,e){const n=t[e];if(void 0!==n){if("number"!=typeof n)throw new Error(`Expected a number for ${e}`);return n}}function iQ(t,e){const n=t[e];if(void 0!==n){if("bottom-left"!==n&&"bottom-right"!==n&&"top-left"!==n&&"top-right"!==n)throw new Error(`Expected bottom-left, bottom-right, top-left, or top-right for ${e}`);return n}}function sQ(t,e){const n=t[e];if(void 0!==n){if("pixels"!==n&&"fraction"!==n)throw new Error(`Expected pixels or fraction for ${e}`);return n}}function oQ(t,e){const n=t[e];if(void 0!==n){if("string"!=typeof n)throw new Error(`Expected a string for ${e}`);if("declutter"!==n&&"obstacle"!==n&&"none"!==n)throw new Error(`Expected declutter, obstacle, or none for ${e}`);return n}}function aQ(t,e){if(!Array.isArray(t))throw new Error(`Expected an array for ${e}`);const n=t.length;for(let r=0;r4)throw new Error(`Expected a color with 3 or 4 values for ${e}`);return n}function hQ(t,e){const n=aQ(t,e);if(2!==n.length)throw new Error(`Expected an array of two numbers for ${e}`);return n}const dQ="renderOrder";class pQ extends HZ{constructor(t){t=t||{};const e=Object.assign({},t);delete e.style,delete e.renderBuffer,delete e.updateWhileAnimating,delete e.updateWhileInteracting,super(e),this.declutter_=t.declutter?String(t.declutter):void 0,this.renderBuffer_=void 0!==t.renderBuffer?t.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(t.style),this.updateWhileAnimating_=void 0!==t.updateWhileAnimating&&t.updateWhileAnimating,this.updateWhileInteracting_=void 0!==t.updateWhileInteracting&&t.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(t){return super.getFeatures(t)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(dQ)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(t,e){const n=this.getDeclutter();n in t.declutter==0&&(t.declutter[n]=new XZ(9)),this.getRenderer().renderDeclutter(t,e)}setRenderOrder(t){this.set(dQ,t)}setStyle(t){this.style_=void 0===t?BJ:t;const e=function(t){if(void 0===t)return BJ;if(!t)return null;if("function"==typeof t)return t;if(t instanceof NJ)return t;if(!Array.isArray(t))return WJ([t]);if(0===t.length)return[];const e=t.length,n=t[0];if(n instanceof NJ){const n=new Array(e);for(let r=0;r=0;--r){const i=f[r],s=i.layer;if(s.hasRenderer()&&GZ(i,c)&&o.call(a,s)){const r=s.getRenderer(),o=s.getSource();if(r&&o){const s=o.getWrapX()?d:t,a=u.bind(null,i.managed);y[0]=s[0]+p[b][0],y[1]=s[1]+p[b][1],l=r.forEachFeatureAtCoordinate(y,e,n,a,m)}if(l)return l}}if(0===m.length)return;const v=1/m.length;return m.forEach((t,e)=>t.distanceSq+=e*v),m.sort((t,e)=>t.distanceSq-e.distanceSq),m.some(t=>l=t.callback(t.feature,t.layer,t.geometry)),l}hasFeatureAtCoordinate(t,e,n,r,i,s){return void 0!==this.forEachFeatureAtCoordinate(t,e,n,r,iV,this,i,s)}getMap(){return this.map_}renderFrame(t){yV()}scheduleExpireIconCache(t){oJ.canExpireCache()&&t.postRenderFunctions.push(mQ)}}function mQ(){oJ.expire()}class yQ extends gQ{constructor(t){super(t),this.fontChangeListenerKey_=pV(wJ,qq,t.redrawText,t),this.element_=PV?UK():document.createElement("div");const e=this.element_.style;e.position="absolute",e.width="100%",e.height="100%",e.zIndex="0",this.element_.className=EK+" ol-layers";const n=t.getViewport();n&&n.insertBefore(this.element_,n.firstChild||null),this.children_=[],this.renderedVisible_=!0}dispatchRenderEvent(t,e){const n=this.getMap();if(n.hasListener(t)){const r=new fQ(t,void 0,e);n.dispatchEvent(r)}}disposeInternal(){gV(this.fontChangeListenerKey_),this.element_.remove(),super.disposeInternal()}renderFrame(t){if(!t)return void(this.renderedVisible_&&(this.element_.style.display="none",this.renderedVisible_=!1));this.calculateMatrices2D(t),this.dispatchRenderEvent(VZ,t);const e=t.layerStatesArray.sort((t,e)=>t.zIndex-e.zIndex);e.some(t=>t.layer instanceof pQ&&t.layer.getDeclutter())&&(t.declutter={});const n=t.viewState;this.children_.length=0;const r=[];let i=null;for(let o=0,a=e.length;o0)&&(t.fillStyle=r,t.fillRect(0,0,s.width,s.height)),$K(n)&&n.width>0){const r=e.style.opacity||n.style.opacity;t.globalAlpha=""===r?1:Number(r);const i=n.style.transform;if(i)t.setTransform(...CG(i));else{const e=parseFloat(n.style.width)/n.width,r=parseFloat(n.style.height)/n.height;t.setTransform(e,0,0,r,0,0)}t.drawImage(n,0,0)}}t.globalAlpha=1,t.setTransform(1,0,0,1,0,0)}this.dispatchRenderEvent("postcompose",t),this.renderedVisible_||(this.element_.style.display="",this.renderedVisible_=!0),this.scheduleExpireIconCache(t)}declutter(t,e){if(t.declutter){for(let n=e.length-1;n>=0;--n){const r=e[n],i=r.layer;i.getDeclutter()&&i.renderDeclutter(t,r)}e.forEach(e=>e.layer.renderDeferred(t))}}}function vQ(t){t instanceof HZ?t.setMapInternal(null):t instanceof UZ&&t.getLayers().forEach(vQ)}function bQ(t,e){if(t instanceof HZ)t.setMapInternal(e);else if(t instanceof UZ){const n=t.getLayers().getArray();for(let t=0,r=n.length;tthis.updateSize())),this.controls=e.controls||(PV?new SV:GK()),this.interactions=e.interactions||(PV?new SV:EZ({onFocusOnly:!0})),this.overlays_=e.overlays,this.overlayIdIndex_={},this.renderer_=null,this.postRenderFunctions_=[],this.tileQueue_=new KV(this.getTilePriority.bind(this),this.handleTileChange_.bind(this)),this.addChangeListener(UV,this.handleLayerGroupChanged_),this.addChangeListener(VV,this.handleViewChanged_),this.addChangeListener($V,this.handleSizeChanged_),this.addChangeListener(qV,this.handleTargetChanged_),this.setProperties(e.values);const n=this;!t.view||t.view instanceof _K||t.view.then(function(t){n.setView(new _K(t))}),this.controls.addEventListener(Uq,t=>{t.element.setMap(this)}),this.controls.addEventListener($q,t=>{t.element.setMap(null)}),this.interactions.addEventListener(Uq,t=>{t.element.setMap(this)}),this.interactions.addEventListener($q,t=>{t.element.setMap(null)}),this.overlays_.addEventListener(Uq,t=>{this.addOverlayInternal_(t.element)}),this.overlays_.addEventListener($q,t=>{const e=t.element.getId();void 0!==e&&delete this.overlayIdIndex_[e.toString()],t.element.setMap(null)}),this.controls.forEach(t=>{t.setMap(this)}),this.interactions.forEach(t=>{t.setMap(this)}),this.overlays_.forEach(this.addOverlayInternal_.bind(this))}addControl(t){this.getControls().push(t)}addInteraction(t){this.getInteractions().push(t)}addLayer(t){this.getLayerGroup().getLayers().push(t)}handleLayerAdd_(t){bQ(t.layer,this)}addOverlay(t){this.getOverlays().push(t)}addOverlayInternal_(t){const e=t.getId();void 0!==e&&(this.overlayIdIndex_[e.toString()]=t),t.setMap(this)}disposeInternal(){this.controls.clear(),this.interactions.clear(),this.overlays_.clear(),this.resizeObserver_?.disconnect(),this.setTarget(null),super.disposeInternal()}forEachFeatureAtPixel(t,e,n){if(!this.frameState_||!this.renderer_)return;const r=this.getCoordinateFromPixelInternal(t),i=void 0!==(n=void 0!==n?n:{}).hitTolerance?n.hitTolerance:0,s=void 0!==n.layerFilter?n.layerFilter:iV,o=!1!==n.checkWrapped;return this.renderer_.forEachFeatureAtCoordinate(r,this.frameState_,i,o,e,null,s,null)}getFeaturesAtPixel(t,e){const n=[];return this.forEachFeatureAtPixel(t,function(t){n.push(t)},e),n}getAllLayers(){const t=[];return function e(n){n.forEach(function(n){n instanceof UZ?e(n.getLayers()):t.push(n)})}(this.getLayers()),t}hasFeatureAtPixel(t,e){if(!this.frameState_||!this.renderer_)return!1;const n=this.getCoordinateFromPixelInternal(t),r=void 0!==(e=void 0!==e?e:{}).layerFilter?e.layerFilter:iV,i=void 0!==e.hitTolerance?e.hitTolerance:0,s=!1!==e.checkWrapped;return this.renderer_.hasFeatureAtCoordinate(n,this.frameState_,i,s,r,null)}getEventCoordinate(t){return this.getCoordinateFromPixel(this.getEventPixel(t))}getEventCoordinateInternal(t){return this.getCoordinateFromPixelInternal(this.getEventPixel(t))}getEventPixel(t){const e=this.viewport_.getBoundingClientRect(),n=this.getSize(),r=e.width/n[0],i=e.height/n[1],s="changedTouches"in t?t.changedTouches[0]:t;return[(s.clientX-e.left)/r,(s.clientY-e.top)/i]}getTarget(){return this.get(qV)}getTargetElement(){return this.targetElement_}getCoordinateFromPixel(t){return lG(this.getCoordinateFromPixelInternal(t),this.getView().getProjection())}getCoordinateFromPixelInternal(t){const e=this.frameState_;return e?vG(e.pixelToCoordinateTransform,t.slice()):null}getControls(){return this.controls}getOverlays(){return this.overlays_}getOverlayById(t){const e=this.overlayIdIndex_[t.toString()];return void 0!==e?e:null}getInteractions(){return this.interactions}getLayerGroup(){return this.get(UV)}setLayers(t){const e=this.getLayerGroup();if(t instanceof SV)return void e.setLayers(t);const n=e.getLayers();n.clear(),n.extend(t)}getLayers(){return this.getLayerGroup().getLayers()}getLoadingOrNotReady(){const t=this.getLayerGroup().getLayerStatesArray();for(let e=0,n=t.length;e=0;n--){const r=e[n];if(r.getMap()===this&&r.getActive()&&this.getTargetElement()&&(!r.handleEvent(t)||t.propagationStopped))break}}}handlePostRender(){const t=this.frameState_,e=this.tileQueue_;if(!e.isEmpty()){let n=this.maxTilesLoading_,r=n;if(t){const e=t.viewHints;if(e[0]||e[1]){const e=Date.now()-t.time>8;n=e?0:8,r=e?0:2}}e.getTilesLoading(){this.postRenderTimeoutHandle_=void 0,this.handlePostRender()},0))}setLayerGroup(t){const e=this.getLayerGroup();e&&this.handleLayerRemove_(new jZ("removelayer",e)),this.set(UV,t)}setSize(t){this.set($V,t)}setTarget(t){this.set(qV,t)}setView(t){if(!t||t instanceof _K)return void this.set(VV,t);this.set(VV,new _K);const e=this;t.then(function(t){e.setView(new _K(t))})}updateSize(){const t=this.getTargetElement();let e;if(t){let n,r;if($K(t))n=t.width,r=t.height;else{const e=getComputedStyle(t);n=t.offsetWidth-parseFloat(e.borderLeftWidth)-parseFloat(e.paddingLeft)-parseFloat(e.paddingRight)-parseFloat(e.borderRightWidth),r=t.offsetHeight-parseFloat(e.borderTopWidth)-parseFloat(e.paddingTop)-parseFloat(e.paddingBottom)-parseFloat(e.borderBottomWidth)}isNaN(n)||isNaN(r)||(e=[Math.max(0,n),Math.max(0,r)],!PY(e)&&(t.offsetWidth||t.offsetHeight||t.getClientRects().length)&&tH("No map visible because the map container's width or height are 0."))}const n=this.getSize();!e||n&&rV(e,n)||(this.setSize(e),this.updateViewportSize_(e))}updateViewportSize_(t){const e=this.getView();e&&e.setViewportSize(t)}};const _Q="element",xQ="map",CQ="offset",SQ="position",kQ="positioning";class EQ extends _V{constructor(t){super(),this.on,this.once,this.un,this.options=t,this.id=t.id,this.insertFirst=void 0===t.insertFirst||t.insertFirst,this.stopEvent=void 0===t.stopEvent||t.stopEvent,this.element=document.createElement("div"),this.element.className=void 0!==t.className?t.className:"ol-overlay-container ol-selectable",this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.autoPan=!0===t.autoPan?{}:t.autoPan||void 0,this.rendered={transform_:"",visible:!0},this.mapPostrenderListenerKey=null,this.addChangeListener(_Q,this.handleElementChanged),this.addChangeListener(xQ,this.handleMapChanged),this.addChangeListener(CQ,this.handleOffsetChanged),this.addChangeListener(SQ,this.handlePositionChanged),this.addChangeListener(kQ,this.handlePositioningChanged),void 0!==t.element&&this.setElement(t.element),this.setOffset(void 0!==t.offset?t.offset:[0,0]),this.setPositioning(t.positioning||"top-left"),void 0!==t.position&&this.setPosition(t.position)}getElement(){return this.get(_Q)}getId(){return this.id}getMap(){return this.get(xQ)||null}getOffset(){return this.get(CQ)}getPosition(){return this.get(SQ)}getPositioning(){return this.get(kQ)}handleElementChanged(){BK(this.element);const t=this.getElement();t&&this.element.appendChild(t)}handleMapChanged(){this.mapPostrenderListenerKey&&(this.element?.remove(),gV(this.mapPostrenderListenerKey),this.mapPostrenderListenerKey=null);const t=this.getMap();if(t){this.mapPostrenderListenerKey=pV(t,NV,this.render,this),this.updatePixelPosition();const e=this.stopEvent?t.getOverlayContainerStopEvent():t.getOverlayContainer();this.insertFirst?e.insertBefore(this.element,e.childNodes[0]||null):e.appendChild(this.element),this.performAutoPan()}}render(){this.updatePixelPosition()}handleOffsetChanged(){this.updatePixelPosition()}handlePositionChanged(){this.updatePixelPosition(),this.performAutoPan()}handlePositioningChanged(){this.updatePixelPosition()}setElement(t){this.set(_Q,t)}setMap(t){this.set(xQ,t)}setOffset(t){this.set(CQ,t)}setPosition(t){this.set(SQ,t)}performAutoPan(){this.autoPan&&this.panIntoView(this.autoPan)}panIntoView(t){const e=this.getMap();if(!e||!e.getTargetElement()||!this.get(SQ))return;const n=this.getRect(e.getTargetElement(),e.getSize()),r=this.getElement(),i=this.getRect(r,[DK(r),NK(r)]),s=void 0===(t=t||{}).margin?20:t.margin;if(!fW(n,i)){const r=i[0]-n[0],o=n[2]-i[2],a=i[1]-n[1],l=n[3]-i[3],c=[0,0];if(r<0?c[0]=r-s:o<0&&(c[0]=Math.abs(o)+s),a<0?c[1]=a-s:l<0&&(c[1]=Math.abs(l)+s),0!==c[0]||0!==c[1]){const n=e.getView().getCenterInternal(),r=e.getPixelFromCoordinateInternal(n);if(!r)return;const i=[r[0]+c[0],r[1]+c[1]],s=t.animation||{};e.getView().animateInternal({center:e.getCoordinateFromPixelInternal(i),duration:s.duration,easing:s.easing})}}}getRect(t,e){const n=t.getBoundingClientRect(),r=n.left+window.pageXOffset,i=n.top+window.pageYOffset;return[r,i,r+e[0],i+e[1]]}setPositioning(t){this.set(kQ,t)}setVisible(t){this.rendered.visible!==t&&(this.element.style.display=t?"":"none",this.rendered.visible=t)}updatePixelPosition(){const t=this.getMap(),e=this.getPosition();if(!t||!t.isRendered()||!e)return void this.setVisible(!1);const n=t.getPixelFromCoordinate(e),r=t.getSize();this.updateRenderedPosition(n,r)}updateRenderedPosition(t,e){const n=this.element.style,r=this.getOffset(),i=this.getPositioning();this.setVisible(!0);let s="0%",o="0%";"bottom-right"==i||"center-right"==i||"top-right"==i?s="-100%":"bottom-center"!=i&&"center-center"!=i&&"top-center"!=i||(s="-50%"),"bottom-left"==i||"bottom-center"==i||"bottom-right"==i?o="-100%":"center-left"!=i&&"center-center"!=i&&"center-right"!=i||(o="-50%");const a=`translate(${s}, ${o}) translate(${t[0]+r[0]}px, ${t[1]+r[1]}px)`;this.rendered.transform_!=a&&(this.rendered.transform_=a,n.transform=a)}getOptions(){return this.options}}class TQ extends _V{constructor(t){if(super(),this.on,this.once,this.un,this.id_=void 0,this.geometryName_="geometry",this.style_=null,this.styleFunction_=void 0,this.geometryChangeKey_=null,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),t)if("function"==typeof t.getSimplifiedGeometry){const e=t;this.setGeometry(e)}else{const e=t;this.setProperties(e)}}clone(){const t=new TQ(this.hasProperties()?this.getProperties():null);t.setGeometryName(this.getGeometryName());const e=this.getGeometry();e&&t.setGeometry(e.clone());const n=this.getStyle();return n&&t.setStyle(n),t}getGeometry(){return this.get(this.geometryName_)}getId(){return this.id_}getGeometryName(){return this.geometryName_}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}handleGeometryChange_(){this.changed()}handleGeometryChanged_(){this.geometryChangeKey_&&(gV(this.geometryChangeKey_),this.geometryChangeKey_=null);const t=this.getGeometry();t&&(this.geometryChangeKey_=pV(t,Vq,this.handleGeometryChange_,this)),this.changed()}setGeometry(t){this.set(this.geometryName_,t)}setStyle(t){this.style_=t,this.styleFunction_=t?function(t){if("function"==typeof t)return t;let e;return Array.isArray(t)?e=t:(WV("function"==typeof t.getZIndex,"Expected an `ol/style/Style` or an array of `ol/style/Style.js`"),e=[t]),function(){return e}}(t):void 0,this.changed()}setId(t){this.id_=t,this.changed()}setGeometryName(t){this.removeChangeListener(this.geometryName_,this.handleGeometryChanged_),this.geometryName_=t,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),this.handleGeometryChanged_()}}function RQ(t,e,n,r,i,s,o){let a,l;const c=(n-e)/r;if(1===c)a=e;else if(2===c)a=e,l=i;else if(0!==c){let s=t[e],o=t[e+1],c=0;const u=[0];for(let i=e+r;i>1),i=+n(t[r],e),i<0?s=r+1:(o=r,a=!i);return a?s:~s}(u,h);d<0?(l=(h-u[-d-2])/(u[-d-1]-u[-d-2]),a=e+(-d-2)*r):a=e+d*r}o=o>1?o:2,s=s||new Array(o);for(let u=0;u>1;ia&&(this.instructions.push([4,a,c,t,n,$G,i]),this.hitDetectionInstructions.push([4,a,c,t,r||n,$G,i]));break;case"Point":l=t.getFlatCoordinates(),this.coordinates.push(l[0],l[1]),c=this.coordinates.length,this.instructions.push([4,a,c,t,n,void 0,i]),this.hitDetectionInstructions.push([4,a,c,t,r||n,void 0,i])}this.endGeometry(e)}beginGeometry(t,e,n){this.beginGeometryInstruction1_=[0,e,0,t,n],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[0,e,0,t,n],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const t=this.hitDetectionInstructions;let e;t.reverse();const n=t.length;let r,i,s=-1;for(e=0;ethis.maxLineWidth&&(this.maxLineWidth=e.lineWidth,this.bufferedMaxExtent_=null)}else e.strokeStyle=void 0,e.lineCap=void 0,e.lineDash=null,e.lineDashOffset=void 0,e.lineJoin=void 0,e.lineWidth=void 0,e.miterLimit=void 0;return e}setFillStrokeStyle(t,e){const n=this.state;this.fillStyleToState(t,n),this.strokeStyleToState(e,n)}createFill(t){const e=t.fillStyle,n=[10,e];return"string"!=typeof e&&n.push(t.fillPatternScale),n}applyStroke(t){this.instructions.push(this.createStroke(t))}createStroke(t){return[DQ,t.strokeStyle,t.lineWidth*this.pixelRatio,t.lineCap,t.lineJoin,t.miterLimit,t.lineDash?this.applyPixelRatio(t.lineDash):null,t.lineDashOffset*this.pixelRatio]}updateFillStyle(t,e){const n=t.fillStyle;"string"==typeof n&&t.currentFillStyle==n||(this.instructions.push(e.call(this,t)),t.currentFillStyle=n)}updateStrokeStyle(t,e){const n=t.strokeStyle,r=t.lineCap,i=t.lineDash,s=t.lineDashOffset,o=t.lineJoin,a=t.lineWidth,l=t.miterLimit;(t.currentStrokeStyle!=n||t.currentLineCap!=r||i!=t.currentLineDash&&!rV(t.currentLineDash,i)||t.currentLineDashOffset!=s||t.currentLineJoin!=o||t.currentLineWidth!=a||t.currentMiterLimit!=l)&&(e.call(this,t),t.currentStrokeStyle=n,t.currentLineCap=r,t.currentLineDash=i,t.currentLineDashOffset=s,t.currentLineJoin=o,t.currentLineWidth=a,t.currentMiterLimit=l)}endGeometry(t){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const e=[7,t];this.instructions.push(e),this.hitDetectionInstructions.push(e)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=hW(this.maxExtent),this.maxLineWidth>0)){const t=this.resolution*(this.maxLineWidth+1)/2;uW(this.bufferedMaxExtent_,t,this.bufferedMaxExtent_)}return this.bufferedMaxExtent_}}class qQ extends $Q{constructor(t,e,n,r){super(t,e,n,r)}drawFlatCoordinatess_(t,e,n,r){const i=this.state,s=void 0!==i.fillStyle,o=void 0!==i.strokeStyle,a=n.length;this.instructions.push(BQ),this.hitDetectionInstructions.push(BQ);for(let l=0;l=t){const e=(t-a+h)/h,d=nW(n,c,e),p=nW(r,u,e);l.push(d,p),s.push(l),l=[d,p],a==t&&(o+=i),a=0}else if(a0&&s.push(l),s}function WQ(t,e,n,r,i){let s,o,a,l,c,u,h,d,p,f,g=n,m=n,y=0,v=0,b=n;for(o=n;ot&&(v>y&&(y=v,g=b,m=o),v=0,b=o-i)),a=l,h=p,d=f),c=n,u=r}return v+=l,v>y?[b,o]:[g,m]}const HQ={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1},GQ={Circle:qQ,Default:$Q,Image:class extends $Q{constructor(t,e,n,r){super(t,e,n,r),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(t,e,n){if(!this.image_||this.maxExtent&&!pW(this.maxExtent,t.getFlatCoordinates()))return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=t.getStride(),s=this.coordinates.length,o=this.appendFlatPointCoordinates(r,i);this.instructions.push([6,s,o,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([6,s,o,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(e)}drawMultiPoint(t,e,n){if(!this.image_)return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=[];for(let a=0,l=r.length;a{const r=o[2*(t+n)]===c[n*u]&&o[2*(t+n)+1]===c[n*u+1];return r||--t,r})}this.saveTextStates_();const h=s.backgroundFill?this.createFill(this.fillStyleToState(s.backgroundFill)):null,d=s.backgroundStroke?this.createStroke(this.strokeStyleToState(s.backgroundStroke)):null;this.beginGeometry(t,e,n);let p=s.padding;if(p!=bJ&&(s.scale[0]<0||s.scale[1]<0)){let t=s.padding[0],e=s.padding[1],n=s.padding[2],r=s.padding[3];s.scale[0]<0&&(e=-e,r=-r),s.scale[1]<0&&(t=-t,n=-n),p=[t,e,n,r]}const f=this.pixelRatio;this.instructions.push([6,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,this.declutterMode_,this.declutterImageWithText_,p==bJ?bJ:p.map(function(t){return t*f}),h,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]);const g=1/f,m=h?h.slice(0):null;m&&(m[1]=dJ),this.hitDetectionInstructions.push([6,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[g,g],NaN,this.declutterMode_,this.declutterImageWithText_,p,m,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?dJ:this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]),this.endGeometry(e)}else{if(!jW(this.maxExtent,t.getExtent()))return;let r;if(c=t.getFlatCoordinates(),"LineString"==l)r=[c.length];else if("MultiLineString"==l)r=t.getEnds();else if("Polygon"==l)r=t.getEnds().slice(0,1);else if("MultiPolygon"==l){const e=t.getEndss();r=[];for(let t=0,n=e.length;tt[2]}else R=_>E;const M=Math.PI,L=[],I=C+r===e;let P;if(y=0,v=S,p=t[e=C],f=t[e+1],I){b(),P=Math.atan2(f-m,p-g),R&&(P+=P>0?-M:M);const t=(E+_)/2,e=(T+x)/2;return L[0]=[t,e,(k-s)/2,P,i],L}for(let A=0,O=(i=i.replace(/\n/g," ")).length;A0?-M:M),void 0!==P){let e=t-P;if(e+=e>M?-2*M:e<-M?2*M:0,Math.abs(e)>o)return null}P=t;const h=A;let d=0;for(;A{if("function"==typeof FK()[e])return this.push_(e),this.pushMethodArgs_},set:(t,e,n)=>(this.push_(e,n),!0)})}push_(...t){const e=this.instructions_,n=this.zIndex+this.offset_;e[n]||(e[n]=[]),e[n].push(...t)}pushMethodArgs_=(...t)=>(this.push_(t),this);pushFunction(t){this.push_(t)}getContext(){return this.context_}draw(t){this.instructions_.forEach(e=>{for(let n=0,r=e.length;n0&&t.push("\n",""),t.push(e,""),t}function o0(t,e,n){return n%2==0&&(t+=e),t}class a0{constructor(t,e,n,r,i){this.overlaps=n,this.pixelRatio=e,this.resolution=t,this.alignAndScaleFill_,this.instructions=r.instructions,this.coordinates=r.coordinates,this.coordinateCache_={},this.renderedTransform_=[1,0,0,1,0,0],this.hitDetectionInstructions=r.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=r.fillStates||{},this.strokeStates=r.strokeStates||{},this.textStates=r.textStates||{},this.widths_={},this.labels_={},this.zIndexContext_=i?new YQ:null}getZIndexContext(){return this.zIndexContext_}createLabel(t,e,n,r){const i=t+e+n+r;if(this.labels_[i])return this.labels_[i];const s=r?this.strokeStates[r]:null,o=n?this.fillStates[n]:null,a=this.textStates[e],l=this.pixelRatio,c=[a.scale[0]*l,a.scale[1]*l],u=a.justify?HQ[a.justify]:i0(Array.isArray(t)?t[0]:t,a.textAlign||yJ),h=r&&s.lineWidth?s.lineWidth:0,d=Array.isArray(t)?t:String(t).split("\n").reduce(s0,[]),{width:p,height:f,widths:g,heights:m,lineWidths:y}=function(t,e){const n=[],r=[],i=[];let s=0,o=0,a=0,l=0;for(let c=0,u=e.length;c<=u;c+=2){const h=e[c];if("\n"===h||c===u){s=Math.max(s,o),i.push(o),o=0,a+=l,l=0;continue}const d=e[c+1]||t.font,p=MJ(d,h);n.push(p),o+=p;const f=TJ(d);r.push(f),l=Math.max(l,f)}return{width:s,height:a,widths:n,heights:r,lineWidths:i}}(a,d),v=p+h,b=[],w=(v+2)*c[0],_=(f+h)*c[1],x={width:w<0?Math.floor(w):Math.ceil(w),height:_<0?Math.floor(_):Math.ceil(_),contextInstructions:b};1==c[0]&&1==c[1]||b.push("scale",c),r&&(b.push("strokeStyle",s.strokeStyle),b.push("lineWidth",h),b.push("lineCap",s.lineCap),b.push("lineJoin",s.lineJoin),b.push("miterLimit",s.miterLimit),b.push("setLineDash",[s.lineDash]),b.push("lineDashOffset",s.lineDashOffset)),n&&b.push("fillStyle",o.fillStyle),b.push("textBaseline","middle"),b.push("textAlign","center");const C=.5-u;let S=u*v+C*h;const k=[],E=[];let T,R=0,M=0,L=0,I=0;for(let P=0,A=d.length;Pt?t-l:i,b=s+c>e?e-c:s,w=p[3]+v*h[0]+p[1],_=p[0]+b*h[1]+p[2],x=m-p[3],C=y-p[0];let S;return(f||0!==u)&&(JQ[0]=x,e0[0]=x,JQ[1]=C,QQ[1]=C,QQ[0]=x+w,t0[0]=QQ[0],t0[1]=C+_,e0[1]=t0[1]),0!==u?(S=wG([1,0,0,1,0,0],n,r,1,1,u,-n,-r),vG(S,JQ),vG(S,QQ),vG(S,t0),vG(S,e0),yW(Math.min(JQ[0],QQ[0],t0[0],e0[0]),Math.min(JQ[1],QQ[1],t0[1],e0[1]),Math.max(JQ[0],QQ[0],t0[0],e0[0]),Math.max(JQ[1],QQ[1],t0[1],e0[1]),XQ)):yW(Math.min(x,x+w),Math.min(C,C+_),Math.max(x,x+w),Math.max(C,C+_),XQ),d&&(m=Math.round(m),y=Math.round(y)),{drawImageX:m,drawImageY:y,drawImageW:v,drawImageH:b,originX:l,originY:c,declutterBox:{minX:XQ[0],minY:XQ[1],maxX:XQ[2],maxY:XQ[3],value:g},canvasTransform:S,scale:h}}replayImageOrLabel_(t,e,n,r,i,s,o){const a=!(!s&&!o),l=r.declutterBox,c=o?o[2]*r.scale[0]/2:0;return l.minX-c<=e[0]&&l.maxX+c>=0&&l.minY-c<=e[1]&&l.maxY+c>=0&&(a&&this.replayTextBackground_(t,JQ,QQ,t0,e0,s,o),function(t,e,n,r,i,s,o,a,l,c,u){t.save(),1!==n&&(void 0===t.globalAlpha?t.globalAlpha=t=>t.globalAlpha*=n:t.globalAlpha*=n),e&&t.transform.apply(t,e),r.contextInstructions?(t.translate(l,c),t.scale(u[0],u[1]),function(t,e){const n=t.contextInstructions;for(let r=0,i=n.length;rO&&(this.fill_(t),R=0),M>O&&(t.stroke(),M=0),R||M||(t.beginPath(),v=NaN,b=NaN),++d;break;case 2:T=n[1];const r=c[T],u=c[T+1],h=c[T+2]-r,p=c[T+3]-u,j=Math.sqrt(h*h+p*p);t.moveTo(r+j,u),t.arc(r,u,j,0,2*Math.PI,!0),++d;break;case 3:t.closePath(),++d;break;case 4:T=n[1],f=n[2];const B=n[3],U=n[4],$=n[5];A.geometry=B,A.feature=F,d in L||(L[d]=[]);const q=L[d];$?$(c,T,f,2,q):(q[0]=c[T],q[1]=c[T+1],q.length=2),l&&(l.zIndex=n[6]),U(q,A),++d;break;case 6:T=n[1],f=n[2],x=n[3],g=n[4],m=n[5];let V=n[6];const W=n[7],H=n[8],G=n[9],K=n[10];let Z=n[11];const Y=n[12];let X=n[13];y=n[14]||"declutter";const J=n[15];if(!x&&n.length>=20){C=n[19],S=n[20],k=n[21],E=n[22];const t=this.drawLabelWithPointPlacement_(C,S,k,E);x=t.label,n[3]=x;const e=n[23];g=(t.anchorX-e)*this.pixelRatio,n[4]=g;const r=n[24];m=(t.anchorY-r)*this.pixelRatio,n[5]=m,V=x.height,n[6]=V,X=x.width,n[13]=X}let Q,tt,et,nt;n.length>25&&(Q=n[25]),n.length>17?(tt=n[16],et=n[17],nt=n[18]):(tt=bJ,et=null,nt=null),K&&P?Z+=I:K||P||(Z-=I);let rt=0;for(;T!c0.includes(t));class h0{constructor(t,e,n,r,i,s,o){this.maxExtent_=t,this.overlaps_=r,this.pixelRatio_=n,this.resolution_=e,this.renderBuffer_=s,this.executorsByZIndex_={},this.hitDetectionContext_=null,this.hitDetectionTransform_=[1,0,0,1,0,0],this.renderedContext_=null,this.deferredZIndexContexts_={},this.createExecutors_(i,o)}clip(t,e){const n=this.getClipCoords(e);t.beginPath(),t.moveTo(n[0],n[1]),t.lineTo(n[2],n[3]),t.lineTo(n[4],n[5]),t.lineTo(n[6],n[7]),t.clip()}createExecutors_(t,e){for(const n in t){let r=this.executorsByZIndex_[n];void 0===r&&(r={},this.executorsByZIndex_[n]=r);const i=t[n];for(const t in i){const n=i[t];r[t]=new a0(this.resolution_,this.pixelRatio_,this.overlaps_,n,e)}}}hasExecutors(t){for(const e in this.executorsByZIndex_){const n=this.executorsByZIndex_[e];for(let e=0,r=t.length;en)break;let a=r[o];a||(a=[],r[o]=a),a.push(4*((t+s)*e+(t+i))+3),s>0&&a.push(4*((t-s)*e+(t+i))+3),i>0&&(a.push(4*((t+s)*e+(t-i))+3),s>0&&a.push(4*((t-s)*e+(t-i))+3))}const i=[];for(let s=0,o=r.length;s0){if(!s||"none"===n||"Image"!==d&&"Text"!==d||s.includes(t)){const n=(h[l]-3)/4,s=r-n%o,a=r-(n/o|0),c=i(t,e,s*s+a*a);if(c)return c}c.clearRect(0,0,o,o);break}}const f=Object.keys(this.executorsByZIndex_).map(Number);let g,m,y,v,b;for(f.sort(Jq),g=f.length-1;g>=0;--g){const t=f[g].toString();for(y=this.executorsByZIndex_[t],m=l0.length-1;m>=0;--m)if(d=l0[m],v=y[d],void 0!==v&&(b=v.executeHitDetection(c,a,n,p,u),b))return b}}getClipCoords(t){const e=this.maxExtent_;if(!e)return null;const n=e[0],r=e[1],i=e[2],s=e[3],o=[n,r,n,s,i,s,i,r];return SG(o,0,8,2,t,o),o}isEmpty(){return uV(this.executorsByZIndex_)}execute(t,e,n,r,i,s,o){const a=Object.keys(this.executorsByZIndex_).map(Number);a.sort(o?Qq:Jq),s=s||l0;const l=l0.length;for(let c=0,u=a.length;cp.execute(t,e,n,r,i,o)):p.execute(h,e,n,r,i,o),d&&h.restore(),s){s.offset();const t=a[c]*l+l0.indexOf(u);this.deferredZIndexContexts_[t]||(this.deferredZIndexContexts_[t]=[]),this.deferredZIndexContexts_[t].push(s)}}}}this.renderedContext_=t}getDeferredZIndexContexts(){return this.deferredZIndexContexts_}getRenderedContext(){return this.renderedContext_}renderDeferred(){const t=this.deferredZIndexContexts_,e=Object.keys(t).map(Number).sort(Jq);for(let n=0,r=e.length;n{t.draw(this.renderedContext_),t.clear()}),t[e[n]].length=0}}const d0={};class p0 extends zQ{constructor(t,e,n,r,i,s,o){super(),this.context_=t,this.pixelRatio_=e,this.extent_=n,this.transform_=r,this.transformRotation_=r?rW(Math.atan2(r[1],r[0]),10):0,this.viewRotation_=i,this.squaredTolerance_=s,this.userTransform_=o,this.contextFillState_=null,this.contextStrokeState_=null,this.contextTextState_=null,this.fillState_=null,this.strokeState_=null,this.image_=null,this.imageAnchorX_=0,this.imageAnchorY_=0,this.imageHeight_=0,this.imageOpacity_=0,this.imageOriginX_=0,this.imageOriginY_=0,this.imageRotateWithView_=!1,this.imageRotation_=0,this.imageScale_=[0,0],this.imageWidth_=0,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=!1,this.textRotation_=0,this.textScale_=[0,0],this.textFillState_=null,this.textStrokeState_=null,this.textState_=null,this.pixelCoordinates_=[],this.tmpLocalTransform_=[1,0,0,1,0,0]}drawImages_(t,e,n,r){if(!this.image_)return;const i=SG(t,e,n,r,this.transform_,this.pixelCoordinates_),s=this.context_,o=this.tmpLocalTransform_,a=s.globalAlpha;1!=this.imageOpacity_&&(s.globalAlpha=a*this.imageOpacity_);let l=this.imageRotation_;0===this.transformRotation_&&(l-=this.viewRotation_),this.imageRotateWithView_&&(l+=this.viewRotation_);for(let c=0,u=i.length;ct*this.pixelRatio_),lineDashOffset:(i||0)*this.pixelRatio_,lineJoin:void 0!==s?s:gJ,lineWidth:(void 0!==o?o:1)*this.pixelRatio_,miterLimit:void 0!==a?a:10,strokeStyle:uJ(t||mJ)}}else this.strokeState_=null}setImageStyle(t){let e;if(!t||!(e=t.getSize()))return void(this.image_=null);const n=t.getPixelRatio(this.pixelRatio_),r=t.getAnchor(),i=t.getOrigin();this.image_=t.getImage(this.pixelRatio_),this.imageAnchorX_=r[0]*n,this.imageAnchorY_=r[1]*n,this.imageHeight_=e[1]*n,this.imageOpacity_=t.getOpacity(),this.imageOriginX_=i[0],this.imageOriginY_=i[1],this.imageRotateWithView_=t.getRotateWithView(),this.imageRotation_=t.getRotation();const s=t.getScaleArray();this.imageScale_=[s[0]*this.pixelRatio_/n,s[1]*this.pixelRatio_/n],this.imageWidth_=e[0]*n}setTextStyle(t){if(t){const e=t.getFill();if(e){const t=e.getColor();this.textFillState_={fillStyle:uJ(t||dJ)}}else this.textFillState_=null;const n=t.getStroke();if(n){const t=n.getColor(),e=n.getLineCap(),r=n.getLineDash(),i=n.getLineDashOffset(),s=n.getLineJoin(),o=n.getWidth(),a=n.getMiterLimit();this.textStrokeState_={lineCap:void 0!==e?e:pJ,lineDash:r||fJ,lineDashOffset:i||0,lineJoin:void 0!==s?s:gJ,lineWidth:void 0!==o?o:1,miterLimit:void 0!==a?a:10,strokeStyle:uJ(t||mJ)}}else this.textStrokeState_=null;const r=t.getFont(),i=t.getOffsetX(),s=t.getOffsetY(),o=t.getRotateWithView(),a=t.getRotation(),l=t.getScaleArray(),c=t.getText(),u=t.getTextAlign(),h=t.getTextBaseline();this.textState_={font:void 0!==r?r:hJ,textAlign:void 0!==u?u:yJ,textBaseline:void 0!==h?h:vJ},this.text_=void 0!==c?Array.isArray(c)?c.reduce((t,e,n)=>t+(n%2?" ":e),""):c:"",this.textOffsetX_=void 0!==i?this.pixelRatio_*i:0,this.textOffsetY_=void 0!==s?this.pixelRatio_*s:0,this.textRotateWithView_=void 0!==o&&o,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*l[0],this.pixelRatio_*l[1]]}else this.text_=""}}const f0=.5;function g0(t,e,n,r,i,s,o,a,l){const c=i,u=AK(t[0]*f0,t[1]*f0);u.imageSmoothingEnabled=!1;const h=u.canvas,d=new p0(u,f0,i,null,o,a,l?rG(null,l):null),p=n.length,f=Math.floor(16777215/p),g={};for(let y=1;y<=p;++y){const t=n[y-1],e=t.getStyleFunction()||r;if(!e)continue;let i=e(t,s);if(!i)continue;Array.isArray(i)||(i=[i]);const o=(y*f).toString(16).padStart(7,"#00000");for(let n=0,r=i.length;n0;return h&&Promise.all(l).then(()=>i(null)),function(t,e,n,r,i,s,o){const a=n.getGeometryFunction()(e);if(!a)return;const l=a.simplifyTransformed(r,i);n.getRenderer()?x0(t,l,n,e,o):(0,y0[l.getType()])(t,l,n,e,o,s)}(t,e,n,r,s,o,a),h}function x0(t,e,n,r,i){if("GeometryCollection"==e.getType()){const s=e.getGeometries();for(let e=0,o=s.length;ethis.maxStaleKeys&&(this.staleKeys_.length=this.maxStaleKeys)}getFeatures(t){return yV()}getData(t){return null}prepareFrame(t){return yV()}renderFrame(t,e){return yV()}forEachFeatureAtCoordinate(t,e,n,r,i){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(t){const e=t.target;2!==e.getState()&&3!==e.getState()||this.renderIfReadyAndVisible()}loadImage(t){let e=t.getState();return 2!=e&&3!=e&&t.addEventListener(Vq,this.boundHandleImageChange_),0==e&&(t.load(),e=t.getState()),2==e}renderIfReadyAndVisible(){const t=this.getLayer();t&&t.getVisible()&&"ready"===t.getSourceState()&&t.changed()}renderDeferred(t){}disposeInternal(){delete this.layer_,super.disposeInternal()}}const S0=[];let k0=null;class E0 extends C0{constructor(t){super(t),this.container=null,this.renderedResolution,this.tempTransform=[1,0,0,1,0,0],this.pixelTransform=[1,0,0,1,0,0],this.inversePixelTransform=[1,0,0,1,0,0],this.context=null,this.deferredContext_=null,this.containerReused=!1,this.frameState=null}getImageData(t,e,n){let r;k0||(k0=AK(1,1,void 0,{willReadFrequently:!0})),k0.clearRect(0,0,1,1);try{k0.drawImage(t,e,n,1,1,0,0,1,1),r=k0.getImageData(0,0,1,1).data}catch{return k0=null,null}return r}getBackground(t){let e=this.getLayer().getBackground();return"function"==typeof e&&(e=e(t.viewState.resolution)),e||void 0}useContainer(t,e,n){const r=this.getLayer().getClassName();let i,s;if(t&&t.className===r&&(!n||t&&t.style.backgroundColor&&rV(LY(t.style.backgroundColor),LY(n)))){const e=t.firstElementChild;$K(e)&&(s=e.getContext("2d"))}if(s&&function(t,e){const n=CG(t),r=CG(e);for(let i=0;i<6;++i)if(0!==Math.round((n[i]-r[i])*xG[i]))return!1;return!0}(s.canvas.style.transform,e)?(this.container=t,this.context=s,this.containerReused=!0):this.containerReused?(this.container=null,this.context=null,this.containerReused=!1):this.container&&(this.container.style.backgroundColor=null),!this.container){i=PV?UK():document.createElement("div"),i.className=r;let t=i.style;t.position="absolute",t.width="100%",t.height="100%",s=AK();const e=s.canvas;i.appendChild(e),t=e.style,t.position="absolute",t.left="0",t.transformOrigin="top left",this.container=i,this.context=s}this.containerReused||!n||this.container.style.backgroundColor||(this.container.style.backgroundColor=n)}clipUnrotated(t,e,n){const r=zW(n),i=DW(n),s=MW(n),o=RW(n);vG(e.coordinateToPixelTransform,r),vG(e.coordinateToPixelTransform,i),vG(e.coordinateToPixelTransform,s),vG(e.coordinateToPixelTransform,o);const a=this.inversePixelTransform;vG(a,r),vG(a,i),vG(a,s),vG(a,o),t.save(),t.beginPath(),t.moveTo(Math.round(r[0]),Math.round(r[1])),t.lineTo(Math.round(i[0]),Math.round(i[1])),t.lineTo(Math.round(s[0]),Math.round(s[1])),t.lineTo(Math.round(o[0]),Math.round(o[1])),t.clip()}prepareContainer(t,e){const n=t.extent,r=t.viewState.resolution,i=t.viewState.rotation,s=t.pixelRatio,o=Math.round(NW(n)/r*s),a=Math.round(OW(n)/r*s);wG(this.pixelTransform,t.size[0]/2,t.size[1]/2,1/s,1/s,i,-o/2,-a/2),_G(this.inversePixelTransform,this.pixelTransform);const l="matrix("+this.pixelTransform.join(", ")+")";if(this.useContainer(e,l,this.getBackground(t)),!this.containerReused){const t=this.context.canvas;t.width!=o||t.height!=a?(t.width=o,t.height=a):this.context.clearRect(0,0,o,a),l!==t.style.transform&&(t.style.transform=l)}}dispatchRenderEvent_(t,e,n){const r=this.getLayer();if(r.hasListener(t)){const i=new fQ(t,this.inversePixelTransform,n,e);r.dispatchEvent(i)}}preRender(t,e){this.frameState=e,e.declutter||this.dispatchRenderEvent_($Z,t,e)}postRender(t,e){e.declutter||this.dispatchRenderEvent_(qZ,t,e)}renderDeferredInternal(t){}getRenderContext(t){return t.declutter&&!this.deferredContext_&&(this.deferredContext_=new YQ),t.declutter?this.deferredContext_.getContext():this.context}renderDeferred(t){t.declutter&&(this.dispatchRenderEvent_($Z,this.context,t),t.declutter&&this.deferredContext_&&(this.deferredContext_.draw(this.context),this.deferredContext_.clear()),this.renderDeferredInternal(t),this.dispatchRenderEvent_(qZ,this.context,t))}getRenderTransform(t,e,n,r,i,s,o){const a=i/2,l=s/2,c=r/e,u=-c,h=-t[0]+o,d=-t[1];return wG(this.tempTransform,a,l,c,u,-n,h,d)}disposeInternal(){delete this.frameState,super.disposeInternal()}}class T0 extends E0{constructor(t){super(t),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.animatingOrInteracting_,this.hitDetectionImageData_=null,this.clipped_=!1,this.renderedFeatures_=null,this.renderedRevision_=-1,this.renderedResolution_=NaN,this.renderedExtent_=[1/0,1/0,-1/0,-1/0],this.wrappedRenderedExtent_=[1/0,1/0,-1/0,-1/0],this.renderedRotation_,this.renderedCenter_=null,this.renderedProjection_=null,this.renderedPixelRatio_=1,this.renderedRenderOrder_=null,this.renderedFrameDeclutter_,this.replayGroup_=null,this.replayGroupChanged=!0,this.clipping=!0,this.targetContext_=null,this.opacity_=1}renderWorlds(t,e,n){const r=e.extent,i=e.viewState,s=i.center,o=i.resolution,a=i.projection,l=i.rotation,c=a.getExtent(),u=this.getLayer().getSource(),h=this.getLayer().getDeclutter(),d=e.pixelRatio,p=e.viewHints,f=!(p[0]||p[1]),g=this.context,m=Math.round(NW(r)/o*d),y=Math.round(OW(r)/o*d),v=u.getWrapX()&&a.canWrapX(),b=v?NW(c):null,w=v?Math.ceil((r[2]-c[2])/b)+1:1;let _=v?Math.floor((r[0]-c[0])/b):0;do{let r=this.getRenderTransform(s,o,0,d,m,y,_*b);e.declutter&&(r=r.slice(0)),t.execute(g,[g.canvas.width,g.canvas.height],r,l,f,void 0===n?l0:n?c0:u0,n?h&&e.declutter[h]:void 0)}while(++_{if(this.frameState&&!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const t=this.frameState.size.slice(),e=this.renderedCenter_,n=this.renderedResolution_,r=this.renderedRotation_,i=this.renderedProjection_,s=this.wrappedRenderedExtent_,o=this.getLayer(),a=[],l=t[0]*f0,c=t[1]*f0;a.push(this.getRenderTransform(e,n,r,f0,l,c,0).slice());const u=o.getSource(),h=i.getExtent();if(u.getWrapX()&&i.canWrapX()&&!fW(h,s)){let t=s[0];const i=NW(h);let o,u=0;for(;th[2];)++u,o=i*u,a.push(this.getRenderTransform(e,n,r,f0,l,c,o).slice()),t-=i}this.hitDetectionImageData_=g0(t,a,this.renderedFeatures_,o.getStyleFunction(),s,n,r,b0(n,this.renderedPixelRatio_),null)}e(m0(t,this.renderedFeatures_,this.hitDetectionImageData_))})}forEachFeatureAtCoordinate(t,e,n,r,i){if(!this.replayGroup_)return;const s=e.viewState.resolution,o=e.viewState.rotation,a=this.getLayer(),l={},c=this.getLayer().getDeclutter();return this.replayGroup_.forEachFeatureAtCoordinate(t,s,o,n,function(t,e,n){const s=bV(t),o=l[s];if(o){if(!0!==o&&nt.value):null)}handleFontsChanged(){const t=this.getLayer();t.getVisible()&&this.replayGroup_&&t.changed()}handleStyleImageChange_(t){this.renderIfReadyAndVisible()}prepareFrame(t){const e=this.getLayer(),n=e.getSource();if(!n)return!1;const r=t.viewHints[0],i=t.viewHints[1],s=e.getUpdateWhileAnimating(),o=e.getUpdateWhileInteracting();if(this.ready&&!s&&r||!o&&i)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=t.extent,l=t.viewState,c=l.projection,u=l.resolution,h=t.pixelRatio,d=e.getRevision(),p=e.getRenderBuffer();let f=e.getRenderOrder();void 0===f&&(f=v0);const g=l.center.slice(),m=uW(a,p*u),y=m.slice(),v=[m.slice()],b=c.getExtent();if(n.getWrapX()&&c.canWrapX()&&!fW(b,t.extent)){const t=NW(b),e=Math.max(NW(m)/2,t);m[0]=b[0]-e,m[2]=b[2]+e,HW(g,c);const n=$W(v[0],c);n[0]b[0]&&n[2]>b[2]&&v.push([n[0]-t,n[1],n[2]-t,n[3]])}if(this.ready&&this.renderedResolution_==u&&this.renderedRevision_==d&&this.renderedRenderOrder_==f&&this.renderedFrameDeclutter_===!!t.declutter&&fW(this.wrappedRenderedExtent_,m))return rV(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=g,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const w=new KQ(w0(u,h),m,u,h);for(let R=0,M=v.length;R{let r;const i=t.getStyleFunction()||e.getStyleFunction();if(i&&(r=i(t,u)),r){const e=this.renderFeature(t,_,r,w,void 0,this.getLayer().getDeclutter(),n);x=x&&!e}},S=m,k=n.getFeaturesInExtent(S);f&&k.sort(f);for(let R=0,M=k.length;R=200&&a.status<300){const t=e.getType();try{let r;"text"==t||"json"==t?r=a.responseText:"xml"==t?r=a.responseXML||a.responseText:"arraybuffer"==t&&(r=a.response),r?s(e.readFeatures(r,{extent:n,featureProjection:i}),e.readProjection(r)):o()}catch{o()}}else o()},a.onerror=o,a.send()}function L0(t,e){return function(n,r,i,s,o){M0(t,e,n,r,i,t=>{this.addFeatures(t),void 0!==s&&s(t)},()=>{this.changed(),void 0!==o&&o()})}}function I0(){return[[-1/0,-1/0,1/0,1/0]]}function P0(t){return[t]}class A0 extends RG{constructor(t){super(),this.geometries_=t,this.changeEventsKeys_=[],this.listenGeometriesChange_()}unlistenGeometriesChange_(){this.changeEventsKeys_.forEach(gV),this.changeEventsKeys_.length=0}listenGeometriesChange_(){const t=this.geometries_;for(let e=0,n=t.length;et.clone())}const F0=[1,0,0,1,0,0];class z0{constructor(t,e,n,r,i,s){this.styleFunction,this.extent_,this.id_=s,this.type_=t,this.flatCoordinates_=e,this.flatInteriorPoints_=null,this.flatMidpoints_=null,this.ends_=n||null,this.properties_=i,this.squaredTolerance_,this.stride_=r,this.simplifiedGeometry_}get(t){return this.properties_[t]}getExtent(){return this.extent_||(this.extent_="Point"===this.type_?bW(this.flatCoordinates_):wW(this.flatCoordinates_,0,this.flatCoordinates_.length,2)),this.extent_}getFlatInteriorPoint(){if(!this.flatInteriorPoints_){const t=LW(this.getExtent());this.flatInteriorPoints_=eK(this.flatCoordinates_,0,this.ends_,2,t,0)}return this.flatInteriorPoints_}getFlatInteriorPoints(){if(!this.flatInteriorPoints_){const t=pK(this.flatCoordinates_,this.ends_),e=OQ(this.flatCoordinates_,0,t,2);this.flatInteriorPoints_=nK(this.flatCoordinates_,0,t,2,e)}return this.flatInteriorPoints_}getFlatMidpoint(){return this.flatMidpoints_||(this.flatMidpoints_=RQ(this.flatCoordinates_,0,this.flatCoordinates_.length,2,.5)),this.flatMidpoints_}getFlatMidpoints(){if(!this.flatMidpoints_){this.flatMidpoints_=[];const t=this.flatCoordinates_;let e=0;const n=this.ends_;for(let r=0,i=n.length;r{if(t===this.squaredTolerance_)return this.simplifiedGeometry_;this.simplifiedGeometry_=this.clone(),e&&this.simplifiedGeometry_.applyTransform(e);const n=this.simplifiedGeometry_.getFlatCoordinates();let r;switch(this.type_){case"LineString":n.length=WG(n,0,this.simplifiedGeometry_.flatCoordinates_.length,this.simplifiedGeometry_.stride_,t,n,0),r=[n.length];break;case"MultiLineString":r=[],n.length=HG(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,t,n,0,r);break;case"Polygon":r=[],n.length=ZG(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,Math.sqrt(t),n,0,r)}return r&&(this.simplifiedGeometry_=new z0(this.type_,n,r,2,this.properties_,this.id_)),this.squaredTolerance_=t,this.simplifiedGeometry_}),this}}z0.prototype.getFlatCoordinates=z0.prototype.getOrientedFlatCoordinates;class D0{constructor(t){this.rbush_=new XZ(t),this.items_={}}insert(t,e){const n={minX:t[0],minY:t[1],maxX:t[2],maxY:t[3],value:e};this.rbush_.insert(n),this.items_[bV(e)]=n}load(t,e){const n=new Array(e.length);for(let r=0,i=e.length;rt):null}const B0="addfeature",U0="removefeature";class $0 extends hV{constructor(t,e,n){super(t),this.feature=e,this.features=n}}class q0 extends N0{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:!0,projection:void 0,state:"ready",wrapX:void 0===t.wrapX||t.wrapX}),this.on,this.once,this.un,this.loader_=oV,this.format_=t.format||null,this.overlaps_=void 0===t.overlaps||t.overlaps,this.url_=t.url,void 0!==t.loader?this.loader_=t.loader:void 0!==this.url_&&(WV(this.format_,"`format` must be set when `url` is set"),this.loader_=L0(this.url_,this.format_)),this.strategy_=void 0!==t.strategy?t.strategy:I0;const e=void 0===t.useSpatialIndex||t.useSpatialIndex;let n,r;this.featuresRtree_=e?new D0:null,this.loadedExtentsRtree_=new D0,this.loadingExtentsCount_=0,this.nullGeometryFeatures_={},this.idIndex_={},this.uidIndex_={},this.featureChangeKeys_={},this.featuresCollection_=null,Array.isArray(t.features)?r=t.features:t.features&&(n=t.features,r=n.getArray()),e||void 0!==n||(n=new SV(r)),void 0!==r&&this.addFeaturesInternal(r),void 0!==n&&this.bindFeaturesCollection_(n)}addFeature(t){this.addFeatureInternal(t),this.changed()}addFeatureInternal(t){const e=bV(t);if(!this.addToIndex_(e,t))return void(this.featuresCollection_&&this.featuresCollection_.remove(t));this.setupChangeEvents_(e,t);const n=t.getGeometry();if(n){const e=n.getExtent();this.featuresRtree_&&this.featuresRtree_.insert(e,t)}else this.nullGeometryFeatures_[e]=t;this.dispatchEvent(new $0(B0,t))}setupChangeEvents_(t,e){e instanceof z0||(this.featureChangeKeys_[t]=[pV(e,Vq,this.handleFeatureChange_,this),pV(e,qq,this.handleFeatureChange_,this)])}addToIndex_(t,e){let n=!0;if(void 0!==e.getId()){const t=String(e.getId());if(t in this.idIndex_)if(e instanceof z0){const r=this.idIndex_[t];r instanceof z0?Array.isArray(r)?r.push(e):this.idIndex_[t]=[r,e]:n=!1}else n=!1;else this.idIndex_[t]=e}return n&&(WV(!(t in this.uidIndex_),"The passed `feature` was already added to the source"),this.uidIndex_[t]=e),n}addFeatures(t){this.addFeaturesInternal(t),this.changed()}addFeaturesInternal(t){const e=[],n=[],r=[];for(let i=0,s=t.length;i{e||(e=!0,this.addFeature(t.element),e=!1)}),t.addEventListener($q,t=>{e||(e=!0,this.removeFeature(t.element),e=!1)}),this.featuresCollection_=t}clear(t){if(t){for(const t in this.featureChangeKeys_)this.featureChangeKeys_[t].forEach(gV);this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){this.featuresRtree_.forEach(t=>{this.removeFeatureInternal(t)});for(const t in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[t])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const e=new $0("clear");this.dispatchEvent(e),this.changed()}forEachFeature(t){if(this.featuresRtree_)return this.featuresRtree_.forEach(t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureAtCoordinateDirect(t,e){const n=[t[0],t[1],t[0],t[1]];return this.forEachFeatureInExtent(n,function(n){const r=n.getGeometry();if(r instanceof z0||r.intersectsCoordinate(t))return e(n)})}forEachFeatureInExtent(t,e){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(t,e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureIntersectingExtent(t,e){return this.forEachFeatureInExtent(t,function(n){const r=n.getGeometry();if(r instanceof z0||r.intersectsExtent(t)){const t=e(n);if(t)return t}})}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let t;return this.featuresCollection_?t=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(t=this.featuresRtree_.getAll(),uV(this.nullGeometryFeatures_)||nV(t,Object.values(this.nullGeometryFeatures_))),t}getFeaturesAtCoordinate(t){const e=[];return this.forEachFeatureAtCoordinateDirect(t,function(t){e.push(t)}),e}getFeaturesInExtent(t,e){if(this.featuresRtree_){if(!(e&&e.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(t);const n=qW(t,e);return[].concat(...n.map(t=>this.featuresRtree_.getInExtent(t)))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(t,e){const n=t[0],r=t[1];let i=null;const s=[NaN,NaN];let o=1/0;const a=[-1/0,-1/0,1/0,1/0];return e=e||iV,this.featuresRtree_.forEachInExtent(a,function(t){if(e(t)){const e=t.getGeometry(),l=o;if(o=e instanceof z0?0:e.closestPointXY(n,r,s,o),o{--this.loadingExtentsCount_,this.dispatchEvent(new $0("featuresloadend",void 0,t))},()=>{--this.loadingExtentsCount_,this.dispatchEvent(new $0("featuresloaderror"))}),r.insert(t,{extent:t.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(t){const e=this.loadedExtentsRtree_,n=e.forEachInExtent(t,function(e){if(_W(e.extent,t))return e});n&&e.remove(n)}removeFeatures(t){let e=!1;for(let n=0,r=t.length;nG0({...t,geometry:e})).flat();const r="MultiPolygon"===n.type?"Polygon":n.type;if("GeometryCollection"===r||"Circle"===r)throw new Error("Unsupported geometry type: "+r);const i=n.layout.length;return W0(new z0(r,"Polygon"===r?function(t,e,n){return Array.isArray(e[0])?(uK(t,0,e,n)||dK(t=t.slice(),0,e,n),t):(cK(t,0,e,n)||hK(t=t.slice(),0,e,n),t)}(n.flatCoordinates,n.ends,i):n.flatCoordinates,n.ends?.flat(),i,t.properties||{},t.id).enableSimplifyTransformed(),!1,e)}function K0(t,e){if(!t)return null;if(Array.isArray(t)){const n=t.map(t=>K0(t,e));return new A0(n)}return W0(new(0,H0[t.type])(t.flatCoordinates,t.layout||"XY",t.ends),!1,e)}class Z0 extends V0{constructor(){super()}getType(){return"json"}readFeature(t,e){return this.readFeatureFromObject(Y0(t),this.getReadOptions(t,e))}readFeatures(t,e){return this.readFeaturesFromObject(Y0(t),this.getReadOptions(t,e))}readFeatureFromObject(t,e){return yV()}readFeaturesFromObject(t,e){return yV()}readGeometry(t,e){return this.readGeometryFromObject(Y0(t),this.getReadOptions(t,e))}readGeometryFromObject(t,e){return yV()}readProjection(t){return this.readProjectionFromObject(Y0(t))}readProjectionFromObject(t){return yV()}writeFeature(t,e){return JSON.stringify(this.writeFeatureObject(t,e))}writeFeatureObject(t,e){return yV()}writeFeatures(t,e){return JSON.stringify(this.writeFeaturesObject(t,e))}writeFeaturesObject(t,e){return yV()}writeGeometry(t,e){return JSON.stringify(this.writeGeometryObject(t,e))}writeGeometryObject(t,e){return yV()}}function Y0(t){return"string"==typeof t?JSON.parse(t)||null:null!==t?t:null}class X0 extends Z0{constructor(t){t=t||{},super(),this.dataProjection=YH(t.dataProjection?t.dataProjection:"EPSG:4326"),t.featureProjection&&(this.defaultFeatureProjection=YH(t.featureProjection)),t.featureClass&&(this.featureClass=t.featureClass),this.geometryName_=t.geometryName,this.extractGeometryName_=t.extractGeometryName,this.supportedMediaTypes=["application/geo+json","application/vnd.geo+json"]}readFeatureFromObject(t,e){let n=null;n="Feature"===t.type?t:{type:"Feature",geometry:t,properties:null};const r=J0(n.geometry);if(this.featureClass===z0)return G0({geometry:r,id:n.id,properties:n.properties},e);const i=new TQ;return this.geometryName_?i.setGeometryName(this.geometryName_):this.extractGeometryName_&&n.geometry_name&&i.setGeometryName(n.geometry_name),i.setGeometry(K0(r,e)),"id"in n&&i.setId(n.id),n.properties&&i.setProperties(n.properties,!0),i}readFeaturesFromObject(t,e){let n=null;if("FeatureCollection"===t.type){n=[];const r=t.features;for(let t=0,i=r.length;t{t in e&&(n[t]=e[t])}),n}function f1(t){t=t.slice();const e=Object.create(null);for(let n=0;n`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const O1=[y1,v1,b1,w1,_1,x1,E1,C1,P1(S1),T1,M1,R1,L1,I1];function F1(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!F1(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of O1)if(!F1(t,e))return null}return`Expected ${A1(t)} but found ${A1(e)} instead.`}function z1(t,e){return e.some(e=>e.kind===t.kind)}function D1(t,e){return e.some(e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t)}function N1(t,e){return"array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const j1=.96422,B1=.82521,U1=4/29,$1=6/29,q1=3*$1*$1,V1=$1*$1*$1,W1=Math.PI/180,H1=180/Math.PI;function G1(t){return(t%=360)<0&&(t+=360),t}function K1([t,e,n,r]){let i,s;const o=Y1((.2225045*(t=Z1(t))+.7168786*(e=Z1(e))+.0606169*(n=Z1(n)))/1);t===e&&e===n?i=s=o:(i=Y1((.4360747*t+.3850649*e+.1430804*n)/j1),s=Y1((.0139322*t+.0971045*e+.7141733*n)/B1));const a=116*o-16;return[a<0?0:a,500*(i-o),200*(o-s),r]}function Z1(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Y1(t){return t>V1?Math.pow(t,1/3):t/q1+U1}function X1([t,e,n,r]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,o=isNaN(n)?i:i-n/200;return i=1*Q1(i),s=j1*Q1(s),o=B1*Q1(o),[J1(3.1338561*s-1.6168667*i-.4906146*o),J1(-.9787684*s+1.9161415*i+.033454*o),J1(.0719453*s-.2289914*i+1.4052427*o),r]}function J1(t){return(t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function Q1(t){return t>$1?t*t*t:q1*(t-U1)}const t2=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function e2(t,e){return t2(t,e)?t[e]:void 0}function n2(t){return parseInt(t.padEnd(2,t),16)/255}function r2(t,e){return i2(e?t/100:t,0,1)}function i2(t,e,n){return Math.min(Math.max(e,t),n)}function s2(t){return!t.some(Number.isNaN)}const o2={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function a2(t,e,n){return t+n*(e-t)}function l2(t,e,n){return t.map((t,r)=>a2(t,e[r],n))}class c2{constructor(t,e,n,r=1,i=!0){this.r=t,this.g=e,this.b=n,this.a=r,i||(this.r*=r,this.g*=r,this.b*=r,r||this.overwriteGetter("rgb",[t,e,n,r]))}static parse(t){if(t instanceof c2)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return[0,0,0,0];const e=e2(o2,t);if(e){const[t,n,r]=e;return[t/255,n/255,r/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let n=1;return[n2(t.slice(n,n+=e)),n2(t.slice(n,n+=e)),n2(t.slice(n,n+=e)),n2(t.slice(n,n+e)||"ff")]}if(t.startsWith("rgb")){const e=/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/,n=t.match(e);if(n){const[t,e,r,i,s,o,a,l,c,u,h,d]=n,p=[i||" ",a||" ",u].join("");if(" "===p||" /"===p||",,"===p||",,,"===p){const t=[r,o,c].join(""),n="%%%"===t?100:""===t?255:0;if(n){const t=[i2(+e/n,0,1),i2(+s/n,0,1),i2(+l/n,0,1),h?r2(+h,d):1];if(s2(t))return t}}return}}const n=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(n){const[t,e,r,i,s,o,a,l,c]=n,u=[r||" ",s||" ",a].join("");if(" "===u||" /"===u||",,"===u||",,,"===u){const t=[+e,i2(+i,0,100),i2(+o,0,100),l?r2(+l,c):1];if(s2(t))return function([t,e,n,r]){function i(r){const i=(r+t/30)%12,s=e*Math.min(n,1-n);return n-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=G1(t),e/=100,n/=100,[i(0),i(8),i(4),r]}(t)}}}(t);return e?new c2(...e,!1):void 0}get rgb(){const{r:t,g:e,b:n,a:r}=this,i=r||1/0;return this.overwriteGetter("rgb",[t/i,e/i,n/i,r])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,n,r,i]=K1(t),s=Math.sqrt(n*n+r*r);return[Math.round(1e4*s)?G1(Math.atan2(r,n)*H1):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",K1(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,n,r]=this.rgb;return`rgba(${[t,e,n].map(t=>Math.round(255*t)).join(",")},${r})`}static interpolate(t,e,n,r="rgb"){switch(r){case"rgb":{const[r,i,s,o]=l2(t.rgb,e.rgb,n);return new c2(r,i,s,o,!1)}case"hcl":{const[r,i,s,o]=t.hcl,[a,l,c,u]=e.hcl;let h,d;if(isNaN(r)||isNaN(a))isNaN(r)?isNaN(a)?h=NaN:(h=a,1!==s&&0!==s||(d=l)):(h=r,1!==c&&0!==c||(d=i));else{let t=a-r;a>r&&t>180?t-=360:a180&&(t+=360),h=r+n*t}const[p,f,g,m]=function([t,e,n,r]){return t=isNaN(t)?0:t*W1,X1([n,Math.cos(t)*e,Math.sin(t)*e,r])}([h,null!=d?d:a2(i,l,n),a2(s,c,n),a2(o,u,n)]);return new c2(p,f,g,m,!1)}case"lab":{const[r,i,s,o]=X1(l2(t.lab,e.lab,n));return new c2(r,i,s,o,!1)}}}}c2.black=new c2(0,0,0,1),c2.white=new c2(1,1,1,1),c2.transparent=new c2(0,0,0,0),c2.red=new c2(1,0,0,1);class u2{constructor(t,e,n){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=n,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const h2=["bottom","center","top"];class d2{constructor(t,e,n,r,i,s){this.text=t,this.image=e,this.scale=n,this.fontStack=r,this.textColor=i,this.verticalAlign=s}}class p2{constructor(t){this.sections=t}static fromString(t){return new p2([new d2(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some(t=>0!==t.text.length||t.image&&0!==t.image.name.length)}static factory(t){return t instanceof p2?t:p2.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map(t=>t.text).join("")}}class f2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof f2)return t;if("number"==typeof t)return new f2([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]]}return new f2(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new f2(l2(t.values,e.values,n))}}class g2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof g2)return t;if("number"==typeof t)return new g2([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new g2(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n){return new g2(l2(t.values,e.values,n))}}class m2{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof m2)return t;if("string"==typeof t){const e=c2.parse(t);if(!e)return;return new m2([e])}if(!Array.isArray(t))return;const e=[];for(const n of t){if("string"!=typeof n)return;const t=c2.parse(n);if(!t)return;e.push(t)}return new m2(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,n,r="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof n&&n>=0&&n<=255?void 0===r||"number"==typeof r&&r>=0&&r<=1?null:`Invalid rgba value [${[t,e,n,r].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof r?[t,e,n,r]:[t,e,n]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function C2(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof _2||t instanceof c2||t instanceof u2||t instanceof p2||t instanceof f2||t instanceof g2||t instanceof m2||t instanceof b2||t instanceof w2)return!0;if(Array.isArray(t)){for(const e of t)if(!C2(e))return!1;return!0}if("object"==typeof t){for(const e in t)if(!C2(t[e]))return!1;return!0}return!1}function S2(t){if(null===t)return y1;if("string"==typeof t)return b1;if("boolean"==typeof t)return w1;if("number"==typeof t)return v1;if(t instanceof c2)return _1;if(t instanceof _2)return x1;if(t instanceof u2)return k1;if(t instanceof p2)return E1;if(t instanceof f2)return T1;if(t instanceof g2)return M1;if(t instanceof m2)return R1;if(t instanceof b2)return I1;if(t instanceof w2)return L1;if(Array.isArray(t)){const e=t.length;let n;for(const r of t){const t=S2(r);if(n){if(n===t)continue;n=S1;break}n=t}return P1(n||S1,e)}return C1}function k2(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof c2||t instanceof _2||t instanceof p2||t instanceof f2||t instanceof g2||t instanceof m2||t instanceof b2||t instanceof w2?t.toString():JSON.stringify(t)}class E2{constructor(t,e){this.type=t,this.value=e}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!C2(t[1]))return e.error("invalid value");const n=t[1];let r=S2(n);const i=e.expectedType;return"array"!==r.kind||0!==r.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(r=i),new E2(r,n)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const T2={string:b1,number:v1,boolean:w1,object:C1};class R2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n,r=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const n=t[1];if("string"!=typeof n||!(n in T2)||"object"===n)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=T2[n],r++}else i=S1;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],r++}n=P1(i,s)}else{if(!T2[i])throw new Error(`Types doesn't contain name = ${i}`);n=T2[i]}const s=[];for(;rt.outputDefined())}}const M2={"to-boolean":w1,"to-color":_1,"to-number":v1,"to-string":b1};class L2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[0];if(!M2[n])throw new Error(`Can't parse ${n} as it is not part of the known types`);if(("to-boolean"===n||"to-string"===n)&&2!==t.length)return e.error("Expected one argument.");const r=M2[n],i=[];for(let s=1;s4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:x2(e[0],e[1],e[2],e[3]),!n))return new c2(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new y2(n||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const n of this.args){e=n.evaluate(t);const r=f2.parse(e);if(r)return r}throw new y2(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"numberArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=g2.parse(e);if(r)return r}throw new y2(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"colorArray":{let e;for(const n of this.args){e=n.evaluate(t);const r=m2.parse(e);if(r)return r}throw new y2(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const n of this.args){e=n.evaluate(t);const r=b2.parse(e);if(r)return r}throw new y2(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const n of this.args){if(e=n.evaluate(t),null===e)return 0;const r=Number(e);if(!isNaN(r))return r}throw new y2(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return p2.fromString(k2(this.args[0].evaluate(t)));case"resolvedImage":return w2.fromString(k2(this.args[0].evaluate(t)));case"projectionDefinition":return this.args[0].evaluate(t);default:return k2(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every(t=>t.outputDefined())}}const I2=["Unknown","Point","LineString","Polygon"];class P2{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?I2[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=c2.parse(t),this._parseColorCache.set(t,e)),e}}class A2{constructor(t,e,n=[],r,i=new m1,s=[]){this.registry=t,this.path=n,this.key=n.map(t=>`[${t}]`).join(""),this.scope=i,this.errors=s,this.expectedType=r,this._isConstant=e}parse(t,e,n,r,i={}){return e?this.concat(e,n,r)._parse(t,i):this._parse(t,i)}_parse(t,e){function n(t,e,n){return"assert"===n?new R2(e,[t]):"coerce"===n?new L2(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const r=t[0];if("string"!=typeof r)return this.error(`Expression name must be a string, but found ${typeof r} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[r];if(i){let r=i.parse(t,this);if(!r)return null;if(this.expectedType){const t=this.expectedType,i=r.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))r=n(r,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else r=n(r,t,e.typeAnnotation||"assert")}if(!(r instanceof E2)&&"resolvedImage"!==r.type.kind&&this._isConstant(r)){const t=new P2;try{r=new E2(r.type,r.evaluate(t))}catch(ej){return this.error(ej.message),null}}return r}return this.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error(`Expected an array, but found ${typeof t} instead.`)}concat(t,e,n){const r="number"==typeof t?this.path.concat(t):this.path,i=n?this.scope.concat(n):this.scope;return new A2(this.registry,this._isConstant,r,e||null,i,this.errors)}error(t,...e){const n=`${this.key}${e.map(t=>`[${t}]`).join("")}`;this.errors.push(new g1(n,t))}checkSubtype(t,e){const n=F1(t,e);return n&&this.error(n),n}}class O2{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result)}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const n=[];for(let i=1;i=n.length)throw new y2(`Array index out of bounds: ${e} > ${n.length-1}.`);if(e!==Math.floor(e))throw new y2(`Array index must be an integer, but found ${e} instead.`);return n[e]}eachChild(t){t(this.index),t(this.input)}outputDefined(){return!1}}class D2{constructor(t,e){this.type=w1,this.needle=t,this.haystack=e}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,S1);return n&&r?z1(n.type,[w1,b1,v1,y1,S1])?new D2(n,r):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${A1(n.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!n)return!1;if(!D1(e,["boolean","string","number","null"]))throw new y2(`Expected first argument to be of type boolean, string, number or null, but found ${A1(S2(e))} instead.`);if(!D1(n,["string","array"]))throw new y2(`Expected second argument to be of type array or string, but found ${A1(S2(n))} instead.`);return n.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack)}outputDefined(){return!0}}class N2{constructor(t,e,n){this.type=v1,this.needle=t,this.haystack=e,this.fromIndex=n}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,S1);if(!n||!r)return null;if(!z1(n.type,[w1,b1,v1,y1,S1]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${A1(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,v1);return i?new N2(n,r,i):null}return new N2(n,r)}evaluate(t){const e=this.needle.evaluate(t),n=this.haystack.evaluate(t);if(!D1(e,["boolean","string","number","null"]))throw new y2(`Expected first argument to be of type boolean, string, number or null, but found ${A1(S2(e))} instead.`);let r;if(this.fromIndex&&(r=this.fromIndex.evaluate(t)),D1(n,["string"])){const t=n.indexOf(e,r);return-1===t?-1:[...n.slice(0,t)].length}if(D1(n,["array"]))return n.indexOf(e,r);throw new y2(`Expected second argument to be of type array or string, but found ${A1(S2(n))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex)}outputDefined(){return!1}}class j2{constructor(t,e,n,r,i,s){this.inputType=t,this.type=e,this.input=n,this.cases=r,this.outputs=i,this.otherwise=s}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let n,r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const i={},s=[];for(let l=2;lNumber.MAX_SAFE_INTEGER)return c.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return c.error("Numeric branch labels must be integer values.");if(n){if(c.checkSubtype(n,S2(t)))return null}else n=S2(t);if(void 0!==i[String(t)])return c.error("Branch labels must be unique.");i[String(t)]=s.length}const u=e.parse(a,l,r);if(!u)return null;r=r||u.type,s.push(u)}const o=e.parse(t[1],1,S1);if(!o)return null;const a=e.parse(t[t.length-1],t.length-1,r);return a?"value"!==o.type.kind&&e.concat(1).checkSubtype(n,o.type)?null:new j2(n,r,o,i,s,a):null}evaluate(t){const e=this.input.evaluate(t);return(S2(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)}outputDefined(){return this.outputs.every(t=>t.outputDefined())&&this.otherwise.outputDefined()}}class B2{constructor(t,e,n){this.type=t,this.branches=e,this.otherwise=n}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const r=[];for(let s=1;se.outputDefined())&&this.otherwise.outputDefined()}}class U2{constructor(t,e,n,r){this.type=t,this.input=e,this.beginIndex=n,this.endIndex=r}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const n=e.parse(t[1],1,S1),r=e.parse(t[2],2,v1);if(!n||!r)return null;if(!z1(n.type,[P1(S1),b1,S1]))return e.error(`Expected first argument to be of type array or string, but found ${A1(n.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,v1);return i?new U2(n.type,n,r,i):null}return new U2(n.type,n,r)}evaluate(t){const e=this.input.evaluate(t),n=this.beginIndex.evaluate(t);let r;if(this.endIndex&&(r=this.endIndex.evaluate(t)),D1(e,["string"]))return[...e].slice(n,r).join("");if(D1(e,["array"]))return e.slice(n,r);throw new y2(`Expected first argument to be of type array or string, but found ${A1(S2(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex)}outputDefined(){return!1}}function $2(t,e){const n=t.length-1;let r,i,s=0,o=n,a=0;for(;s<=o;)if(a=Math.floor((s+o)/2),r=t[a],i=t[a+1],r<=e){if(a===n||ee))throw new y2("Input is not a number.");o=a-1}return 0}class q2{constructor(t,e,n){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[r,i]of n)this.labels.push(r),this.outputs.push(i)}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const n=e.parse(t[1],1,v1);if(!n)return null;const r=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let s=1;s=n)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const c=e.parse(o,l,i);if(!c)return null;i=i||c.type,r.push([n,c])}return new q2(i,n,r)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;return r>=e[i-1]?n[i-1].evaluate(t):n[$2(e,r)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every(t=>t.outputDefined())}}function V2(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W2,H2,G2=function(){if(H2)return W2;function t(t,e,n,r){this.cx=3*t,this.bx=3*(n-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=n,this.p2y=r}return H2=1,W2=t,t.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var n=t,r=0;r<8;r++){var i=this.sampleCurveX(n)-t;if(Math.abs(i)i?o=n:a=n,n=.5*(a-o)+o;return n},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},W2}(),K2=V2(G2);class Z2{constructor(t,e,n,r,i){this.type=t,this.operator=e,this.interpolation=n,this.input=r,this.labels=[],this.outputs=[];for(const[s,o]of i)this.labels.push(s),this.outputs.push(o)}static interpolationFactor(t,e,n,r){let i=0;if("exponential"===t.name)i=Y2(e,t.base,n,r);else if("linear"===t.name)i=Y2(e,1,n,r);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new K2(s[0],s[1],s[2],s[3]).solve(Y2(e,1,n,r))}return i}static parse(t,e){let[n,r,i,...s]=t;if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){const t=r[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:t}}else{if("cubic-bezier"!==r[0])return e.error(`Unknown interpolation type ${String(r[0])}`,1,0);{const t=r.slice(1);if(4!==t.length||t.some(t=>"number"!=typeof t||t<0||t>1))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:t}}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,v1),!i)return null;const o=[];let a=null;"interpolate-hcl"!==n&&"interpolate-lab"!==n||e.expectedType==R1?e.expectedType&&"value"!==e.expectedType.kind&&(a=e.expectedType):a=_1;for(let l=0;l=t)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',r);const c=e.parse(n,i,a);if(!c)return null;a=a||c.type,o.push([t,c])}return N1(a,v1)||N1(a,x1)||N1(a,_1)||N1(a,T1)||N1(a,M1)||N1(a,R1)||N1(a,I1)||N1(a,P1(v1))?new Z2(a,n,r,i,o):e.error(`Type ${A1(a)} is not interpolatable.`)}evaluate(t){const e=this.labels,n=this.outputs;if(1===e.length)return n[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return n[0].evaluate(t);const i=e.length;if(r>=e[i-1])return n[i-1].evaluate(t);const s=$2(e,r),o=e[s],a=e[s+1],l=Z2.interpolationFactor(this.interpolation,r,o,a),c=n[s].evaluate(t),u=n[s+1].evaluate(t);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return a2(c,u,l);case"color":return c2.interpolate(c,u,l);case"padding":return f2.interpolate(c,u,l);case"colorArray":return m2.interpolate(c,u,l);case"numberArray":return g2.interpolate(c,u,l);case"variableAnchorOffsetCollection":return b2.interpolate(c,u,l);case"array":return l2(c,u,l);case"projectionDefinition":return _2.interpolate(c,u,l)}case"interpolate-hcl":switch(this.type.kind){case"color":return c2.interpolate(c,u,l,"hcl");case"colorArray":return m2.interpolate(c,u,l,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return c2.interpolate(c,u,l,"lab");case"colorArray":return m2.interpolate(c,u,l,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every(t=>t.outputDefined())}}function Y2(t,e,n,r){const i=r-n,s=t-n;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}class X2{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let n=null;const r=e.expectedType;r&&"value"!==r.kind&&(n=r);const i=[];for(const o of t.slice(1)){const t=e.parse(o,1+i.length,n,void 0,{typeAnnotation:"omit"});if(!t)return null;n=n||t.type,i.push(t)}if(!n)throw new Error("No output type");const s=r&&i.some(t=>F1(r,t.type));return new X2(s?S1:n,i)}evaluate(t){let e,n=null,r=0;for(const i of this.args)if(r++,n=i.evaluate(t),n&&n instanceof w2&&!n.available&&(e||(e=n.name),n=null,r===this.args.length&&(n=e)),null!==n)break;return n}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every(t=>t.outputDefined())}}function J2(t,e){return"=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function Q2(t,e,n,r){return 0===r.compare(e,n)}function t3(t,e,n){const r="=="!==t&&"!="!==t;return class i{constructor(t,e,n){this.type=w1,this.lhs=t,this.rhs=e,this.collator=n,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const n=t[0];let s=e.parse(t[1],1,S1);if(!s)return null;if(!J2(n,s.type))return e.concat(1).error(`"${n}" comparisons are not supported for type '${A1(s.type)}'.`);let o=e.parse(t[2],2,S1);if(!o)return null;if(!J2(n,o.type))return e.concat(2).error(`"${n}" comparisons are not supported for type '${A1(o.type)}'.`);if(s.type.kind!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error(`Cannot compare types '${A1(s.type)}' and '${A1(o.type)}'.`);r&&("value"===s.type.kind&&"value"!==o.type.kind?s=new R2(o.type,[s]):"value"!==s.type.kind&&"value"===o.type.kind&&(o=new R2(s.type,[o])));let a=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(a=e.parse(t[3],3,k1),!a)return null}return new i(s,o,a)}evaluate(i){const s=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(r&&this.hasUntypedArgument){const e=S2(s),n=S2(o);if(e.kind!==n.kind||"string"!==e.kind&&"number"!==e.kind)throw new y2(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${n.kind}) instead.`)}if(this.collator&&!r&&this.hasUntypedArgument){const t=S2(s),n=S2(o);if("string"!==t.kind||"string"!==n.kind)return e(i,s,o)}return this.collator?n(i,s,o,this.collator.evaluate(i)):e(i,s,o)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator)}outputDefined(){return!0}}}const e3=t3("==",function(t,e,n){return e===n},Q2),n3=t3("!=",function(t,e,n){return e!==n},function(t,e,n,r){return!Q2(0,e,n,r)}),r3=t3("<",function(t,e,n){return e",function(t,e,n){return e>n},function(t,e,n,r){return r.compare(e,n)>0}),s3=t3("<=",function(t,e,n){return e<=n},function(t,e,n,r){return r.compare(e,n)<=0}),o3=t3(">=",function(t,e,n){return e>=n},function(t,e,n,r){return r.compare(e,n)>=0});class a3{constructor(t,e,n){this.type=k1,this.locale=n,this.caseSensitive=t,this.diacriticSensitive=e}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const n=t[1];if("object"!=typeof n||Array.isArray(n))return e.error("Collator options argument must be an object.");const r=e.parse(void 0!==n["case-sensitive"]&&n["case-sensitive"],1,w1);if(!r)return null;const i=e.parse(void 0!==n["diacritic-sensitive"]&&n["diacritic-sensitive"],1,w1);if(!i)return null;let s=null;return n.locale&&(s=e.parse(n.locale,1,b1),!s)?null:new a3(r,i,s)}evaluate(t){return new u2(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale)}outputDefined(){return!1}}class l3{constructor(t,e,n,r,i){this.type=b1,this.number=t,this.locale=e,this.currency=n,this.minFractionDigits=r,this.maxFractionDigits=i}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,v1);if(!n)return null;const r=t[2];if("object"!=typeof r||Array.isArray(r))return e.error("NumberFormat options argument must be an object.");let i=null;if(r.locale&&(i=e.parse(r.locale,1,b1),!i))return null;let s=null;if(r.currency&&(s=e.parse(r.currency,1,b1),!s))return null;let o=null;if(r["min-fraction-digits"]&&(o=e.parse(r["min-fraction-digits"],1,v1),!o))return null;let a=null;return r["max-fraction-digits"]&&(a=e.parse(r["max-fraction-digits"],1,v1),!a)?null:new l3(n,i,s,o,a)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits)}outputDefined(){return!1}}class c3{constructor(t){this.type=E1,this.sections=t}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const n=t[1];if(!Array.isArray(n)&&"object"==typeof n)return e.error("First argument must be an image or text section.");const r=[];let i=!1;for(let s=1;s<=t.length-1;++s){const n=t[s];if(i&&"object"==typeof n&&!Array.isArray(n)){i=!1;let t=null;if(n["font-scale"]&&(t=e.parse(n["font-scale"],1,v1),!t))return null;let s=null;if(n["text-font"]&&(s=e.parse(n["text-font"],1,P1(b1)),!s))return null;let o=null;if(n["text-color"]&&(o=e.parse(n["text-color"],1,_1),!o))return null;let a=null;if(n["vertical-align"]){if("string"==typeof n["vertical-align"]&&!h2.includes(n["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${n["vertical-align"]}' instead.`);if(a=e.parse(n["vertical-align"],1,b1),!a)return null}const l=r[r.length-1];l.scale=t,l.font=s,l.textColor=o,l.verticalAlign=a}else{const n=e.parse(t[s],1,S1);if(!n)return null;const o=n.type.kind;if("string"!==o&&"value"!==o&&"null"!==o&&"resolvedImage"!==o)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,r.push({content:n,scale:null,font:null,textColor:null,verticalAlign:null})}}return new c3(r)}evaluate(t){return new p2(this.sections.map(e=>{const n=e.content.evaluate(t);return S2(n)===L1?new d2("",n,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new d2(k2(n),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)}))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign)}outputDefined(){return!1}}class u3{constructor(t){this.type=L1,this.input=t}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const n=e.parse(t[1],1,b1);return n?new u3(n):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),n=w2.fromString(e);return n&&t.availableImages&&(n.available=t.availableImages.indexOf(e)>-1),n}eachChild(t){t(this.input)}outputDefined(){return!1}}class h3{constructor(t){this.type=v1,this.input=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=e.parse(t[1],1);return n?"array"!==n.type.kind&&"string"!==n.type.kind&&"value"!==n.type.kind?e.error(`Expected argument of type string or array, but found ${A1(n.type)} instead.`):new h3(n):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return[...e].length;if(Array.isArray(e))return e.length;throw new y2(`Expected value to be of type string or array, but found ${A1(S2(e))} instead.`)}eachChild(t){t(this.input)}outputDefined(){return!1}}const d3=8192;function p3(t,e){const n=(180+t[0])/360,r=(i=t[1],(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+i*Math.PI/360)))/360);var i;const s=Math.pow(2,e.z);return[Math.round(n*s*d3),Math.round(r*s*d3)]}function f3(t,e){const n=Math.pow(2,e.z);return[(i=(t[0]/d3+e.x)/n,360*i-180),(r=(t[1]/d3+e.y)/n,360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90)];var r,i}function g3(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1])}function m3(t,e){return!(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function y3(t,e,n){return e[1]>t[1]!=n[1]>t[1]&&t[0]<(n[0]-e[0])*(t[1]-e[1])/(n[1]-e[1])+e[0]}function v3(t,e,n){const r=t[0]-e[0],i=t[1]-e[1],s=t[0]-n[0],o=t[1]-n[1];return r*o-s*i===0&&r*s<=0&&i*o<=0}function b3(t,e,n,r){const i=[e[0]-t[0],e[1]-t[1]];return 0!==function(t,e){return t[0]*e[1]-t[1]*e[0]}([r[0]-n[0],r[1]-n[1]],i)&&!(!k3(t,e,n,r)||!k3(n,r,t,e))}function w3(t,e,n){for(const r of n)for(let n=0;n0&&h<0||u<0&&h>0}function E3(t,e,n){const r=[];for(let i=0;in[2]){const e=.5*r;let i=t[0]-n[0]>e?-r:n[0]-t[0]>e?r:0;0===i&&(i=t[0]-n[2]>e?-r:n[2]-t[0]>e?r:0),t[0]+=i}g3(e,t)}function M3(t,e,n,r){const i=Math.pow(2,r.z)*d3,s=[r.x*d3,r.y*d3],o=[];for(const a of t)for(const t of a){const r=[t.x+s[0],t.y+s[1]];R3(r,e,n,i),o.push(r)}return o}function L3(t,e,n,r){const i=Math.pow(2,r.z)*d3,s=[r.x*d3,r.y*d3],o=[];for(const a of t){const t=[];for(const n of a){const r=[n.x+s[0],n.y+s[1]];g3(e,r),t.push(r)}o.push(t)}if(e[2]-e[0]<=i/2){!function(t){t[0]=t[1]=1/0,t[2]=t[3]=-1/0}(e);for(const t of o)for(const r of t)R3(r,e,n,i)}return o}class I3{constructor(t,e){this.type=w1,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(C2(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const n of e.features){const{type:e,coordinates:r}=n.geometry;"Polygon"===e&&t.push(r),"MultiPolygon"===e&&t.push(...r)}if(t.length)return new I3(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new I3(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new I3(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=E3(e.coordinates,r,i),o=M3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!_3(t,s))return!1}if("MultiPolygon"===e.type){const s=T3(e.coordinates,r,i),o=M3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!x3(t,s))return!1}return!0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=E3(e.coordinates,r,i),o=L3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!C3(t,s))return!1}if("MultiPolygon"===e.type){const s=T3(e.coordinates,r,i),o=L3(t.geometry(),n,r,i);if(!m3(n,r))return!1;for(const t of o)if(!S3(t,s))return!1}return!0}(t,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}class P3{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(t){this.data.push(t),this._up(this.length++)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:n}=this,r=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(n(r,s)>=0)break;e[t]=s,t=i}e[t]=r}_down(t){const{data:e,compare:n}=this,r=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[r],t=r}e[t]=i}}function A3(t){let e=0;for(let n,r,i=0,s=t.length,o=s-1;i1?(l=t[a+1][0],c=t[a+1][1]):d>0&&(l+=u/this.kx*d,c+=h/this.ky*d)),u=this.wrap(e[0]-l)*this.kx,h=(e[1]-c)*this.ky;const p=u*u+h*h;p180;)t-=360;return t}}function N3(t,e){return e[0]-t[0]}function j3(t){return t[1]-t[0]+1}function B3(t,e){return t[1]>=t[0]&&t[1]t[1])return[null,null];const n=j3(t);if(e){if(2===n)return[t,null];const e=Math.floor(n/2);return[[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===n)return[t,null];const r=Math.floor(n/2)-1;return[[t[0],t[0]+r],[t[0]+r+1,t[1]]]}function $3(t,e){if(!B3(e,t.length))return[1/0,1/0,-1/0,-1/0];const n=[1/0,1/0,-1/0,-1/0];for(let r=e[0];r<=e[1];++r)g3(n,t[r]);return n}function q3(t){const e=[1/0,1/0,-1/0,-1/0];for(const n of t)for(const t of n)g3(e,t);return e}function V3(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function W3(t,e,n){if(!V3(t)||!V3(e))return NaN;let r=0,i=0;return t[2]e[2]&&(r=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=r)return r;if(m3(i,s)){if(J3(t,e))return 0}else if(J3(e,t))return 0;let o=1/0;for(const a of t)for(let t=0,r=a.length,i=r-1;t0;){const i=o.pop();if(i[0]>=s)continue;const l=i[1],c=e?50:100;if(j3(l)<=c){if(!B3(l,t.length))return NaN;if(e){const e=X3(t,l,n,r);if(isNaN(e)||0===e)return e;s=Math.min(s,e)}else for(let e=l[0];e<=l[1];++e){const i=Y3(t[e],n,r);if(s=Math.min(s,i),0===s)return 0}}else{const n=U3(l,e);t5(o,s,r,t,a,n[0]),t5(o,s,r,t,a,n[1])}}return s}function r5(t,e,n,r,i,s=1/0){let o=Math.min(s,i.distance(t[0],n[0]));if(0===o)return o;const a=new P3([[0,[0,t.length-1],[0,n.length-1]]],N3);for(;a.length>0;){const s=a.pop();if(s[0]>=o)continue;const l=s[1],c=s[2],u=e?50:100,h=r?50:100;if(j3(l)<=u&&j3(c)<=h){if(!B3(l,t.length)&&B3(c,n.length))return NaN;let s;if(e&&r)s=K3(t,l,n,c,i),o=Math.min(o,s);else if(e&&!r){const e=t.slice(l[0],l[1]+1);for(let t=c[0];t<=c[1];++t)if(s=H3(n[t],e,i),o=Math.min(o,s),0===o)return o}else if(!e&&r){const e=n.slice(c[0],c[1]+1);for(let n=l[0];n<=l[1];++n)if(s=H3(t[n],e,i),o=Math.min(o,s),0===o)return o}else s=Z3(t,l,n,c,i),o=Math.min(o,s)}else{const s=U3(l,e),u=U3(c,r);e5(a,o,i,t,n,s[0],u[0]),e5(a,o,i,t,n,s[0],u[1]),e5(a,o,i,t,n,s[1],u[0]),e5(a,o,i,t,n,s[1],u[1])}}return o}function i5(t){return"MultiPolygon"===t.type?t.coordinates.map(t=>({type:"Polygon",coordinates:t})):"MultiLineString"===t.type?t.coordinates.map(t=>({type:"LineString",coordinates:t})):"MultiPoint"===t.type?t.coordinates.map(t=>({type:"Point",coordinates:t})):[t]}class s5{constructor(t,e){this.type=v1,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(C2(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new s5(e,e.features.map(t=>i5(t.geometry)).flat());if("Feature"===e.type)return new s5(e,i5(e.geometry));if("type"in e&&"coordinates"in e)return new s5(e,i5(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map(e=>f3([e.x,e.y],t.canonical));if(0===n.length)return NaN;const i=new D3(r[0][1]);let s=1/0;for(const o of e){switch(o.type){case"Point":s=Math.min(s,r5(r,!1,[o.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,r5(r,!1,o.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,n5(r,!1,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const n=t.geometry(),r=n.flat().map(e=>f3([e.x,e.y],t.canonical));if(0===n.length)return NaN;const i=new D3(r[0][1]);let s=1/0;for(const o of e){switch(o.type){case"Point":s=Math.min(s,r5(r,!0,[o.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,r5(r,!0,o.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,n5(r,!0,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const n=t.geometry();if(0===n.length||0===n[0].length)return NaN;const r=function(t){if(t.length<=1)return[t];const e=[];let n,r;for(const i of t){const t=A3(i);0!==t&&(i.area=Math.abs(t),void 0===r&&(r=t<0),r===t<0?(n&&e.push(n),n=[i]):n.push(i))}return n&&e.push(n),e}(n).map(e=>e.map(e=>e.map(e=>f3([e.x,e.y],t.canonical)))),i=new D3(r[0][0][0][1]);let s=1/0;for(const o of e)for(const t of r){switch(o.type){case"Point":s=Math.min(s,n5([o.coordinates],!1,t,i,s));break;case"LineString":s=Math.min(s,n5(o.coordinates,!0,t,i,s));break;case"Polygon":s=Math.min(s,Q3(t,o.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class o5{constructor(t){this.type=S1,this.key=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const n=t[1];return null==n?e.error("Global state property must be defined."):"string"!=typeof n?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new o5(n)}evaluate(t){var e;const n=null===(e=t.globals)||void 0===e?void 0:e.globalState;return n&&0!==Object.keys(n).length?e2(n,this.key):null}eachChild(){}outputDefined(){return!1}}const a5={"==":e3,"!=":n3,">":i3,"<":r3,">=":o3,"<=":s3,array:R2,at:z2,boolean:R2,case:B2,coalesce:X2,collator:a3,format:c3,image:u3,in:D2,"index-of":N2,interpolate:Z2,"interpolate-hcl":Z2,"interpolate-lab":Z2,length:h3,let:O2,literal:E2,match:j2,number:R2,"number-format":l3,object:R2,slice:U2,step:q2,string:R2,"to-boolean":L2,"to-color":L2,"to-number":L2,"to-string":L2,var:F2,within:I3,distance:s5,"global-state":o5};class l5{constructor(t,e,n,r){this.name=t,this.type=e,this._evaluate=n,this.args=r}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t)}outputDefined(){return!1}static parse(t,e){const n=t[0],r=l5.definitions[n];if(!r)return e.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(r)?r[0]:r.type,s=Array.isArray(r)?[[r[1],r[2]]]:r.overloads,o=s.filter(([e])=>!Array.isArray(e)||e.length===t.length-1);let a=null;for(const[l,c]of o){a=new A2(e.registry,p5,e.path,null,e.scope);const r=[];let s=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(A1).join(", ")})`:`(${A1(e.type)}...)`;var e}).join(" | "),r=[];for(let i=1;i{n=e?n&&p5(t):n&&t instanceof E2}),!!n&&f5(t)&&m5(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function f5(t){if(t instanceof l5){if("get"===t.name&&1===t.args.length)return!1;if("feature-state"===t.name)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}if(t instanceof I3)return!1;if(t instanceof s5)return!1;let e=!0;return t.eachChild(t=>{e&&!f5(t)&&(e=!1)}),e}function g5(t){if(t instanceof l5&&"feature-state"===t.name)return!1;let e=!0;return t.eachChild(t=>{e&&!g5(t)&&(e=!1)}),e}function m5(t,e){if(t instanceof l5&&e.indexOf(t.name)>=0)return!1;let n=!0;return t.eachChild(t=>{n&&!m5(t,e)&&(n=!1)}),n}function y5(t){return{result:"success",value:t}}function v5(t){return{result:"error",value:t}}function b5(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)&&S2(t)===C1}l5.register(a5,{error:[{kind:"error"},[b1],(t,[e])=>{throw new y2(e.evaluate(t))}],typeof:[b1,[S1],(t,[e])=>A1(S2(e.evaluate(t)))],"to-rgba":[P1(v1,4),[_1],(t,[e])=>{const[n,r,i,s]=e.evaluate(t).rgb;return[255*n,255*r,255*i,s]}],rgb:[_1,[v1,v1,v1],c5],rgba:[_1,[v1,v1,v1,v1],c5],has:{type:w1,overloads:[[[b1],(t,[e])=>u5(e.evaluate(t),t.properties())],[[b1,C1],(t,[e,n])=>u5(e.evaluate(t),n.evaluate(t))]]},get:{type:S1,overloads:[[[b1],(t,[e])=>h5(e.evaluate(t),t.properties())],[[b1,C1],(t,[e,n])=>h5(e.evaluate(t),n.evaluate(t))]]},"feature-state":[S1,[b1],(t,[e])=>h5(e.evaluate(t),t.featureState||{})],properties:[C1,[],t=>t.properties()],"geometry-type":[b1,[],t=>t.geometryType()],id:[S1,[],t=>t.id()],zoom:[v1,[],t=>t.globals.zoom],"heatmap-density":[v1,[],t=>t.globals.heatmapDensity||0],elevation:[v1,[],t=>t.globals.elevation||0],"line-progress":[v1,[],t=>t.globals.lineProgress||0],accumulated:[S1,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[v1,d5(v1),(t,e)=>{let n=0;for(const r of e)n+=r.evaluate(t);return n}],"*":[v1,d5(v1),(t,e)=>{let n=1;for(const r of e)n*=r.evaluate(t);return n}],"-":{type:v1,overloads:[[[v1,v1],(t,[e,n])=>e.evaluate(t)-n.evaluate(t)],[[v1],(t,[e])=>-e.evaluate(t)]]},"/":[v1,[v1,v1],(t,[e,n])=>e.evaluate(t)/n.evaluate(t)],"%":[v1,[v1,v1],(t,[e,n])=>e.evaluate(t)%n.evaluate(t)],ln2:[v1,[],()=>Math.LN2],pi:[v1,[],()=>Math.PI],e:[v1,[],()=>Math.E],"^":[v1,[v1,v1],(t,[e,n])=>Math.pow(e.evaluate(t),n.evaluate(t))],sqrt:[v1,[v1],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))],log2:[v1,[v1],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[v1,[v1],(t,[e])=>Math.sin(e.evaluate(t))],cos:[v1,[v1],(t,[e])=>Math.cos(e.evaluate(t))],tan:[v1,[v1],(t,[e])=>Math.tan(e.evaluate(t))],asin:[v1,[v1],(t,[e])=>Math.asin(e.evaluate(t))],acos:[v1,[v1],(t,[e])=>Math.acos(e.evaluate(t))],atan:[v1,[v1],(t,[e])=>Math.atan(e.evaluate(t))],min:[v1,d5(v1),(t,e)=>Math.min(...e.map(e=>e.evaluate(t)))],max:[v1,d5(v1),(t,e)=>Math.max(...e.map(e=>e.evaluate(t)))],abs:[v1,[v1],(t,[e])=>Math.abs(e.evaluate(t))],round:[v1,[v1],(t,[e])=>{const n=e.evaluate(t);return n<0?-Math.round(-n):Math.round(n)}],floor:[v1,[v1],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[v1,[v1],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[w1,[b1,S1],(t,[e,n])=>t.properties()[e.value]===n.value],"filter-id-==":[w1,[S1],(t,[e])=>t.id()===e.value],"filter-type-==":[w1,[b1],(t,[e])=>t.geometryType()===e.value],"filter-<":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r{const n=t.id(),r=e.value;return typeof n==typeof r&&n":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>i}],"filter-id->":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>r}],"filter-<=":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r<=i}],"filter-id-<=":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n<=r}],"filter->=":[w1,[b1,S1],(t,[e,n])=>{const r=t.properties()[e.value],i=n.value;return typeof r==typeof i&&r>=i}],"filter-id->=":[w1,[S1],(t,[e])=>{const n=t.id(),r=e.value;return typeof n==typeof r&&n>=r}],"filter-has":[w1,[S1],(t,[e])=>e.value in t.properties()],"filter-has-id":[w1,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[w1,[P1(b1)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[w1,[P1(S1)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[w1,[b1,P1(S1)],(t,[e,n])=>n.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[w1,[b1,P1(S1)],(t,[e,n])=>function(t,e,n,r){for(;n<=r;){const i=n+r>>1;if(e[i]===t)return!0;e[i]>t?r=i-1:n=i+1}return!1}(t.properties()[e.value],n.value,0,n.value.length-1)],all:{type:w1,overloads:[[[w1,w1],(t,[e,n])=>e.evaluate(t)&&n.evaluate(t)],[d5(w1),(t,e)=>{for(const n of e)if(!n.evaluate(t))return!1;return!0}]]},any:{type:w1,overloads:[[[w1,w1],(t,[e,n])=>e.evaluate(t)||n.evaluate(t)],[d5(w1),(t,e)=>{for(const n of e)if(n.evaluate(t))return!0;return!1}]]},"!":[w1,[w1],(t,[e])=>!e.evaluate(t)],"is-supported-script":[w1,[b1],(t,[e])=>{const n=t.globals&&t.globals.isSupportedScript;return!n||n(e.evaluate(t))}],upcase:[b1,[b1],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[b1,[b1],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[b1,d5(S1),(t,e)=>e.map(e=>k2(e.evaluate(t))).join("")],"resolved-locale":[b1,[k1],(t,[e])=>e.evaluate(t).resolvedLocale()]});class w5{constructor(t,e){this.expression=t,this._warningHistory={},this._evaluator=new P2,this._defaultValue=e?function(t){if("color"===t.type&&b5(t.default))return new c2(0,0,0,0);switch(t.type){case"color":return c2.parse(t.default)||null;case"padding":return f2.parse(t.default)||null;case"numberArray":return g2.parse(t.default)||null;case"colorArray":return m2.parse(t.default)||null;case"variableAnchorOffsetCollection":return b2.parse(t.default)||null;case"projectionDefinition":return _2.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=n,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,n,r,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=n||null,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new y2(`Expected value to be one of ${Object.keys(this._enumValues).map(t=>JSON.stringify(t)).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(ej){return this._warningHistory[ej.message]||(this._warningHistory[ej.message]=!0,"undefined"!=typeof console&&console.warn(ej.message)),this._defaultValue}}}function _5(t,e){const n=new A2(a5,p5,[],e?function(t){const e={color:_1,string:b1,number:v1,enum:b1,boolean:w1,formatted:E1,padding:T1,numberArray:M1,colorArray:R1,projectionDefinition:x1,resolvedImage:L1,variableAnchorOffsetCollection:I1};return"array"===t.type?P1(e[t.value]||S1,t.length):e[t.type]}(e):void 0),r=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return r?y5(new w5(r,e)):v5(n.errors)}class x5{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!g5(e.expression),this.globalStateRefs=E5(e.expression)}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._styleExpression.evaluate(t,e,n,r,i,s)}}class C5{constructor(t,e,n,r){this.kind=t,this.zoomStops=n,this._styleExpression=e,this.isStateDependent="camera"!==t&&!g5(e.expression),this.globalStateRefs=E5(e.expression),this.interpolationType=r}evaluateWithoutErrorHandling(t,e,n,r,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,n,r,i,s)}evaluate(t,e,n,r,i,s){return this._styleExpression.evaluate(t,e,n,r,i,s)}interpolationFactor(t,e,n){return this.interpolationType?Z2.interpolationFactor(this.interpolationType,t,e,n):0}}function S5(t,e){const n=_5(t,e);if("error"===n.result)return n;const r=n.value.expression,i=f5(r);if(!i&&"data-driven"!==(s=e)["property-type"]&&"cross-faded-data-driven"!==s["property-type"])return v5([new g1("","data expressions not supported")]);var s;const o=m5(r,["zoom"]);if(!o&&!function(t){return!!t.expression&&t.expression.parameters.indexOf("zoom")>-1}(e))return v5([new g1("","zoom expressions not supported")]);const a=k5(r);if(!a&&!o)return v5([new g1("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);if(a instanceof g1)return v5([a]);if(a instanceof Z2&&!function(t){return!!t.expression&&t.expression.interpolated}(e))return v5([new g1("",'"interpolate" expressions cannot be used with this property')]);if(!a)return y5(new x5(i?"constant":"source",n.value));const l=a instanceof Z2?a.interpolation:void 0;return y5(new C5(i?"camera":"composite",n.value,a.labels,l))}function k5(t){let e=null;if(t instanceof O2)e=k5(t.result);else if(t instanceof X2){for(const n of t.args)if(e=k5(n),e)break}else(t instanceof q2||t instanceof Z2)&&t.input instanceof l5&&"zoom"===t.input.name&&(e=t);return e instanceof g1||t.eachChild(t=>{const n=k5(t);n instanceof g1?e=n:!e&&n?e=new g1("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&n&&e!==n&&(e=new g1("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),e}function E5(t,e=new Set){return t instanceof o5&&e.add(t.key),t.eachChild(t=>{E5(t,e)}),e}function T5(t){if(!0===t||!1===t)return!0;if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!T5(e)&&"boolean"!=typeof e)return!1;return!0;default:return!0}}const R5={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function M5(t){if(null==t)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};T5(t)||(t=P5(t));const e=_5(t,R5);if("error"===e.result)throw new Error(e.value.map(t=>`${t.key}: ${t.message}`).join(", "));return{filter:(t,n,r)=>e.value.evaluate(t,n,{},r),needGeometry:I5(t),getGlobalStateRefs:()=>E5(e.value.expression)}}function L5(t,e){return te?1:0}function I5(t){if(!Array.isArray(t))return!1;if("within"===t[0]||"distance"===t[0])return!0;for(let e=1;e"===e||"<="===e||">="===e?A5(t[1],t[2],e):"any"===e?(n=t.slice(1),["any"].concat(n.map(P5))):"all"===e?["all"].concat(t.slice(1).map(P5)):"none"===e?["all"].concat(t.slice(1).map(P5).map(z5)):"in"===e?O5(t[1],t.slice(2)):"!in"===e?z5(O5(t[1],t.slice(2))):"has"===e?F5(t[1]):"!has"!==e||z5(F5(t[1]));var n}function A5(t,e,n){switch(t){case"$type":return[`filter-type-${n}`,e];case"$id":return[`filter-id-${n}`,e];default:return[`filter-${n}`,t,e]}}function O5(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(t=>typeof t!=typeof e[0])?["filter-in-large",t,["literal",e.sort(L5)]]:["filter-in-small",t,["literal",e]]}}function F5(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function z5(t){return["!",t]}function D5(t){return"object"==typeof t?["literal",t]:t}function N5(t){switch(t.colorSpace){case"hcl":return"interpolate-hcl";case"lab":return"interpolate-lab";default:return"interpolate"}}function j5(t,e){const n=D5((r=t.default,i=e.default,void 0!==r?r:void 0!==i?i:void 0));var r,i;return void 0===n&&"resolvedImage"===e.type?"":n}function B5(t,e,n){const r=q5(t,e),i=["get",t.property];if("categorical"===r&&"boolean"==typeof n[0][0]){const r=["case"];for(const t of n)r.push(["==",i,t[0]],t[1]);return r.push(j5(t,e)),r}if("categorical"===r){const r=["match",i];for(const t of n)$5(r,t[0],t[1],!1);return r.push(j5(t,e)),r}if("interval"===r){const e=["step",["number",i]];for(const t of n)$5(e,t[0],t[1],!0);return U5(e),void 0===t.default?e:["case",["==",["typeof",i],"number"],e,D5(t.default)]}if("exponential"===r){const e=void 0!==t.base?t.base:1,r=[N5(t),1===e?["linear"]:["exponential",e],["number",i]];for(const t of n)$5(r,t[0],t[1],!1);return void 0===t.default?r:["case",["==",["typeof",i],"number"],r,D5(t.default)]}throw new Error(`Unknown property function type ${r}`)}function U5(t){"step"===t[0]&&3===t.length&&(t.push(0),t.push(t[3]))}function $5(t,e,n,r){t.length>3&&e===t[t.length-2]||(r&&2===t.length||t.push(e),t.push(n))}function q5(t,e){return t.type?t.type:e.expression.interpolated?"exponential":"interval"}function V5(t){const e=["concat"],n=/{([^{}]+)}/g;let r=0;for(let i=n.exec(t);null!==i;i=n.exec(t)){const s=t.slice(r,n.lastIndex-i[0].length);r=n.lastIndex,s.length>0&&e.push(s),e.push(["get",i[1]])}if(1===e.length)return t;if(r":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};var H5={thin:100,hairline:100,"ultra-light":200,"extra-light":200,light:300,book:300,regular:400,normal:400,plain:400,roman:400,standard:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,heavy:900,black:900,"heavy-black":900,fat:900,poster:900,"ultra-black":950,"extra-black":950},G5=" ",K5=/(italic|oblique)$/i,Z5={};function Y5(t,e,n){var r=Z5[t];if(!r){Array.isArray(t)||(t=[t]);for(var i,s,o=400,a="normal",l=[],c=0,u=t.length;c1?h[h.length-2].toLowerCase():"";if(d==p||d==p.replace("-","")||f+"-"+d==p){o=i?o:H5[p],h.pop(),f&&p.startsWith(f)&&h.pop();break}}i||"number"!=typeof d||(o=d,i=!0);var g=h.join(G5).replace("Klokantech Noto Sans","Noto Sans").replace("DIN Pro","Barlow").replace("Arial Unicode MS","Arial");-1!==g.indexOf(G5)&&(g='"'+g+'"'),l.push(g)}r=Z5[t]=[a,o,l]}return r[0]+G5+r[1]+G5+e+"px"+(n?"/"+n:"")+G5+r[2]}class X5 extends iJ{constructor(t,e,n,r,i){super(t,e,n,void 0!==i?0:2),this.loader_=void 0!==i?i:null,this.canvas_=r,this.error_=null}getError(){return this.error_}handleLoad_(t){t?(this.error_=t,this.state=3):this.state=2,this.changed()}load(){0==this.state&&(this.state=1,this.changed(),this.loader_(this.handleLoad_.bind(this)))}getImage(){return this.canvas_}}class J5 extends dV{constructor(t,e,n){super(),n=n||{},this.tileCoord=t,this.state=e,this.key="",this.transition_=void 0===n.transition?250:n.transition,this.transitionStarts_={},this.interpolate=!!n.interpolate}changed(){this.dispatchEvent(Vq)}release(){this.setState(4)}getKey(){return this.key+"/"+this.tileCoord}getTileCoord(){return this.tileCoord}getState(){return this.state}setState(t){if(4!==this.state){if(3!==this.state&&this.state>t)throw new Error("Tile load sequence violation");this.state=t,this.changed()}}load(){yV()}getAlpha(t,e){if(!this.transition_)return 1;let n=this.transitionStarts_[t];if(n){if(-1===n)return 1}else n=e,this.transitionStarts_[t]=n;const r=e-n+1e3/60;return r>=this.transition_?1:GW(r/this.transition_)}inTransition(t){return!!this.transition_&&-1!==this.transitionStarts_[t]}endTransition(t){this.transition_&&(this.transitionStarts_[t]=-1)}disposeInternal(){this.release(),super.disposeInternal()}}class Q5 extends J5{constructor(t,e,n,r,i,s){super(t,e,s),this.crossOrigin_=r,this.src_=n,this.key=n,this.image_,PV?this.image_=new OffscreenCanvas(1,1):(this.image_=new Image,null!==r&&(this.image_.crossOrigin=r)),this.unlisten_=null,this.tileLoadFunction_=i}getImage(){return this.image_}setImage(t){this.image_=t,this.state=2,this.unlistenImage_(),this.changed()}getCrossOrigin(){return this.crossOrigin_}handleImageError_(){this.state=3,this.unlistenImage_(),this.image_=function(){const t=AK(1,1);return t.fillStyle="rgba(0,0,0,0)",t.fillRect(0,0,1,1),t.canvas}(),this.changed()}handleImageLoad_(){if(PV)this.state=2;else{const t=this.image_;t.naturalWidth&&t.naturalHeight?this.state=2:this.state=4}this.unlistenImage_(),this.changed()}load(){3==this.state&&(this.state=0,this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)),0==this.state&&(this.state=1,this.changed(),this.tileLoadFunction_(this,this.src_),this.unlisten_=function(t,e,n){const r=t;let i=!0,s=!1,o=!1;const a=[fV(r,"load",function(){o=!0,s||e()})];return r.src&&AV?(s=!0,r.decode().then(function(){i&&e()}).catch(function(){i&&(o?e():n())})):a.push(fV(r,"error",n)),function(){i=!1,a.forEach(gV)}}(this.image_,this.handleImageLoad_.bind(this),this.handleImageError_.bind(this)))}unlistenImage_(){this.unlisten_&&(this.unlisten_(),this.unlisten_=null)}disposeInternal(){this.unlistenImage_(),this.image_=null,super.disposeInternal()}}class t4{constructor(t,e,n,r){this.minX=t,this.maxX=e,this.minY=n,this.maxY=r}contains(t){return this.containsXY(t[1],t[2])}containsTileRange(t){return this.minX<=t.minX&&t.maxX<=this.maxX&&this.minY<=t.minY&&t.maxY<=this.maxY}containsXY(t,e){return this.minX<=t&&t<=this.maxX&&this.minY<=e&&e<=this.maxY}equals(t){return this.minX==t.minX&&this.minY==t.minY&&this.maxX==t.maxX&&this.maxY==t.maxY}extend(t){t.minXthis.maxX&&(this.maxX=t.maxX),t.minYthis.maxY&&(this.maxY=t.maxY)}getHeight(){return this.maxY-this.minY+1}getSize(){return[this.getWidth(),this.getHeight()]}getWidth(){return this.maxX-this.minX+1}intersects(t){return this.minX<=t.maxX&&this.maxX>=t.minX&&this.minY<=t.maxY&&this.maxY>=t.minY}}function e4(t,e,n,r,i){return void 0!==i?(i.minX=t,i.maxX=e,i.minY=n,i.maxY=r,i):new t4(t,e,n,r)}const n4=[];class r4 extends J5{constructor(t,e,n,r,i){super(t,e,{transition:0}),this.context_=null,this.executorGroups={},this.loadingSourceTiles=0,this.hitDetectionImageData={},this.replayState_={},this.sourceTiles=[],this.errorTileKeys={},this.wantedResolution,this.getSourceTiles=r.bind(void 0,this),this.removeSourceTiles_=i,this.wrappedTileCoord=n}getContext(){return this.context_||(this.context_=AK(1,1,n4)),this.context_}hasContext(){return!!this.context_}getImage(){return this.hasContext()?this.getContext().canvas:null}getReplayState(t){const e=bV(t);return e in this.replayState_||(this.replayState_[e]={dirty:!1,renderedRenderOrder:null,renderedResolution:NaN,renderedRevision:-1,renderedTileResolution:NaN,renderedTileRevision:-1,renderedTileZ:-1}),this.replayState_[e]}load(){this.getSourceTiles()}release(){this.context_&&(zK(this.context_),n4.push(this.context_.canvas),this.context_=null),this.removeSourceTiles_(this),this.sourceTiles.length=0,super.release()}}let i4=class extends J5{constructor(t,e,n,r,i,s){super(t,e,s),this.extent=null,this.format_=r,this.features_=null,this.loader_,this.projection=null,this.resolution,this.tileLoadFunction_=i,this.url_=n,this.key=n}getTileUrl(){return this.url_}getFormat(){return this.format_}getFeatures(){return this.features_}load(){0==this.state&&(this.setState(1),this.tileLoadFunction_(this,this.url_),this.loader_&&this.loader_(this.extent,this.resolution,this.projection))}onLoad(t,e){this.setFeatures(t)}onError(){this.setState(3)}setFeatures(t){this.features_=t,this.setState(2)}setLoader(t){this.loader_=t}};const s4="https://api.mapbox.com";function o4(t){return 0!==t.indexOf("mapbox://")?"":t.slice(9)}function a4(t,e,n){const r=o4(t);if(!r)return decodeURI(new URL(t,n).href);if(0!==r.indexOf("sprites/"))throw new Error(`unexpected sprites url: ${t}`);const i=r.slice(8);return`${s4}/styles/v1/${i}/sprite?access_token=${e}`}function l4(t,e){const n=o4(t);if(!n)return decodeURI(new URL(t,location.href).href);if(0!==n.indexOf("styles/"))throw new Error(`unexpected style url: ${t}`);const r=n.slice(7);return`${s4}/styles/v1/${r}?&access_token=${e}`}const c4=["a","b","c","d"];function u4(t,e,n,r){const i=new URL(t,r||location.href),s=o4(t);if(!s)return e?(i.searchParams.has(n)||i.searchParams.set(n,e),[decodeURI(i.href)]):[decodeURI(i.href)];if("mapbox.satellite"===s){const t=window.devicePixelRatio>=1.5?"@2x":"";return[`https://api.mapbox.com/v4/${s}/{z}/{x}/{y}${t}.webp?access_token=${e}`]}return c4.map(t=>`https://${t}.tiles.mapbox.com/v4/${s}/{z}/{x}/{y}.vector.pbf?access_token=${e}`)}const h4=Object.freeze({}),d4={},p4={};let f4=0;function g4(t){return t.id||(t.id=f4++),t.id}function m4(t){let e=d4[t.id];return e||(e={},d4[g4(t)]=e),e}function y4(t){return t*Math.PI/180}const v4=function(){const t=[];for(let e=78271.51696402048;t.length<=24;e/=2)t.push(e);return t}();function b4(t,e){if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,e);const n=document.createElement("canvas");return n.width=t,n.height=e,n}function w4(t,e){let n=0;const r=e.length;for(;ni).then(t=>t instanceof Response?(r&&(r.url=t.url),o(t)):(t instanceof Request||(t=new Request(t)),t.headers.get("Accept")||t.headers.set("Accept","application/json"),r&&(r.url=t.url),fetch(t).then(o).catch(s))).catch(s);return x4[e]=[i,a],a}function S4(t,e){if("string"!=typeof t)return Promise.resolve(t);if(!t.trim().startsWith("{"))return C4("Style",t=l4(t,e.accessToken),e);try{const e=JSON.parse(t);return Promise.resolve(e)}catch(v5){return Promise.reject(v5)}}const k4={};function E4(t,e,n={}){const r=[e,JSON.stringify(t)].toString();let i=k4[r];if(!i||n.transformRequest){let s;n.transformRequest&&(s=(t,e)=>{const r=n.transformRequest&&n.transformRequest(e,"Tiles")||e;if(t instanceof i4)t.setLoader((e,n,i)=>{const s=function(n){n.arrayBuffer().then(n=>{const r=t.getFormat().readFeatures(n,{extent:e,featureProjection:i});t.setFeatures(r)})};lV(()=>r).then(e=>{if(e instanceof Response)return s(e);fetch(e).then(s).catch(()=>t.setState(3))}).catch(()=>t.setState(3))});else{const e=t.getImage();lV(()=>r).then(n=>{if("string"==typeof n)return void(e.src=n);const r=t=>t.blob().then(t=>{const n=URL.createObjectURL(t);e.addEventListener("load",()=>URL.revokeObjectURL(n)),e.addEventListener("error",()=>URL.revokeObjectURL(n)),e.src=n});if(n instanceof Response)return r(n);fetch(n).then(r).catch(()=>t.setState(3))}).catch(()=>t.setState(3))}});const o=t.url;if(o&&!t.tiles){const r=u4(o,n.accessToken,n.accessTokenParam||"access_token",e||location.href);if(o.startsWith("mapbox://"))i=Promise.resolve({tileJson:Object.assign({},t,{url:void 0,tiles:r}),tileLoadFunction:s});else{const t={};i=C4("Source",r[0],n,t).then(function(e){return e.tiles=e.tiles.map(function(r){return"tms"===e.scheme&&(r=r.replace("{y}","{-y}")),u4(r,n.accessToken,n.accessTokenParam||"access_token",t.url)[0]}),Promise.resolve({tileJson:e,tileLoadFunction:s})})}}else t.tiles?(t=Object.assign({},t,{tiles:t.tiles.map(function(r){return"tms"===t.scheme&&(r=r.replace("{y}","{-y}")),u4(r,n.accessToken,n.accessTokenParam||"access_token",e||location.href)[0]})}),i=Promise.resolve({tileJson:Object.assign({},t),tileLoadFunction:s})):i=Promise.reject(new Error("source has no `tiles` nor `url`"));k4[r]=i}return i}function T4(t,e,n,r){const i=[2*n*e.pixelRatio+e.width,2*n*e.pixelRatio+e.height],s=b4(i[0],i[1]),o=s.getContext("2d");o.drawImage(t,e.x,e.y,e.width,e.height,n*e.pixelRatio,n*e.pixelRatio,e.width,e.height);const a=o.getImageData(0,0,i[0],i[1]);o.globalCompositeOperation="destination-over",o.fillStyle=`rgba(${255*r.r},${255*r.g},${255*r.b},${r.a})`;const l=a.data;for(let c=0,u=a.width;c0&&o.arc(c,t,n*e.pixelRatio,0,2*Math.PI);return o.fill(),s}function R4(t,e,n){const r=Math.max(0,Math.min(1,(n-t)/(e-t)));return r*r*(3-2*r)}function M4(t,e,n){const r=b4(e.width,e.height),i=r.getContext("2d");i.drawImage(t,e.x,e.y,e.width,e.height,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),o=s.data;for(let a=0,l=s.width;a0?(o[e+0]=Math.round(255*n.r*s),o[e+1]=Math.round(255*n.g*s),o[e+2]=Math.round(255*n.b*s),o[e+3]=Math.round(255*s)):o[e+3]=0}return i.putImageData(s,0,0),r}const L4=Array(256).join(" ");function I4(t,e){if(e>=.05){let n="";const r=t.split("\n"),i=L4.slice(0,Math.round(e/.1));for(let t=0,e=r.length;t0&&(n+="\n"),n+=r[t].split("").join(i);return n}return t}let P4;function A4(){return P4||(P4=b4(1,1).getContext("2d")),P4}function O4(t,e){return A4().measureText(t).width+(t.length-1)*e}const F4={};function z4(t,e,n,r){if(-1!==t.indexOf("\n")){const i=t.split("\n"),s=[];for(let t=0,o=i.length;t1){const t=A4();t.font=e;const i=t.measureText("M").width*n;let a="";const l=[];for(let e=0,n=o.length;e1;++e){const t=l[e];if(O4(t,r)<.35*i){const i=e>0?O4(l[e-1],r):1/0,s=e.7*i&&O4(s,r)<.6*i){const o=t.split(" "),a=o.pop();O4(a,r)<.2*i&&(l[e]=o.join(" "),l[e+1]=a+" "+s),n-=1}}s=l.join("\n")}else s=t;s=I4(s,r),F4[i]=s}return s}wJ.on("propertychange",()=>{for(const t in F4)delete F4[t]});const D4=["Arial","Courier New","Times New Roman","Verdana","sans-serif","serif","monospace","cursive","fantasy"],N4={},j4={Point:1,MultiPoint:1,LineString:2,MultiLineString:2,Polygon:3,MultiPolygon:3},B4={center:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]},U4={zoom:0,distanceFromCenter:0};let $4,q4;function V4(t,e,n,r,i,s){const o=t.id;i||(i={},console.warn("No functionCache provided to getValue()")),i[o]||(i[o]={});const a=i[o];if(!a[n]){let r=(t[e]||h4)[n];const i=W5[`${e}_${t.type}`][n];void 0===r&&(r=i.default);let s=(l=r,Array.isArray(l)&&l.length>0&&"string"==typeof l[0]&&l[0]in a5);if(!s&&b5(r)&&(r=function(t,e){let n=t.stops;if(!n)return function(t,e){const n=["get",t.property];if(void 0===t.default)return"string"===e.type?["string",n]:n;if("enum"===e.type)return["match",n,Object.keys(e.values),n,t.default];{const r=["color"===e.type?"to-color":e.type,n,D5(t.default)];return"array"===e.type&&r.splice(1,0,e.value,e.length||null),r}}(t,e);const r=n&&"object"==typeof n[0][0],i=r||void 0!==t.property,s=r||!i;return n=n.map(t=>!i&&e.tokens&&"string"==typeof t[1]?[t[0],V5(t[1])]:[t[0],D5(t[1])]),r?function(t,e,n){const r={},i={},s=[];for(let o=0;o`${t.key}: ${t.message}`).join(", "));return n.value}(r,i);a[n]=t.evaluate.bind(t)}else{const t=i.type;"color"!==t&&"colorArray"!==t||(r=c2.parse(r)),a[n]=function(){return r}}}var l;return a[n](U4,r,s)}function W4(t,e,n,r){return V4(t,"layout",`${n}-allow-overlap`,e,r)?V4(t,"layout",`${n}-ignore-placement`,e,r)?"none":"obstacle":"declutter"}function H4(t,e,n,r){if(r||console.warn("No filterCache provided to evaluateFilter()"),!(t in r))try{r[t]=M5(e).filter}catch(ej){console.warn("Filter will evaluate to false: "+ej.message),r[t]=function(){return!1}}return r[t](U4,n)}function G4(t,e){if(t){if(0===t.a||0===e)return;const n=t.a;return e=void 0===e?1:e,0===n?"transparent":"rgba("+Math.round(255*t.r/n)+","+Math.round(255*t.g/n)+","+Math.round(255*t.b/n)+","+n*e+")"}return t}l5.register(a5,{...l5.definitions,pitch:[{kind:"number"},[],()=>U4.pitch||90],"distance-from-center":[{kind:"number"},[],()=>U4.distanceFromCenter||0]});const K4=/\{[^{}}]*\}/g;function Z4(t,e){return t.replace(K4,function(t){return e[t.slice(1,-1)]||""})}function Y4(t,e){let n=t.split(":")[0];return n===t&&(n="default"),e[n]}const X4={},J4=4294967296,Q4=1/J4,t6="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class e6{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(t,e,n=this.length){for(;this.pos>3,i=this.pos;this.type=7&n,t(r,e,this),this.pos===i&&this.skip(n)}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*J4;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*J4;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let n,r;return r=e[this.pos++],n=127&r,r<128?n:(r=e[this.pos++],n|=(127&r)<<7,r<128?n:(r=e[this.pos++],n|=(127&r)<<14,r<128?n:(r=e[this.pos++],n|=(127&r)<<21,r<128?n:(r=e[this.pos],n|=(15&r)<<28,function(t,e,n){const r=n.buf;let i,s;if(s=r[n.pos++],i=(112&s)>>4,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<3,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<10,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<17,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(127&s)<<24,s<128)return n6(t,i,e);if(s=r[n.pos++],i|=(1&s)<<31,s<128)return n6(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(n,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&t6?t6.decode(this.buf.subarray(e,t)):function(t,e,n){let r="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+c>n)break;1===c?e<128&&(l=e):2===c?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===c?(s=t[i+1],o=t[i+2],128==(192&s)&&128==(192&o)&&(l=(15&e)<<12|(63&s)<<6|63&o,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===c&&(s=t[i+1],o=t[i+2],a=t[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(l=(15&e)<<18|(63&s)<<12|(63&o)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,c=1):l>65535&&(l-=65536,r+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),r+=String.fromCharCode(l),i+=c}return r}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const n=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else{if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8}}writeTag(t,e){this.writeVarint(t<<3|e)}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let n,r;if(t>=0?(n=t%4294967296|0,r=t/4294967296|0):(n=~(-t%4294967296),r=~(-t/4294967296),4294967295^n?n=n+1|0:(n=0,r=r+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,n){n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos++]=127&t|128,t>>>=7,n.buf[n.pos]=127&t}(n,0,e),function(t,e){const n=(7&t)<<4;e.buf[e.pos++]|=n|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(r,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))}writeSVarint(t){this.writeVarint(t<0?2*-t-1:2*t)}writeBoolean(t){this.writeVarint(+t)}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,n){for(let r,i,s=0;s55295&&r<57344){if(!i){r>56319||s+1===e.length?(t[n++]=239,t[n++]=191,t[n++]=189):i=r;continue}if(r<56320){t[n++]=239,t[n++]=191,t[n++]=189,i=r;continue}r=i-55296<<10|r-56320|65536,i=null}else i&&(t[n++]=239,t[n++]=191,t[n++]=189,i=null);r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:(r<65536?t[n++]=r>>12|224:(t[n++]=r>>18|240,t[n++]=r>>12&63|128),t[n++]=r>>6&63|128),t[n++]=63&r|128)}return n}(this.buf,t,this.pos);const n=this.pos-e;n>=128&&r6(e,n,this),this.pos=e-1,this.writeVarint(n),this.pos+=n}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let n=0;n=128&&r6(n,r,this),this.pos=n-1,this.writeVarint(r),this.pos+=r}writeMessage(t,e,n){this.writeTag(t,2),this.writeRawMessage(e,n)}writePackedVarint(t,e){e.length&&this.writeMessage(t,i6,e)}writePackedSVarint(t,e){e.length&&this.writeMessage(t,s6,e)}writePackedBoolean(t,e){e.length&&this.writeMessage(t,l6,e)}writePackedFloat(t,e){e.length&&this.writeMessage(t,o6,e)}writePackedDouble(t,e){e.length&&this.writeMessage(t,a6,e)}writePackedFixed32(t,e){e.length&&this.writeMessage(t,c6,e)}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,u6,e)}writePackedFixed64(t,e){e.length&&this.writeMessage(t,h6,e)}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,d6,e)}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e)}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e)}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e)}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e)}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e)}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e)}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e)}writeStringField(t,e){this.writeTag(t,2),this.writeString(e)}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e)}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e)}writeBooleanField(t,e){this.writeVarintField(t,+e)}}function n6(t,e,n){return n?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function r6(t,e,n){const r=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));n.realloc(r);for(let i=n.pos-1;i>=t;i--)n.buf[i+r]=n.buf[i]}function i6(t,e){for(let n=0;n>3}if(o--,1===s||2===s)a+=t.readSVarint(),l+=t.readSVarint(),1===s&&c>u&&(r.push(c),u=c),n.push(a,l),c+=2;else{if(7!==s)throw new Error("Invalid command found in the PBF");c>u&&(n.push(n[u],n[u+1]),c+=2)}}c>u&&(r.push(c),u=c)}createFeature_(t,e,n){const r=e.type;if(0===r)return null;let i;const s=e.properties;let o;this.idProperty_?(o=s[this.idProperty_],delete s[this.idProperty_]):o=e.id,s[this.layerName_]=e.layer.name;const a=[],l=[];this.readRawGeometry_(t,e,a,l);const c=function(t,e){let n;return 1===t?n=1===e?"Point":"MultiPoint":2===t?n=1===e?"LineString":"MultiLineString":3===t&&(n="Polygon"),n}(r,l.length);if(this.featureClass===z0)i=new this.featureClass(c,a,l,2,s,o),i.transform(n.dataProjection);else{let t;if("Polygon"==c){const e=pK(a,l);t=e.length>1?new FQ(a,"XY",e):new fK(a,"XY",l)}else t="Point"===c?new XG(a,"XY"):"LineString"===c?new IQ(a,"XY"):"MultiPoint"===c?new AQ(a,"XY"):"MultiLineString"===c?new PQ(a,"XY",l):null;i=new(0,this.featureClass),this.geometryName_&&i.setGeometryName(this.geometryName_);const e=W0(t,!1,n);i.setGeometry(e),void 0!==o&&i.setId(o),i.setProperties(s,!0)}return i}getType(){return"arraybuffer"}readFeatures(t,e){const n=this.layers_,r=YH((e=this.adaptOptions(e)).dataProjection);r.setWorldExtent(e.extent),e.dataProjection=r;const i=new e6(t),s=i.readFields(f6,{}),o=[];for(const a in s){if(n&&!n.includes(a))continue;const t=s[a],l=t?[0,0,t.extent,t.extent]:null;r.setExtent(l);for(let n=0,r=t.length;n>3)?n.readString():2===t?n.readFloat():3===t?n.readDouble():4===t?n.readVarint64():5===t?n.readVarint():6===t?n.readSVarint():7===t?n.readBoolean():null;e.values.push(r)}}function m6(t,e,n){if(1==t)e.id=n.readVarint();else if(2==t){const t=n.readVarint()+n.pos;for(;n.pos=o.width)return null;const c=OW(s),u=Math.floor(o.height*((s[3]-r[1])/c));return u<0||u>=o.height?null:this.getImageData(o,l,u)}renderFrame(t,e){const n=this.image,r=n.getExtent(),i=n.getResolution(),[s,o]=Array.isArray(i)?i:[i,i],a=n.getPixelRatio(),l=t.layerStatesArray[t.layerIndex],c=t.pixelRatio,u=t.viewState,h=u.center,d=u.resolution,p=c*s/(d*a),f=c*o/(d*a);this.prepareContainer(t,e);const g=this.context.canvas.width,m=this.context.canvas.height,y=this.getRenderContext(t);let v=!1,b=!0;if(l.extent){const e=uG(l.extent,u.projection);b=jW(e,t.extent),v=b&&!fW(e,t.extent),v&&this.clipUnrotated(y,t,e)}const w=n.getImage(),_=wG(this.tempTransform,g/2,m/2,p,f,0,a*(r[0]-h[0])/s,a*(h[1]-r[3])/o);this.renderedResolution=o*c/a;const x=w.width*_[0],C=w.height*_[3];if(this.getLayer().getSource().getInterpolate()||(y.imageSmoothingEnabled=!1),this.preRender(y,t),b&&x>=.5&&C>=.5){const t=_[4],e=_[5],n=l.opacity;1!==n&&(y.save(),y.globalAlpha=n),y.drawImage(w,0,0,+w.width,+w.height,t,e,x,C),1!==n&&y.restore()}return this.postRender(this.context,t),v&&y.restore(),y.imageSmoothingEnabled=!0,this.container}}class b6 extends HZ{constructor(t){super(t=t||{})}}class w6 extends b6{constructor(t){super(t)}createRenderer(){return new v6(this)}getData(t){return super.getData(t)}}function _6(t){return t instanceof Image||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageBitmap?t:null}const x6=new Error("disposed"),C6=[256,256];class S6 extends J5{constructor(t){super(t.tileCoord,0,{transition:t.transition,interpolate:t.interpolate}),this.loader_=t.loader,this.data_=null,this.error_=null,this.size_=t.size||null,this.controller_=t.controller||null}getSize(){if(this.size_)return this.size_;const t=_6(this.data_);return t?[t.width,t.height]:C6}getData(){return this.data_}getError(){return this.error_}load(){if(0!==this.state&&3!==this.state)return;this.state=1,this.changed();const t=this;this.loader_().then(function(e){t.data_=e,t.state=2,t.changed()}).catch(function(e){t.error_=e,t.state=3,t.changed()})}disposeInternal(){this.controller_&&(this.controller_.abort(x6),this.controller_=null),super.disposeInternal()}}let k6;const E6=[];function T6(t,e,n,r,i){t.beginPath(),t.moveTo(0,0),t.lineTo(e,n),t.lineTo(r,i),t.closePath(),t.save(),t.clip(),t.fillRect(0,0,Math.max(e,r)+1,Math.max(n,i)),t.restore()}function R6(t,e){return Math.abs(t[4*e]-210)>2||Math.abs(t[4*e+3]-191.25)>2}function M6(t,e,n,r){const i=oG(n,e,t);let s=XH(e,r,n);const o=e.getMetersPerUnit();void 0!==o&&(s*=o);const a=t.getMetersPerUnit();void 0!==a&&(s/=a);const l=t.getExtent();if(!l||pW(l,i)){const e=XH(t,s,i)/s;isFinite(e)&&e>0&&(s/=e)}return s}function L6(t,e,n,r,i,s,o,a,l,c,u,h,d){const p=AK(Math.round(n*t),Math.round(n*e),E6);if(h||(p.imageSmoothingEnabled=!1),0===l.length)return p.canvas;function f(t){return Math.round(t*n)/n}p.scale(n,n),p.globalCompositeOperation="lighter";const g=[1/0,1/0,-1/0,-1/0];let m;l.forEach(function(t){xW(g,t.extent)});const y=n/r,v=(h?1:1+Math.pow(2,-24))/y;d&&1===l.length&&0===c||(m=AK(Math.round(NW(g)*y),Math.round(OW(g)*y),E6),h||(m.imageSmoothingEnabled=!1),l.forEach(function(t){if(t.image.width>0&&t.image.height>0){if(t.clipExtent){m.save();const e=(t.clipExtent[0]-g[0])*y,n=-(t.clipExtent[3]-g[3])*y,r=NW(t.clipExtent)*y,i=OW(t.clipExtent)*y;m.rect(h?e:Math.round(e),h?n:Math.round(n),h?r:Math.round(e+r)-Math.round(e),h?i:Math.round(n+i)-Math.round(n)),m.clip()}const e=(t.extent[0]-g[0])*y,n=-(t.extent[3]-g[3])*y,r=NW(t.extent)*y,i=OW(t.extent)*y;m.drawImage(t.image,c,c,t.image.width-2*c,t.image.height-2*c,h?e:Math.round(e),h?n:Math.round(n),h?r:Math.round(e+r)-Math.round(e),h?i:Math.round(n+i)-Math.round(n)),t.clipExtent&&m.restore()}}));const b=zW(o);return a.getTriangles().forEach(function(t){const e=t.source,n=t.target;let r=e[0][0],i=e[0][1],o=e[1][0],a=e[1][1],c=e[2][0],u=e[2][1];const d=f((n[0][0]-b[0])/s),y=f(-(n[0][1]-b[1])/s),w=f((n[1][0]-b[0])/s),_=f(-(n[1][1]-b[1])/s),x=f((n[2][0]-b[0])/s),C=f(-(n[2][1]-b[1])/s),S=r,k=i;r=0,i=0,o-=S,a-=k,c-=S,u-=k;const E=function(t){const e=t.length;for(let r=0;ri&&(i=e,n=o)}if(0===i)return null;const s=t[n];t[n]=t[r],t[r]=s;for(let o=r+1;o=0;r--){n[r]=t[r][e]/t[r][r];for(let i=r-1;i>=0;i--)t[i][e]-=t[i][r]*n[r]}return n}([[o,a,0,0,w-d],[c,u,0,0,x-d],[0,0,o,a,_-y],[0,0,c,u,C-y]]);if(!E)return;if(p.save(),p.beginPath(),function(){if(void 0===k6){const t=AK(6,6,E6);t.globalCompositeOperation="lighter",t.fillStyle="rgba(210, 0, 0, 0.75)",T6(t,4,5,4,0),T6(t,4,5,0,5);const e=t.getImageData(0,0,3,3).data;k6=R6(e,0)||R6(e,4)||R6(e,8),zK(t),E6.push(t.canvas)}return k6}()||!h){p.moveTo(w,_);const t=4,e=d-w,n=y-_;for(let r=0;rvG(o,oG(t,this.targetProj_,this.sourceProj_)),function(t,e,n,r){const i=t.length;n=void 0!==n?n:2,r=r??n,e=void 0!==e?e:new Array(i);for(let s=0;s=o?t[s+n]:i[n]}return e}):sG(this.targetProj_,this.sourceProj_);var c;this.transformInv_=function(t){const e=t[0]+"/"+t[1];return a[e]||(a[e]=l(t)),a[e]},this.maxSourceExtent_=r,this.errorThresholdSquared_=i*i,this.triangles_=[],this.wrapsXInSource_=!1,this.canWrapXInSource_=this.sourceProj_.canWrapX()&&!!r&&!!this.sourceProj_.getExtent()&&NW(r)>=NW(this.sourceProj_.getExtent()),this.sourceWorldWidth_=this.sourceProj_.getExtent()?NW(this.sourceProj_.getExtent()):null,this.targetWorldWidth_=this.targetProj_.getExtent()?NW(this.targetProj_.getExtent()):null;const u=zW(n),h=DW(n),d=MW(n),p=RW(n),f=this.transformInv_(u),g=this.transformInv_(h),m=this.transformInv_(d),y=this.transformInv_(p),v=10+(s?Math.max(0,Math.ceil(Math.log2(TW(n)/(s*s*256*256)))):0);if(this.addQuad_(u,h,d,p,f,g,m,y,v),this.wrapsXInSource_){let t=1/0;this.triangles_.forEach(function(e){t=Math.min(t,e.source[0][0],e.source[1][0],e.source[2][0])}),this.triangles_.forEach(e=>{if(Math.max(e.source[0][0],e.source[1][0],e.source[2][0])-t>this.sourceWorldWidth_/2){const n=[[e.source[0][0],e.source[0][1]],[e.source[1][0],e.source[1][1]],[e.source[2][0],e.source[2][1]]];n[0][0]-t>this.sourceWorldWidth_/2&&(n[0][0]-=this.sourceWorldWidth_),n[1][0]-t>this.sourceWorldWidth_/2&&(n[1][0]-=this.sourceWorldWidth_),n[2][0]-t>this.sourceWorldWidth_/2&&(n[2][0]-=this.sourceWorldWidth_);const r=Math.min(n[0][0],n[1][0],n[2][0]);Math.max(n[0][0],n[1][0],n[2][0])-r.5&&u<1;let p=!1;if(l>0&&(this.targetProj_.isGlobal()&&this.targetWorldWidth_&&(p=NW(cW([t,e,n,r]))/this.targetWorldWidth_>.25||p),!d&&this.sourceProj_.isGlobal()&&u&&(p=u>.25||p)),!p&&this.maxSourceExtent_&&isFinite(c[0])&&isFinite(c[1])&&isFinite(c[2])&&isFinite(c[3])&&!jW(c,this.maxSourceExtent_))return;let f=0;if(!(p||isFinite(i[0])&&isFinite(i[1])&&isFinite(s[0])&&isFinite(s[1])&&isFinite(o[0])&&isFinite(o[1])&&isFinite(a[0])&&isFinite(a[1])))if(l>0)p=!0;else if(f=(isFinite(i[0])&&isFinite(i[1])?0:8)+(isFinite(s[0])&&isFinite(s[1])?0:4)+(isFinite(o[0])&&isFinite(o[1])?0:2)+(isFinite(a[0])&&isFinite(a[1])?0:1),1!=f&&2!=f&&4!=f&&8!=f)return;if(l>0){if(!p){const e=[(t[0]+n[0])/2,(t[1]+n[1])/2],r=this.transformInv_(e);let s;s=d?(eW(i[0],h)+eW(o[0],h))/2-eW(r[0],h):(i[0]+o[0])/2-r[0];const a=(i[1]+o[1])/2-r[1];p=s*s+a*a>this.errorThresholdSquared_}if(p){if(Math.abs(t[0]-n[0])<=Math.abs(t[1]-n[1])){const c=[(e[0]+n[0])/2,(e[1]+n[1])/2],u=this.transformInv_(c),h=[(r[0]+t[0])/2,(r[1]+t[1])/2],d=this.transformInv_(h);this.addQuad_(t,e,c,h,i,s,u,d,l-1),this.addQuad_(h,c,n,r,d,u,o,a,l-1)}else{const c=[(t[0]+e[0])/2,(t[1]+e[1])/2],u=this.transformInv_(c),h=[(n[0]+r[0])/2,(n[1]+r[1])/2],d=this.transformInv_(h);this.addQuad_(t,c,h,r,i,u,d,a,l-1),this.addQuad_(c,e,n,h,u,s,o,d,l-1)}return}}if(d){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=!0}11&f||this.addTriangle_(t,n,r,i,o,a),14&f||this.addTriangle_(t,n,e,i,o,s),f&&(13&f||this.addTriangle_(e,r,t,s,a,i),7&f||this.addTriangle_(e,r,n,s,a,o))}calculateSourceExtent(){const t=[1/0,1/0,-1/0,-1/0];return this.triangles_.forEach(function(e){const n=e.source;CW(t,n[0]),CW(t,n[1]),CW(t,n[2])}),t}getTriangles(){return this.triangles_}}class P6 extends J5{constructor(t,e,n,r,i,s,o,a,l,c,u,h){super(i,0,h),this.renderEdges_=void 0!==u&&u,this.pixelRatio_=o,this.gutter_=a,this.canvas_=null,this.sourceTileGrid_=e,this.targetTileGrid_=r,this.wrappedTileCoord_=s||i,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0,this.clipExtent_=t.canWrapX()?t.getExtent():void 0;const d=r.getTileCoordExtent(this.wrappedTileCoord_),p=this.targetTileGrid_.getExtent();let f=this.sourceTileGrid_.getExtent();const g=p?FW(d,p):d;if(0===TW(g))return void(this.state=4);const m=t.getExtent();m&&(f=f?FW(f,m):m);const y=r.getResolution(this.wrappedTileCoord_[0]),v=function(t,e,n,r){const i=LW(n);let s=M6(t,e,i,r);return(!isFinite(s)||s<=0)&&EW(n,function(n){return s=M6(t,e,n,r),isFinite(s)&&s>0}),s}(t,n,g,y);if(!isFinite(v)||v<=0)return void(this.state=4);const b=void 0!==c?c:.5;if(this.triangulation_=new I6(t,n,g,f,v*b,y),0===this.triangulation_.getTriangles().length)return void(this.state=4);this.sourceZ_=e.getZForResolution(v);let w=this.triangulation_.calculateSourceExtent();if(f&&(t.canWrapX()?(w[1]=YV(w[1],f[1],f[3]),w[3]=YV(w[3],f[1],f[3])):w=FW(w,f)),TW(w)){let n=0,r=0;t.canWrapX()&&(n=NW(m),r=Math.floor((w[0]-m[0])/n)),qW(w.slice(),t,!0).forEach(t=>{const i=e.getTileRangeForExtentAndZ(t,this.sourceZ_);for(let e=i.minX;e<=i.maxX;e++)for(let t=i.minY;t<=i.maxY;t++){const i=l(this.sourceZ_,e,t,o);if(i){const t=r*n;this.sourceTiles_.push({tile:i,offset:t})}}++r}),0===this.sourceTiles_.length&&(this.state=4)}else this.state=4}getImage(){return this.canvas_}reproject_(){const t=[];if(this.sourceTiles_.forEach(e=>{const n=e.tile;if(n&&2==n.getState()){const r=this.sourceTileGrid_.getTileCoordExtent(n.tileCoord);r[0]+=e.offset,r[2]+=e.offset;const i=this.clipExtent_?.slice();i&&(i[0]+=e.offset,i[2]+=e.offset),t.push({extent:r,clipExtent:i,image:n.getImage()})}}),this.sourceTiles_.length=0,0===t.length)this.state=3;else{const e=this.wrappedTileCoord_[0],n=this.targetTileGrid_.getTileSize(e),r="number"==typeof n?n:n[0],i="number"==typeof n?n:n[1],s=this.targetTileGrid_.getResolution(e),o=this.sourceTileGrid_.getResolution(this.sourceZ_),a=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=L6(r,i,this.pixelRatio_,o,this.sourceTileGrid_.getExtent(),s,a,this.triangulation_,t,this.gutter_,this.renderEdges_,this.interpolate),this.state=2}this.changed()}load(){if(0==this.state){this.state=1,this.changed();let t=0;this.sourcesListenerKeys_=[],this.sourceTiles_.forEach(({tile:e})=>{const n=e.getState();if(0==n||1==n){t++;const n=pV(e,Vq,()=>{const r=e.getState();2!=r&&3!=r&&4!=r||(gV(n),t--,0===t&&(this.unlistenSources_(),this.reproject_()))});this.sourcesListenerKeys_.push(n)}}),0===t?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach(function({tile:t}){0==t.getState()&&t.load()})}}unlistenSources_(){this.sourcesListenerKeys_.forEach(gV),this.sourcesListenerKeys_=null}release(){this.canvas_&&(zK(this.canvas_.getContext("2d")),E6.push(this.canvas_),this.canvas_=null),super.release()}}class A6{constructor(t){this.highWaterMark=void 0!==t?t:2048,this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}deleteOldest(){const t=this.pop();t instanceof Xq&&t.dispose()}canExpireCache(){return this.highWaterMark>0&&this.getCount()>this.highWaterMark}expireCache(t){for(;this.canExpireCache();)this.deleteOldest()}clear(){for(;this.oldest_;)this.deleteOldest()}containsKey(t){return this.entries_.hasOwnProperty(t)}forEach(t){let e=this.oldest_;for(;e;)t(e.value_,e.key_,this),e=e.newer}get(t,e){const n=this.entries_[t];return WV(void 0!==n,"Tried to get a value for a key that does not exist in the cache"),n===this.newest_||(n===this.oldest_?(this.oldest_=this.oldest_.newer,this.oldest_.older=null):(n.newer.older=n.older,n.older.newer=n.newer),n.newer=null,n.older=this.newest_,this.newest_.newer=n,this.newest_=n),n.value_}remove(t){const e=this.entries_[t];return WV(void 0!==e,"Tried to get a value for a key that does not exist in the cache"),e===this.newest_?(this.newest_=e.older,this.newest_&&(this.newest_.newer=null)):e===this.oldest_?(this.oldest_=e.newer,this.oldest_&&(this.oldest_.older=null)):(e.newer.older=e.older,e.older.newer=e.newer),delete this.entries_[t],--this.count_,e.value_}getCount(){return this.count_}getKeys(){const t=new Array(this.count_);let e,n=0;for(e=this.newest_;e;e=e.older)t[n++]=e.key_;return t}getValues(){const t=new Array(this.count_);let e,n=0;for(e=this.newest_;e;e=e.older)t[n++]=e.value_;return t}peekLast(){return this.oldest_.value_}peekLastKey(){return this.oldest_.key_}peekFirstKey(){return this.newest_.key_}peek(t){return this.entries_[t]?.value_}pop(){const t=this.oldest_;return delete this.entries_[t.key_],t.newer&&(t.newer.older=null),this.oldest_=t.newer,this.oldest_||(this.newest_=null),--this.count_,t.value_}replace(t,e){this.get(t),this.entries_[t].value_=e}set(t,e){WV(!(t in this.entries_),"Tried to set a value for a key that is used already");const n={key_:t,newer:null,older:this.newest_,value_:e};this.newest_?this.newest_.newer=n:this.oldest_=n,this.newest_=n,this.entries_[t]=n,++this.count_}setSize(t){this.highWaterMark=t}}function O6(t,e,n,r){return void 0!==r?(r[0]=t,r[1]=e,r[2]=n,r):[t,e,n]}function F6(t,e,n,r,i){return`${bV(t)},${e},${function(t,e,n){return t+"/"+e+"/"+n}(n,r,i)}`}function z6(t,e,n){if(!(n in t))return t[n]=new Set([e]),!0;const r=t[n],i=r.has(e);return i||r.add(e),!i}function D6(t,e,n){const r=t[n];return!!r&&r.delete(e)}function N6(t,e){const n=t.layerStatesArray[t.layerIndex];n.extent&&(e=FW(e,uG(n.extent,t.viewState.projection)));const r=n.layer.getRenderSource();if(!r.getWrapX()){const n=r.getTileGridForProjection(t.viewState.projection).getExtent();n&&(e=FW(e,n))}return e}class j6 extends E0{constructor(t,e){super(t),e=e||{},this.extentChanged=!0,this.renderComplete=!1,this.renderedExtent_=null,this.renderedPixelRatio,this.renderedProjection=null,this.renderedTiles=[],this.renderedSourceKey_,this.renderedSourceRevision_,this.tempExtent=[1/0,1/0,-1/0,-1/0],this.tempTileRange_=new t4(0,0,0,0),this.tempTileCoord_=O6(0,0,0);const n=void 0!==e.cacheSize?e.cacheSize:512;this.tileCache_=new A6(n),this.sourceTileCache_=null,this.maxStaleKeys=.5*n}getTileCache(){return this.tileCache_}getSourceTileCache(){return this.sourceTileCache_||(this.sourceTileCache_=new A6(512)),this.sourceTileCache_}getOrCreateTile(t,e,n,r){const i=this.tileCache_,s=this.getLayer().getSource(),o=F6(s,s.getKey(),t,e,n);let a;if(i.containsKey(o))a=i.get(o);else{const l=r.viewState.projection,c=s.getProjection();if(a=s.getTile(t,e,n,r.pixelRatio,l,!c||nG(c,l)?void 0:this.getSourceTileCache()),!a)return null;i.set(o,a)}return a}getTile(t,e,n,r){return this.getOrCreateTile(t,e,n,r)||null}getData(t){const e=this.frameState;if(!e)return null;const n=this.getLayer(),r=vG(e.pixelToCoordinateTransform,t.slice()),i=n.getExtent();if(i&&!pW(i,r))return null;const s=e.viewState,o=n.getRenderSource(),a=o.getTileGridForProjection(s.projection),l=o.getTilePixelRatio(e.pixelRatio);for(let c=a.getZForResolution(s.resolution);c>=a.getMinZoom();--c){const t=a.getTileCoordForCoordAndZ(r,c),n=this.getTile(c,t[1],t[2],e);if(!n||2!==n.getState())continue;const i=a.getOrigin(c),u=AY(a.getTileSize(c)),h=a.getResolution(c);let d;if(n instanceof Q5||n instanceof P6)d=n.getImage();else{if(!(n instanceof S6))continue;if(d=_6(n.getData()),!d)continue}const p=Math.floor(l*((r[0]-i[0])/h-t[1]*u[0])),f=Math.floor(l*((i[1]-r[1])/h-t[2]*u[1])),g=Math.round(l*o.getGutterForProjection(s.projection));return this.getImageData(d,p+g,f+g)}return null}prepareFrame(t){this.renderedProjection?t.viewState.projection!==this.renderedProjection&&(this.tileCache_.clear(),this.renderedProjection=t.viewState.projection):this.renderedProjection=t.viewState.projection;const e=this.getLayer().getSource();if(!e)return!1;const n=e.getRevision();return this.renderedSourceRevision_?this.renderedSourceRevision_!==n&&(this.renderedSourceRevision_=n,this.renderedSourceKey_===e.getKey()&&(this.tileCache_.clear(),this.sourceTileCache_?.clear())):this.renderedSourceRevision_=n,!0}enqueueTilesForNextExtent(){return!0}enqueueTiles(t,e,n,r,i){const s=t.viewState,o=this.getLayer(),a=o.getRenderSource(),l=a.getTileGridForProjection(s.projection),c=bV(a);c in t.wantedTiles||(t.wantedTiles[c]={});const u=t.wantedTiles[c],h=o.getMapInternal(),d=Math.max(n-i,l.getMinZoom(),l.getZForResolution(Math.min(o.getMaxResolution(),h?h.getView().getResolutionForZoom(Math.max(o.getMinZoom(),0)):l.getResolution(0)),a.zDirection)),p=s.rotation,f=p?AW(s.center,s.resolution,p,t.size):void 0;for(let g=n;g>=d;--g){const n=l.getTileRangeForExtentAndZ(e,g,this.tempTileRange_),i=l.getResolution(g);for(let e=n.minX;e<=n.maxX;++e)for(let s=n.minY;s<=n.maxY;++s){if(p&&!l.tileCoordIntersectsViewport([g,e,s],f))continue;const n=this.getTile(g,e,s,t);if(!n)continue;if(!z6(r,n,g))continue;const o=n.getKey();if(u[o]=!0,0===n.getState()&&!t.tileQueue.isKeyQueued(o)){const r=O6(g,e,s,this.tempTileCoord_);t.tileQueue.enqueue([n,c,l.getTileCoordCenter(r),i])}}}}findStaleTile_(t,e){const n=this.tileCache_,r=t[0],i=t[1],s=t[2],o=this.getStaleKeys();for(let a=0;a0&&setTimeout(()=>{this.enqueueTiles(t,S,h-1,x,C-1)},0),!(h in x))return this.container;const k=bV(this),E=t.time;for(const A of x[h]){const e=A.getState();if(4===e)continue;const n=A.tileCoord;if(2===e&&1===A.getAlpha(k,E)){A.endTransition(k);continue}if(3!==e&&(this.renderComplete=!1),this.findStaleTile_(n,x)){D6(x,A,h),t.animate=!0;continue}if(this.findAltTiles_(u,n,h+1,x))continue;const r=u.getMinZoom();for(let t=h-1;t>=r&&!this.findAltTiles_(u,n,t,x);--t);}const T=d/s*a/g,R=this.getRenderContext(t);wG(this.tempTransform,m/2,y/2,T,T,0,-m/2,-y/2),n.extent&&this.clipUnrotated(R,t,v),c.getInterpolate()||(R.imageSmoothingEnabled=!1),this.preRender(R,t);const M=Object.keys(x).map(Number);let L;M.sort(Jq);const I=[],P=[];for(let A=M.length-1;A>=0;--A){const e=M[A],n=c.getTilePixelSize(e,a,i),r=u.getResolution(e)/d,s=n[0]*r*T,o=n[1]*r*T,l=u.getTileCoordForCoordAndZ(zW(_),e),h=u.getTileCoordExtent(l),p=vG(this.tempTransform,[g*(h[0]-_[0])/d,g*(_[3]-h[3])/d]),f=g*c.getGutterForProjection(i);for(const i of x[e]){if(2!==i.getState())continue;const n=i.tileCoord,r=l[1]-n[1],a=Math.round(p[0]-(r-1)*s),u=l[2]-n[2],h=Math.round(p[1]-(u-1)*o),d=Math.round(p[0]-r*s),g=Math.round(p[1]-u*o),m=a-d,y=h-g,v=1===M.length;let b=!1;L=[d,g,d+m,g,d+m,g+y,d,g+y];for(let t=0,i=I.length;t{const n=bV(c),r=e.wantedTiles[n],i=r?Object.keys(r).length:0;this.updateCacheSize(i),this.tileCache_.expireCache(),this.sourceTileCache_?.expireCache()};t.postRenderFunctions.push(e)}return this.container}updateCacheSize(t){this.tileCache_.highWaterMark=Math.max(this.tileCache_.highWaterMark,2*t)}drawTile(t,e,n,r,i,s,o,a){let l;if(t instanceof S6){if(l=_6(t.getData()),!l)throw new Error("Rendering array data is not yet supported")}else l=this.getTileImage(t);if(!l)return;const c=this.getRenderContext(e),u=bV(this),h=e.layerStatesArray[e.layerIndex],d=h.opacity*(a?t.getAlpha(u,e.time):1),p=d!==c.globalAlpha;p&&(c.save(),c.globalAlpha=d),c.drawImage(l,o,o,l.width-2*o,l.height-2*o,n,r,i,s),p&&c.restore(),d!==h.opacity?e.animate=!0:a&&t.endTransition(u)}getImage(){const t=this.context;return t?t.canvas:null}getTileImage(t){return t.getImage()}updateUsedTiles(t,e,n){const r=bV(e);r in t||(t[r]={}),t[r][n.getKey()]=!0}}const B6="preload",U6="useInterimTilesOnError";class $6 extends HZ{constructor(t){t=t||{};const e=Object.assign({},t),n=t.cacheSize;delete t.cacheSize,delete e.preload,delete e.useInterimTilesOnError,super(e),this.on,this.once,this.un,this.cacheSize_=n,this.setPreload(void 0!==t.preload?t.preload:0),this.setUseInterimTilesOnError(void 0===t.useInterimTilesOnError||t.useInterimTilesOnError)}getCacheSize(){return this.cacheSize_}getPreload(){return this.get(B6)}setPreload(t){this.set(B6,t)}getUseInterimTilesOnError(){return this.get(U6)}setUseInterimTilesOnError(t){this.set(U6,t)}getData(t){return super.getData(t)}}class q6 extends $6{constructor(t){super(t)}createRenderer(){return new j6(this,{cacheSize:this.getCacheSize()})}}const V6={image:["Polygon","Circle","LineString","Image","Text"],hybrid:["Polygon","LineString"],vector:[]},W6={hybrid:["Image","Text","Default"],vector:["Polygon","Circle","LineString","Image","Text","Default"]};class H6 extends j6{constructor(t,e){super(t,e),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.renderedLayerRevision_,this.renderedPixelToCoordinateTransform_=null,this.renderedRotation_,this.renderedOpacity_=1,this.tmpTransform_=[1,0,0,1,0,0],this.tileClipContexts_=null}enqueueTilesForNextExtent(){return"vector"!==this.getLayer().getRenderMode()}drawTile(t,e,n,r,i,s,o,a){this.updateExecutorGroup_(t,e.pixelRatio,e.viewState.projection),this.tileImageNeedsRender_(t)&&this.renderTileImage_(t,e),super.drawTile(t,e,n,r,i,s,o,a)}getTile(t,e,n,r){const i=this.getOrCreateTile(t,e,n,r);if(!i)return null;const s=r.viewState,o=s.resolution,a=r.viewHints,l=this.getLayer().getSource(),c=l.getTileGridForProjection(s.projection),u=!(a[0]||a[1]),h=c.getZForResolution(o,l.zDirection)===t;return u&&h?i.wantedResolution=o:i.wantedResolution||(i.wantedResolution=c.getResolution(t)),i}prepareFrame(t){const e=this.getLayer().getRevision();return this.renderedLayerRevision_!==e&&(this.renderedLayerRevision_=e,this.renderedTiles.length=0),super.prepareFrame(t)}updateExecutorGroup_(t,e,n){const r=this.getLayer(),i=r.getRevision(),s=r.getRenderOrder()||null,o=t.wantedResolution,a=t.getReplayState(r);if(!a.dirty&&a.renderedResolution===o&&a.renderedRevision==i&&a.renderedRenderOrder==s)return;const l=r.getSource(),c=!!r.getDeclutter(),u=l.getTileGrid(),h=l.getTileGridForProjection(n).getTileCoordExtent(t.wrappedTileCoord),d=l.getSourceTiles(e,n,t),p=bV(r);delete t.hitDetectionImageData[p],t.executorGroups[p]=[],a.dirty=!1;for(let f=0,g=d.length;ft.value):null;let m;t:for(let y=0,v=d.length;y{const n=this.getLayer(),r=n.getSource(),i=this.renderedProjection,s=i.getExtent(),o=this.renderedResolution,a=r.getTileGridForProjection(i),l=vG(this.renderedPixelToCoordinateTransform_,t.slice()),c=a.getTileCoordForCoordAndResolution(l,o).toString(),u=this.renderedTiles.find(t=>t.tileCoord.toString()===c&&2===t.getState());if(!u||u.loadingSourceTiles>0)return void e([]);r.getWrapX()&&i.canWrapX()&&!fW(s,a.getTileCoordExtent(u.tileCoord))&&HW(l,i);const h=bV(n),d=zW(a.getTileCoordExtent(u.wrappedTileCoord)),p=[(l[0]-d[0])/o,(d[1]-l[1])/o],f=u.getSourceTiles().reduce((t,e)=>t.concat(e.getFeatures()),[]);let g=u.hitDetectionImageData[h];if(!g){const t=AY(a.getTileSize(a.getZForResolution(o,r.zDirection))),e=this.renderedRotation_;g=g0(t,[this.getRenderTransform(a.getTileCoordCenter(u.wrappedTileCoord),o,0,f0,t[0]*f0,t[1]*f0,0)],f,n.getStyleFunction(),a.getTileCoordExtent(u.wrappedTileCoord),u.getReplayState(n).renderedResolution,e),u.hitDetectionImageData[h]=g}e(m0(p,f,g))})}getFeaturesInExtent(t){const e=[],n=this.getTileCache();if(0===n.getCount())return e;const r=this.getLayer().getSource().getTileGridForProjection(this.frameState.viewState.projection),i=r.getZForResolution(this.renderedResolution),s={};return n.forEach(n=>{if(n.tileCoord[0]!==i||2!==n.getState())return;const o=n.getSourceTiles();for(let i=0,a=o.length;i=0;--r)n[r].execute(this.context,o,this.getTileRenderTransform(e,t),t.viewState.rotation,s,c0,l)}n.globalAlpha=r}renderDeferredInternal(t){const e=this.renderedTiles,n=bV(this.getLayer()),r=e.reduce((t,e,r)=>(e.executorGroups[n].forEach(e=>t.push({executorGroup:e,index:r})),t),[]),i=r.map(({executorGroup:t})=>t.getDeferredZIndexContexts()),s={};for(let o=0,a=r.length;o{i.forEach((e,n)=>{e[t]&&(e[t].forEach(t=>{const{executorGroup:e,index:i}=r[n],s=e.getRenderedContext(),o=s.globalAlpha;s.globalAlpha=this.renderedOpacity_;const a=this.tileClipContexts_[i];a&&a.draw(s),t.draw(s),a&&s.restore(),s.globalAlpha=o,t.clear()}),e[t].length=0)})})}getTileRenderTransform(t,e){const n=e.pixelRatio,r=e.viewState,i=r.center,s=r.resolution,o=r.rotation,a=e.size,l=Math.round(a[0]*n),c=Math.round(a[1]*n),u=this.getLayer().getSource().getTileGridForProjection(e.viewState.projection),h=t.tileCoord,d=u.getTileCoordExtent(t.wrappedTileCoord),p=u.getTileCoordExtent(h,this.tempExtent)[0]-d[0];return mG(bG(this.inversePixelTransform.slice(),1/n,1/n),this.getRenderTransform(i,s,o,n,l,c,p))}postRender(t,e){const n=e.viewHints,r=!(n[0]||n[1]);this.renderedPixelToCoordinateTransform_=e.pixelToCoordinateTransform.slice(),this.renderedRotation_=e.viewState.rotation,this.renderedOpacity_=e.layerStatesArray[e.layerIndex].opacity;const i=this.getLayer(),s=i.getRenderMode(),o=t.globalAlpha;t.globalAlpha=this.renderedOpacity_;const a=i.getDeclutter(),l=a?W6[s].filter(t=>!c0.includes(t)):W6[s],c=e.viewState,u=c.rotation,h=i.getSource(),d=h.getTileGridForProjection(c.projection).getZForResolution(c.resolution,h.zDirection),p=this.renderedTiles,f=[],g=[],m=[],y=bV(i);let v=!0;for(let b=p.length-1;b>=0;--b){const n=p[b];v=v&&!n.getReplayState(i).dirty;const s=n.executorGroups[y].filter(t=>t.hasExecutors(l));if(0===s.length)continue;const o=this.getTileRenderTransform(n,e),c=n.tileCoord[0];let h=!1;const w=s[0].getClipCoords(o);let _,x=t;if(w){_=new YQ,x=_.getContext();for(let t=0,e=f.length;t{const t=this.sourceImage_.getState();2!=t&&3!=t||(this.unlistenSource_(),this.reproject_())}),this.sourceImage_.load())}}unlistenSource_(){gV(this.sourceListenerKey_),this.sourceListenerKey_=null}}class Y6 extends hV{constructor(t,e){super(t),this.image=e}}class X6 extends N0{constructor(t){super({attributions:t.attributions,projection:t.projection,state:t.state,interpolate:void 0===t.interpolate||t.interpolate}),this.on,this.once,this.un,this.loader=t.loader||null,this.resolutions_=void 0!==t.resolutions?t.resolutions:null,this.reprojectedImage_=null,this.reprojectedRevision_=0,this.image=null,this.wantedExtent_,this.wantedResolution_,this.static_=!!t.loader&&0===t.loader.length,this.wantedProjection_=null}getResolutions(){return this.resolutions_}setResolutions(t){this.resolutions_=t}findNearestResolution(t){const e=this.getResolutions();return e&&(t=e[tV(e,t,0)]),t}getImage(t,e,n,r){const i=this.getProjection();if(!i||!r||nG(i,r))return i&&(r=i),this.getImageInternal(t,e,n,r);if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&nG(this.reprojectedImage_.getProjection(),r)&&this.reprojectedImage_.getResolution()==e&&_W(this.reprojectedImage_.getExtent(),t))return this.reprojectedImage_;this.reprojectedImage_.dispose(),this.reprojectedImage_=null}return this.reprojectedImage_=new Z6(i,r,t,e,n,(t,e,n)=>this.getImageInternal(t,e,n,i),this.getInterpolate()),this.reprojectedRevision_=this.getRevision(),this.reprojectedImage_}getImageInternal(t,e,n,r){if(this.loader){const i=function(t,e,n){const r=e/n,i=LW(t),s=sW(NW(t)/r,4),o=sW(OW(t)/r,4);return PW(i,r,0,[s+2*sW(0*s/2,4),o+2*sW(0*o/2,4)])}(t,e,n),s=this.findNearestResolution(e);if(this.image&&(this.static_||this.wantedProjection_===r&&(this.wantedExtent_&&fW(this.wantedExtent_,i)||fW(this.image.getExtent(),i))&&(this.wantedResolution_&&K6(this.wantedResolution_)===s||K6(this.image.getResolution())===s)))return this.image;this.wantedProjection_=r,this.wantedExtent_=i,this.wantedResolution_=s,this.image=new iJ(i,s,n,this.loader),this.image.addEventListener(Vq,this.handleImageChange.bind(this))}return this.image}handleImageChange(t){const e=t.target;let n;switch(e.getState()){case 1:this.loading=!0,n="imageloadstart";break;case 2:this.loading=!1,n="imageloadend";break;case 3:this.loading=!1,n="imageloaderror";break;default:return}this.hasListener(n)&&this.dispatchEvent(new Y6(n,e))}}const J6=[0,0,0];class Q6{constructor(t){let e;if(this.minZoom=void 0!==t.minZoom?t.minZoom:0,this.resolutions_=t.resolutions,WV(function(t){const e=((t,e)=>e-t)||Jq;return t.every(function(n,r){if(0===r)return!0;const i=e(t[r-1],n);return!(i>0||0===i)})}(this.resolutions_),"`resolutions` must be sorted in descending order"),!t.origins)for(let r=0,i=this.resolutions_.length-1;r{const r=new t4(Math.min(0,t[0]),Math.max(t[0]-1,-1),Math.min(0,t[1]),Math.max(t[1]-1,-1));if(n){const t=this.getTileRangeForExtentAndZ(n,e);r.minX=Math.max(t.minX,r.minX),r.maxX=Math.min(t.maxX,r.maxX),r.minY=Math.max(t.minY,r.minY),r.maxY=Math.min(t.maxY,r.maxY)}return r}):n&&this.calculateTileRanges_(n)}forEachTileCoord(t,e,n){const r=this.getTileRangeForExtentAndZ(t,e);for(let i=r.minX,s=r.maxX;i<=s;++i)for(let t=r.minY,o=r.maxY;t<=o;++t)n([e,i,t])}forEachTileCoordParentTileRange(t,e,n,r){let i,s,o,a=null,l=t[0]-1;for(2===this.zoomFactor_?(s=t[1],o=t[2]):a=this.getTileCoordExtent(t,r);l>=this.minZoom;){if(void 0!==s&&void 0!==o?(s=Math.floor(s/2),o=Math.floor(o/2),i=e4(s,s,o,o,n)):i=this.getTileRangeForExtentAndZ(a,l,n),e(l,i))return!0;--l}return!1}getExtent(){return this.extent_}getMaxZoom(){return this.maxZoom}getMinZoom(){return this.minZoom}getOrigin(t){return this.origin_?this.origin_:this.origins_[t]}getResolution(t){return this.resolutions_[t]}getResolutions(){return this.resolutions_}getTileCoordChildTileRange(t,e,n){if(t[0]this.maxZoom||e0?r:Math.max(s/n[0],i/n[1]);const o=e+1,a=new Array(o);for(let l=0;ln||n>e.getMaxZoom())return!1;const s=e.getFullTileRange(n);return!s||s.containsXY(r,i)}(t,r)?t:null}clear(){}refresh(){this.clear(),super.refresh()}}class s8 extends hV{constructor(t,e){super(t),this.tile=e}}function o8(t){return function(e){const n=e.buffers,r=e.meta,i=e.imageOps,s=e.width,o=e.height,a=n.length,l=n[0].byteLength;if(i){const e=new Array(a);for(let t=0;tthis.maxQueueLength_;)this.queue_.shift().callback(null,null)}dispatch_(){if(this.running_||0===this.queue_.length)return;const t=this.queue_.shift();this.job_=t;const e=t.inputs[0].width,n=t.inputs[0].height,r=t.inputs.map(function(t){return t.data.buffer}),i=this.workers_.length;if(this.running_=i,1===i)return void this.workers_[0].postMessage({buffers:r,meta:t.meta,imageOps:this.imageOps_,width:e,height:n},r);const s=t.inputs[0].data.length,o=4*Math.ceil(s/4/i);for(let a=0;athis.getTileInternal(t,e,n,r,o,s),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_,this.tileOptions);return d.key=l,d}getTileInternal(t,e,n,r,i,s){const o=this.getKey(),a=F6(this,o,t,e,n);if(s&&s.containsKey(a))return s.get(a);const l=this.createTile_(t,e,n,r,i,o);return s?.set(a,l),l}setRenderReprojectionEdges(t){this.renderReprojectionEdges_!=t&&(this.renderReprojectionEdges_=t,this.changed())}setTileGridForProjection(t,e){const n=YH(t);if(n){const t=bV(n);t in this.tileGridForProjection||(this.tileGridForProjection[t]=e)}}}function x8(t,e){if(PV){const n=t.getCrossOrigin();let r="same-origin",i="same-origin";return"anonymous"===n||""===n?(r="cors",i="omit"):"use-credentials"===n&&(r="cors",i="include"),void fetch(e,{mode:r,credentials:i}).then(t=>{if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.blob()}).then(t=>createImageBitmap(t)).then(e=>{const n=t.getImage();n.width=e.width,n.height=e.height,n.getContext("2d").drawImage(e,0,0),e.close?.(),n.dispatchEvent(new Event("load"))}).catch(()=>{t.getImage().dispatchEvent(new Event("error"))})}t.getImage().src=e}class C8 extends _8{constructor(t){if(super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:YH("EPSG:3857"),reprojectionErrorThreshold:t.reprojectionErrorThreshold,state:"loading",tileLoadFunction:t.tileLoadFunction,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.tileJSON_=null,this.tileSize_=t.tileSize,t.url)if(t.jsonp)!function(t,e,n){const r=document.createElement("script"),i="olc_"+bV(e);function s(){delete window[i],r.parentNode.removeChild(r)}r.async=!0,r.src=t+(t.includes("?")?"&":"?")+"callback="+i;const o=setTimeout(function(){s(),n&&n()},1e4);window[i]=function(t){clearTimeout(o),s(),e(t)},document.head.appendChild(r)}(t.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const e=new XMLHttpRequest;e.addEventListener("load",this.onXHRLoad_.bind(this)),e.addEventListener("error",this.onXHRError_.bind(this)),e.open("GET",t.url),e.send()}else{if(!t.tileJSON)throw new Error("Either `url` or `tileJSON` options must be provided");this.handleTileJSONResponse(t.tileJSON)}}onXHRLoad_(t){const e=t.target;if(!e.status||e.status>=200&&e.status<300){let t;try{t=JSON.parse(e.responseText)}catch{return void this.handleTileJSONError()}this.handleTileJSONResponse(t)}else this.handleTileJSONError()}onXHRError_(t){this.handleTileJSONError()}getTileJSON(){return this.tileJSON_}handleTileJSONResponse(t){const e=YH("EPSG:4326"),n=this.getProjection();let r;if(void 0!==t.bounds){const i=rG(e,n);r=UW(t.bounds,i)}const i=r8(n),s=t.minzoom||0,o=e8({extent:i,maxZoom:t.maxzoom||22,minZoom:s,tileSize:this.tileSize_});if(this.tileGrid=o,this.tileUrlFunction=b8(t.tiles,o),t.attribution&&!this.getAttributions()){const e=void 0!==r?r:i;this.setAttributions(function(n){return jW(e,n.extent)?[t.attribution]:null})}this.tileJSON_=t,this.setState("ready")}handleTileJSONError(){this.setState("error")}}class S8 extends w8{constructor(t){const e=t.projection||"EPSG:3857",n=t.extent||r8(e),r=t.tileGrid||e8({extent:n,maxResolution:t.maxResolution,maxZoom:void 0!==t.maxZoom?t.maxZoom:22,minZoom:t.minZoom,tileSize:t.tileSize||512});super({attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,cacheSize:t.cacheSize,interpolate:!0,projection:e,state:t.state,tileGrid:r,tileLoadFunction:t.tileLoadFunction?t.tileLoadFunction:k8,tileUrlFunction:t.tileUrlFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:void 0===t.zDirection?1:t.zDirection}),this.format_=t.format?t.format:null,this.tileKeysBySourceTileUrl_={},this.sourceTiles_={},this.overlaps_=null==t.overlaps||t.overlaps,this.tileClass=t.tileClass?t.tileClass:i4,this.tileGrids_={}}getOverlaps(){return this.overlaps_}getSourceTiles(t,e,n){if(0===n.getState()){n.setState(1);const r=n.wrappedTileCoord,i=this.getTileGridForProjection(e);let s=i.getTileCoordExtent(r);const o=r[0],a=i.getResolution(o);uW(s,-a,s);const l=this.projection;e&&this.projection&&!nG(e,l)&&(s=aG(s,e,l));const c=this.tileGrid,u=c.getExtent();u&&FW(s,u,s);let h=a;e&&l&&!nG(e,l)&&(h=a/l.getMetersPerUnit()/e.getMetersPerUnit());const d=c.getZForResolution(h,this.zDirection);c.forEachTileCoord(s,d,r=>{const i=this.tileUrlFunction(r,t,e);this.sourceTiles_[i]||(this.sourceTiles_[i]=new this.tileClass(r,i?0:4,i,this.format_,this.tileLoadFunction));const s=this.sourceTiles_[i];n.sourceTiles.push(s),this.tileKeysBySourceTileUrl_[i]||(this.tileKeysBySourceTileUrl_[i]=[]),this.tileKeysBySourceTileUrl_[i].push(n.getKey());const o=s.getState();if(o<2){const t=e=>{this.handleTileChange(e);const r=s.getState();if(2===r||3===r){const e=s.getKey();e in n.errorTileKeys?2===s.getState()&&delete n.errorTileKeys[e]:n.loadingSourceTiles--,3===r?n.errorTileKeys[e]=!0:s.removeEventListener(Vq,t),0===n.loadingSourceTiles&&n.setState(uV(n.errorTileKeys)?2:3)}};s.addEventListener(Vq,t),n.loadingSourceTiles++}0===o&&(s.extent=c.getTileCoordExtent(r),s.projection=this.projection,s.resolution=c.getResolution(r[0]),s.load())}),n.loadingSourceTiles||n.setState(n.sourceTiles.some(t=>3===t.getState())?3:2)}return n.sourceTiles}removeSourceTiles(t){const e=t.getKey(),n=t.sourceTiles;for(let r=0,i=n.length;r{u=u&&!this.tileUrlFunction(t,r,l)})}const h=new r4(s,u?4:0,o,this.getSourceTiles.bind(this,r,i),this.removeSourceTiles.bind(this));return h.key=this.getKey(),h}getTileGridForProjection(t){const e=t.getCode();let n=this.tileGrids_[e];if(!n){const r=this.projection;if(null!==r&&!nG(r,t))return t8(t);const i=this.tileGrid,s=i.getResolutions().slice(),o=s.map(function(t,e){return i.getOrigin(e)}),a=s.map(function(t,e){return i.getTileSize(e)}),l=43;for(let t=s.length;td?h-A+d:d-A,P=Math.atan(Math.sqrt(L*L+I*I)),$=m*Math.cos(P)+g*Math.sin(P)*Math.cos(f-A),O=Math.cos(P),F=255*$,j=Math.min(Math.max(2*e.sunEl,0),1),B=1.875-1.75*e.opacity,U=.5!==e.opacity?d*((Math.pow(B,P)-1)/(Math.pow(B,d)-1)):P,D={r:(1-O)*b.r*j*255,g:(1-O)*b.g*j*255,b:(1-O)*b.b*j*255,a:(1-O)*b.a*j*255},z=Math.abs(((A+f)/Math.PI+.5)%2-1),N={r:(y.r*(1-z)+v.r*z)*F,g:(y.g*(1-z)+v.g*z)*F,b:(y.b*(1-z)+v.b*z)*F,a:(y.a*(1-z)+v.a*z)*F},T=4*(x*r+_),o[T]=D.r*(1-z)+N.r,o[T+1]=D.g*(1-z)+N.g,o[T+2]=D.b*(1-z)+N.b,o[T+3]=s[T+3]*e.opacity*j*Math.sin(U);return new ImageData(o,r,i)}function T8(t,e){const n=t[0],r=n.width,i=n.height,s=n.data,o=new Uint8ClampedArray(s.length),a=r-1,l=i-1,c=[0,0,0,0];let u,h,d;const p=(f=e.saturation)>0?1-1/(1.001-f):-f;var f;const g=(m=e.contrast)>0?1/(1-m):1+m;var m;const y=function(t){t*=Math.PI/180;const e=Math.sin(t),n=Math.cos(t);return[(2*n+1)/3,(-Math.sqrt(3)*e-n+1)/3,(Math.sqrt(3)*e-n+1)/3]}(e.hueRotate),v=y,b=[y[2],y[0],y[1]],w=[y[1],y[2],y[0]],_=e.brightnessLow,x=e.brightnessHigh;for(h=0;h<=l;++h)for(u=0;u<=a;++u){d=4*(h*r+u),c[0]=s[d],c[1]=s[d+1],c[2]=s[d+2],c[3]=s[d+3];const t=c[0],e=c[1],n=c[2],i=(t,e)=>{let n=0;for(let r=0;r{e.accessToken=t,e.accessTokenParam=n})),e}function L8(t,e){let n;return t.some(function(t){if(t.id==e)return n=t.source,!0}),n}function I8(t,e,n){const r=new C8({tileJSON:e,tileSize:t.tileSize||e.tileSize||512}),i=r.getTileJSON(),s=r.getTileGrid(),o=YH(n.projection||"EPSG:3857"),a=function(t,e){const n=t.bounds;if(n){const t=tG([n[0],n[1]],e),r=tG([n[2],n[3]],e);return[t[0],t[1],r[0],r[1]]}return YH(e).getExtent()}(i,o),l=o.getExtent(),c=i.minzoom||0,u=i.maxzoom||22,h={attributions:r.getAttributions(),projection:o,tileGrid:new Q6({origin:l?zW(l):s.getOrigin(0),extent:a||s.getExtent(),minZoom:c,resolutions:R8(o,e.tileSize).slice(0,u+1),tileSize:s.getTileSize(0)})};return Array.isArray(i.tiles)?h.urls=i.tiles:h.url=i.tiles,h}function P8(t,e,n){return new Promise(function(r,i){E4(t,e,n).then(function({tileJson:e,tileLoadFunction:i}){const s=I8(t,e,n);s.tileLoadFunction=i,s.format=new p6({layerName:"mvt:layer"});const o=new S8(s);o.set("mapbox-source",t),r(o)}).catch(i)})}function A8(t){return`{bbox-${(t?t.getCode():"EPSG:3857").toLowerCase().replace(/[^a-z0-9]/g,"-")}}`}function O8(t,e,n){const r=new q6;return function(t,e,n){return new Promise(function(r,i){E4(t,e,n).then(function({tileJson:e,tileLoadFunction:i}){const s=new C8({interpolate:void 0===n.interpolate||n.interpolate,transition:0,crossOrigin:"anonymous",tileJSON:e});s.tileGrid=I8(t,e,n).tileGrid,n.projection&&(s.projection=YH(n.projection));const o=s.getTileUrlFunction();i&&s.setTileLoadFunction(i),s.setTileUrlFunction(function(t,e,n){const r=A8(n);let i=o(t,e,n);if(-1!=i.indexOf(r)){const e=s.getTileGrid().getTileCoordExtent(t);i=i.replace(r,e.toString())}return i}),s.set("mapbox-source",t),r(s)}).catch(function(t){i(t)})})}(t,e,n).then(function(t){r.setSource(t)}).catch(function(){r.setSource(void 0)}),r}function F8(t,e,n){const r=n.projection?new X0({dataProjection:n.projection}):new X0,i=t.data,s={};if("string"==typeof i){const[s]=u4(i,n.accessToken,n.accessTokenParam||"access_token",e||location.href);if(/\{bbox-[0-9a-z-]+\}/.test(s)){const e=(t,e,n)=>{const r=A8(n);return s.replace(r,`${t.join(",")}`)},i=new q0({attributions:t.attribution,format:r,loader:(t,r,s,o,a)=>{C4("GeoJSON","function"==typeof e?e(t,r,s):e,n).then(t=>{const e=i.getFormat().readFeatures(t,{featureProjection:s});i.addFeatures(e),o(e)}).catch(()=>{i.removeLoadedExtent(t),a()})},strategy:P0});return i.set("mapbox-source",t),i}const o=new q0({attributions:t.attribution,format:r,url:s,loader:(t,e,r,i,a)=>{C4("GeoJSON",s,n).then(t=>{const e=o.getFormat().readFeatures(t,{featureProjection:r});o.addFeatures(e),i(e)}).catch(()=>{o.removeLoadedExtent(t),a()})}});return o}s.features=r.readFeatures(i,{featureProjection:"EPSG:3857"});const o=new q0(Object.assign({attributions:t.attribution,format:r},s));return o.set("mapbox-source",t),o}function z8(t,e,n,r){const i=m4(t),s=t.layers,o=n.type,a=n.source||L8(s,n.ref),l=t.sources[a];let c;if("background"==o)c=function(t,e,n){const r=PV?{style:{}}:document.createElement("div");return r.className="ol-mapbox-style-background",r.style.position="absolute",r.style.width="100%",r.style.height="100%",new HZ({source:new N0({}),render(i){const s=function(t,e,n,r){const i={id:t.id,type:t.type},s=t.layout||{},o=t.paint||{};let a;i.paint=o,U4.zoom=w4(e,n.resolutions||v4),U4.distanceFromCenter=0;const l=V4(i,"paint","background-color",h4,r);return void 0!==o["background-opacity"]&&(a=V4(i,"paint","background-opacity",h4,r)),"none"==s.visibility?void 0:G4(l,a)}(t,i.viewState.resolution,e,n);return r.style.backgroundColor=s,r}})}(n,r,i);else if("vector"==l.type)c=function(t,e,n){const r=new G6({declutter:!0,visible:!1});return P8(t,e,n).then(function(t){r.setSource(t)}).catch(function(){r.setSource(void 0)}),r}(l,e,r);else if("raster"==l.type){const t=["raster-saturation","raster-contrast","raster-brightness-max","raster-brightness-min","raster-hue-rotate"];Object.keys(n.paint||{}).find(e=>t.includes(e))?(c=function(t,e,n){const r=O8(t,e,n);return new w6({source:new u8({operationType:"image",operation:T8,sources:[r]})})}(l,e,r),c.getSource().on("beforeoperations",function(t){U4.zoom=w4(t.resolution,r.resolutions||v4),U4.distanceFromCenter=0;const e=t.data;e.saturation=V4(n,"paint","raster-saturation",h4,i),e.contrast=V4(n,"paint","raster-contrast",h4,i),e.brightnessHigh=V4(n,"paint","raster-brightness-max",h4,i),e.brightnessLow=V4(n,"paint","raster-brightness-min",h4,i),e.hueRotate=V4(n,"paint","raster-hue-rotate",h4,i)})):c=O8(l,e,r),c.setVisible(!n.layout||"none"!==n.layout.visibility),c.on("prerender",function(t,e,n){let r=null;return function(i){t.paint&&"raster-opacity"in t.paint&&i.frameState.viewState.zoom!==r&&(r=i.frameState.viewState.zoom,delete n[t.id],function(t,e,n,r){U4.zoom=n,U4.distanceFromCenter=0;const i=V4(t,"paint","raster-opacity",h4,r);e.setOpacity(i)}(t,e,r,n))}}(n,c,i))}else if("geojson"==l.type)c=function(t,e,n){return new R0({declutter:!0,source:F8(t,e,n),visible:!1})}(l,e,r);else if("raster-dem"==l.type&&"hillshade"==n.type){const t=function(t,e,n){const r=O8(t,e,n);return new w6({source:new u8({operationType:"image",operation:E8,sources:[r]})})}(l,e,r);c=t,t.getSource().on("beforeoperations",function(t){const e=t.data;e.resolution=XH(r.projection||"EPSG:3857",t.resolution,LW(t.extent),"m"),U4.zoom=w4(t.resolution,r.resolutions||v4),U4.distanceFromCenter=0,e.encoding=l.encoding,e.vert=5*V4(n,"paint","hillshade-exaggeration",h4,i),e.sunAz=V4(n,"paint","hillshade-illumination-direction",h4,i),e.sunEl=35,e.opacity=.3,e.highlightColor=V4(n,"paint","hillshade-highlight-color",h4,i),e.shadowColor=V4(n,"paint","hillshade-shadow-color",h4,i),e.accentColor=V4(n,"paint","hillshade-accent-color",h4,i)}),c.setVisible(!n.layout||"none"!==n.layout.visibility)}const u=a;return c&&c.set("mapbox-source",u),c}function D8(t,e,n,r,i,s={}){let o=24,a=0;const l=n.layers;for(let c=0,u=l.length;c0||n>0)&&t.setMaxResolution(Math.min(_4(Math.max(0,o-1e-12),v4),_4(Math.max(0,n-1e-12),e.getResolutions()))),a<24&&t.setMinResolution(_4(a,v4))}}else o>0&&t.setMaxResolution(_4(Math.max(0,o-1e-12),v4));u instanceof q0||u instanceof S8?function(t,e,n="",r={},i){let s,o,a,l,c=!0;return"string"==typeof n||Array.isArray(n)?l=n:(a=n,l=a.source||a.layers,r=a),"string"==typeof r?(s=r,a={}):(s=r.styleUrl,a=r),!1===a.updateSource&&(c=!1),i||(i=a.resolutions),s||"string"!=typeof e||e.trim().startsWith("{")||(s=e),s&&(s=s.startsWith("data:")?location.href:l4(s,a.accessToken),a=M8(s,a)),new Promise(function(n,r){S4(e,a).then(function(e){if(8!=e.version)return r(new Error("glStyle version 8 required."));if(!(t instanceof R0||t instanceof G6))return r(new Error("Can only apply to VectorLayer or VectorTileLayer"));const u=t instanceof G6?"vector":"geojson";if(l?o=Array.isArray(l)?e.layers.find(function(t){return t.id===l[0]}).source:l:(o=e.layers.find(function(t){return t.source&&e.sources[t.source].type===u}).source,l=o),!o)return r(new Error(`No ${u} source found in the glStyle.`));function h(){if(!c)return Promise.resolve();if(t instanceof G6)return P8(e.sources[o],s,a).then(function(e){const n=t.getSource();n?e!==n&&(n.setTileUrlFunction(e.getTileUrlFunction()),"function"==typeof n.setUrls&&"function"==typeof e.getUrls&&n.setUrls(e.getUrls()),n.format_||(n.format_=e.format_),n.getAttributions()||n.setAttributions(e.getAttributions()),n.getTileLoadFunction()===k8&&n.setTileLoadFunction(e.getTileLoadFunction()),nG(n.getProjection(),e.getProjection())&&(n.tileGrid=e.getTileGrid())):t.setSource(e);const r=t.getSource().getTileGrid();!isFinite(t.getMaxResolution())&&!isFinite(t.getMinZoom())&&r.getMinZoom()>0&&t.setMaxResolution(_4(Math.max(0,r.getMinZoom()-1e-12),r.getResolutions()))});const n=e.sources[o];let r=t.getSource();r&&r.get("mapbox-source")===n||(r=F8(n,s,a));const i=t.getSource();return i?r!==i&&(i.getAttributions()||i.setAttributions(r.getAttributions()),i.format_||(i.format_=r.getFormat()),i.url_=r.getUrl()):t.setSource(r),Promise.resolve()}let d,p;const f={},g={};function m(){if(p||e.sprite&&!f)p?(t.setStyle(p),h().then(n).catch(r)):r(new Error("Something went wrong trying to apply style."));else{if(a.projection&&!i){const t=YH(a.projection).getUnits();"m"!==t&&(i=v4.map(e=>e/eH[t]))}let s;const c=t.getSource();c instanceof S8&&c.format_ instanceof p6&&(s=c.format_.layerName_),p=function(t,e,n,r=v4,i,s,o,a){if("string"==typeof e&&(e=JSON.parse(e)),8!=e.version)throw new Error("glStyle version 8 required.");X4[function(t,e){return g4(t)+"."+bV(e)}(e,t)]=Array.from(arguments);const l={};("string"==typeof s||s instanceof Request||s instanceof Response||s instanceof Promise)&&(s={default:s});for(const _ in s){const e=s[_];lV(()=>e).then(async e=>{let n;if("undefined"!=typeof Image){const r=new Image;if("string"==typeof e)r.crossOrigin="anonymous",r.src=e;else{let t;e instanceof Request?t=await fetch(e):e instanceof Response&&(t=e);const i=await t.blob();n=URL.createObjectURL(i),r.src=n}r.addEventListener("load",function e(){r.removeEventListener("load",e),l[_]={image:r,size:[r.width,r.height]},t.changed(),n&&URL.revokeObjectURL(n)}),r.addEventListener("error",function t(){URL.revokeObjectURL(n),r.removeEventListener("error",t)})}else if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){const t=self;t.postMessage({action:"loadImage",src:e}),t.addEventListener("message",function(t){"imageLoaded"===t.data.action&&t.data.src===e&&(l[_]={image:t.data.image,size:[t.data.image.width,t.data.image.height]})})}})}const c=f1(e.layers),u={},h=[],d={},p={},f=m4(e),g=function(t){let e=p4[t.id];return e||(e={},p4[g4(t)]=e),e}(e);let m;for(let _=0,x=c.length;_=h.maxzoom)continue;const E=h.filter;if(!E||H4(x,E,T,g)){let r,c,g,w,_,x;const E=u.index;if(3==C&&("fill"==h.type||"fill-extrusion"==h.type))if(c=V4(h,"paint",h.type+"-opacity",T,f,R),h.type+"-pattern"in k){const t=V4(h,"paint",h.type+"-pattern",T,f,R);if(t){const e="string"==typeof t?Z4(t,m):t.toString(),n=Y4(e,l);if(i&&i[e]&&n){++M,x=b[M],x&&x.getFill()&&!x.getStroke()&&!x.getText()||(x=new NJ({fill:new OJ}),b[M]=x),g=x.getFill(),x.setZIndex(E);const t=e+"."+c;let r=p[t];if(!r){const s=i[e],o=b4(s.width,s.height),a=o.getContext("2d");a.globalAlpha=c,a.drawImage(n.image,s.x,s.y,s.width,s.height,0,0,s.width,s.height),r=a.createPattern(o,"repeat"),p[t]=r}g.setColor(r)}}}else r=G4(V4(h,"paint",h.type+"-color",T,f,R),c),h.type+"-outline-color"in k&&(_=G4(V4(h,"paint",h.type+"-outline-color",T,f,R),c)),_||(_=r),(r||_)&&(++M,x=b[M],(!x||r&&!x.getFill()||!r&&x.getFill()||_&&!x.getStroke()||!_&&x.getStroke()||x.getText())&&(x=new NJ({fill:r?new OJ:void 0,stroke:_?new DJ:void 0}),b[M]=x),r&&(g=x.getFill(),g.setColor(r)),_&&(w=x.getStroke(),w.setColor(_),w.setWidth(.5)),x.setZIndex(E));if(1!=C&&"line"==h.type){r="line-pattern"in k?void 0:G4(V4(h,"paint","line-color",T,f,R),V4(h,"paint","line-opacity",T,f,R));const t=V4(h,"paint","line-width",T,f,R);r&&t>0&&(++M,x=b[M],x&&x.getStroke()&&!x.getFill()&&!x.getText()||(x=new NJ({stroke:new DJ}),b[M]=x),w=x.getStroke(),w.setLineCap(V4(h,"layout","line-cap",T,f,R)),w.setLineJoin(V4(h,"layout","line-join",T,f,R)),w.setMiterLimit(V4(h,"layout","line-miter-limit",T,f,R)),w.setColor(r),w.setWidth(t),w.setLineDash(k["line-dasharray"]?V4(h,"paint","line-dasharray",T,f,R).map(function(e){return e*t}):null),x.setZIndex(E))}let L,I,P,A,O,F,z,D,N,j=!1,B=null,U=0;if((1==C||2==C)&&"icon-image"in S){const e=V4(h,"layout","icon-image",T,f,R);if(e){let r;L="string"==typeof e?Z4(e,m):e.toString();const o=a?a(t,L):void 0,c=Y4(L,l);if(i&&i[L]&&c||o){const t=V4(h,"layout","icon-rotation-alignment",T,f,R);if(2==C){const e=n.getGeometry();if(e.getFlatMidpoint||e.getFlatMidpoints){const n=e.getExtent();if(Math.sqrt(Math.max(Math.pow((n[2]-n[0])/s,2),Math.pow((n[3]-n[1])/s,2)))>150){const n="MultiLineString"===e.getType()?e.getFlatMidpoints():e.getFlatMidpoint();if(q4||($4=[NaN,NaN],q4=new z0("Point",$4,[],2,{},void 0)),r=q4,$4[0]=n[0],$4[1]=n[1],"line"===V4(h,"layout","symbol-placement",T,f,R)&&"map"===t){const t=e.getStride(),r=e.getFlatCoordinates();for(let e=0,i=r.length-t;e=l){U=Math.atan2(s-a,o-i);break}}}}}}if(2!==C||r){const e=V4(h,"layout","icon-size",T,f,R),n=void 0!==k["icon-color"]?V4(h,"paint","icon-color",T,f,R):null;if(!n||0!==n.a){const r=V4(h,"paint","icon-halo-color",T,f,R),s=V4(h,"paint","icon-halo-width",T,f,R);let a=`${L}.${e}.${s}.${r}`;if(null!==n&&(a+=`.${n}`),I=d[a],!I){const l=W4(h,T,"icon",f);let u;"icon-offset"in S&&(u=V4(h,"layout","icon-offset",T,f,R).slice(0),u[0]*=e,u[1]*=-e);let p=n?[255*n.r,255*n.g,255*n.b,n.a]:void 0;if(o){const n={color:p,rotateWithView:"map"===t,displacement:u,declutterMode:l,scale:e};"string"==typeof o?n.src=o:(n.img=o,n.imgSize=[o.width,o.height]),I=new zJ(n)}else{const o=i[L];let a,h,d;if(s)o.sdf?(a=T4(M4(c.image,o,n||[0,0,0,1]),{x:0,y:0,width:o.width,height:o.height,pixelRatio:o.pixelRatio},s,r),p=void 0):a=T4(c.image,o,s,r);else{if(o.sdf&&!c.unSDFed){const t=M4(c.image,{x:0,y:0,width:c.size[0],height:c.size[1]},{r:1,g:1,b:1});c.image=t,c.unSDFed=!0}a=c.image,h=[o.width,o.height],d=[o.x,o.y]}I=new zJ({color:p,img:a,imgSize:c.size,size:h,offset:d,rotateWithView:"map"===t,scale:e/o.pixelRatio,displacement:u,declutterMode:l})}d[a]=I}}I&&(++M,x=b[M],x&&x.getImage()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x),x.setGeometry(r),I.setRotation(U+y4(V4(h,"layout","icon-rotate",T,f,R))),I.setOpacity(V4(h,"paint","icon-opacity",T,f,R)),I.setAnchor(B4[V4(h,"layout","icon-anchor",T,f,R)]),x.setImage(I),B=x.getText(),x.setText(void 0),x.setZIndex(E),j=!0,P=!1)}else P=!0}}}if(1==C&&"circle"===h.type){++M,x=b[M],x&&x.getImage()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x);const t="circle-radius"in k?V4(h,"paint","circle-radius",T,f,R):5,e=G4(V4(h,"paint","circle-stroke-color",T,f,R),V4(h,"paint","circle-stroke-opacity",T,f,R)),n=V4(h,"paint","circle-translate",T,f,R),r=G4(V4(h,"paint","circle-color",T,f,R),V4(h,"paint","circle-opacity",T,f,R)),i=V4(h,"paint","circle-stroke-width",T,f,R),s=t+"."+e+"."+r+"."+i+"."+n[0]+"."+n[1];I=d[s],I||(I=new AJ({radius:t,displacement:[n[0],-n[1]],stroke:e&&i>0?new DJ({width:i,color:e}):void 0,fill:r?new OJ({color:r}):void 0,declutterMode:"none"}),d[s]=I),x.setImage(I),B=x.getText(),x.setText(void 0),x.setGeometry(void 0),x.setZIndex(E),j=!0}if("text-field"in S){z=Math.round(V4(h,"layout","text-size",T,f,R));const t=V4(h,"layout","text-font",T,f,R);F=V4(h,"layout","text-line-height",T,f,R),O=Y5(o?o(t,e.metadata?e.metadata["ol:webfonts"]:void 0):t,z,F),O.includes("sans-serif")||(O+=",sans-serif"),D=V4(h,"layout","text-letter-spacing",T,f,R),N=V4(h,"layout","text-max-width",T,f,R);const n=V4(h,"layout","text-field",T,f,R);A="object"==typeof n&&n.sections?1===n.sections.length?n.toString():n.sections.reduce((e,n)=>{const r=n.fontStack?n.fontStack.split(","):t,i=Y5(o?o(r):r,z*(n.scale||1),F);let s=n.text;if("\n"===s)return e.push("\n",""),e;if(2==C)return e.push(I4(s,D),i),e;s=z4(s,i,N,D).split("\n");for(let t=0,o=s.length;t0&&e.push("\n",""),e.push(s[t],i);return e},[]):Z4(n,m).trim(),c=V4(h,"paint","text-opacity",T,f,R)}if(A&&c&&!P){j||(++M,x=b[M],x&&x.getText()&&!x.getFill()&&!x.getStroke()||(x=new NJ,b[M]=x),x.setImage(void 0),x.setGeometry(void 0));const t=W4(h,T,"text",f);x.getText()||x.setText(B),B=x.getText(),(!B||"getDeclutterMode"in B&&B.getDeclutterMode()!==t)&&(B=new $J({padding:[2,2,2,2],declutterMode:t}),x.setText(B));const e=V4(h,"layout","text-transform",T,f,R);"uppercase"==e?A=Array.isArray(A)?A.map((t,e)=>e%2?t:t.toUpperCase()):A.toUpperCase():"lowercase"==e&&(A=Array.isArray(A)?A.map((t,e)=>e%2?t:t.toLowerCase()):A.toLowerCase());const n=Array.isArray(A)?A:2==C?I4(A,D):z4(A,O,N,D);if(B.setText(n),B.setFont(O),B.setRotation(y4(V4(h,"layout","text-rotate",T,f,R))),"function"==typeof B.setKeepUpright){const t=V4(h,"layout","text-keep-upright",T,f,R);B.setKeepUpright(t)}const r=V4(h,"layout","text-anchor",T,f,R),i=j||1==C?"point":V4(h,"layout","symbol-placement",T,f,R);let s;if("line-center"===i?(B.setPlacement("line"),s="center"):B.setPlacement(i),"line"===i&&"function"==typeof B.setRepeat){const t=V4(h,"layout","symbol-spacing",T,f,R);B.setRepeat(2*t)}B.setOverflow("point"===i);let o=V4(h,"paint","text-halo-width",T,f,R);const a=V4(h,"layout","text-offset",T,f,R),l=V4(h,"paint","text-translate",T,f,R);let u=0,d=0;if("point"==i){s="center",-1!==r.indexOf("left")?(s="left",d=o):-1!==r.indexOf("right")&&(s="right",d=-o);const t=V4(h,"layout","text-rotation-alignment",T,f,R);B.setRotateWithView("map"==t)}else B.setMaxAngle(y4(V4(h,"layout","text-max-angle",T,f,R))*A.length/n.length),B.setRotateWithView(!1);B.setTextAlign(s);let p="middle";0==r.indexOf("bottom")?(p="bottom",u=-o-.5*(F-1)*z):0==r.indexOf("top")&&(p="top",u=o+.5*(F-1)*z),B.setTextBaseline(p);const g=V4(h,"layout","text-justify",T,f,R);B.setJustify("auto"===g?void 0:g),B.setOffsetX(a[0]*z+d+l[0]),B.setOffsetY(a[1]*z+u+l[1]),v.setColor(G4(V4(h,"paint","text-color",T,f,R),c)),B.setFill(v);const m=G4(V4(h,"paint","text-halo-color",T,f,R),c);if(m&&o>0){y.setColor(m),o*=2;const t=.5*z;y.setWidth(o<=t?o:t),B.setStroke(y)}else B.setStroke(void 0);const w=V4(h,"layout","text-padding",T,f,R),_=B.getPadding();w!==_[0]&&(_[0]=w,_[1]=w,_[2]=w,_[3]=w),x.setZIndex(E)}}}return M>-1?(b.length=M+1,b):void 0};return t.setStyle(w),t.set("mapbox-layers",h),t.set("mapbox-source",m),t.set("mapbox-featurestate",t.get("mapbox-featurestate")||{}),w}(t,e,l,i,f,g,(t,e=a.webfonts)=>function(t,e="https://cdn.jsdelivr.net/npm/@fontsource/{font-family}/{fontweight}{-fontstyle}.css"){if(PV)return t;let n;for(let r=0,i=t.length;r{await document.fonts.ready;for(let t=0,r=n.length;tt.family.replace(/^['"]|['"]$/g,"").toLowerCase()===i.toLowerCase()&&t.weight==s&&t.style===o)){const t=e.replace("{font-family}",i.replace(/ /g,"-").toLowerCase()).replace("{Font+Family}",i.replace(/ /g,"+")).replace("{fontweight}",s).replace("{-fontstyle}",o.replace("normal","").replace(/(.+)/,"-$1")).replace("{fontstyle}",o);if(!document.querySelector('link[href="'+t+'"]')){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}}}})(),t):t}(t,e),a.getImage,s),t.getStyle()?h().then(n).catch(r):r(new Error(`Nothing to show for source [${o}]`))}}if(e.sprite){const t=function(t,e,n){if("string"==typeof t)return[{id:"default",url:a4(t,e,n)}];for(const r of t)r.url=a4(r.url,e,n);return t}(e.sprite,a.accessToken,s||location.href);d=PV?1:window.devicePixelRatio>=1.5?.5:1;const n=.5==d?"@2x":"";Promise.all(t.map(function(t){const e=new URL(t.url);let i=e.origin+e.pathname+n+".json"+e.search;return new Promise(function(t,n){C4("Sprite",i,a).then(t).catch(function(){i=e.origin+e.pathname+".json"+e.search,C4("Sprite",i,a).then(t).catch(n)})}).then(function(i){let s;if(void 0===i&&r(new Error("No sprites found.")),s=e.origin+e.pathname+n+".png"+e.search,a.transformRequest){const t=a.transformRequest(s,"SpriteImage")||s;(t instanceof Request||t instanceof Promise)&&(s=t)}g[t.id]=s;for(const e in i){const n="default"==t.id?e:`${t.id}:${e}`;f[n]=i[e]}}).catch(function(t){r(new Error(`Sprites cannot be loaded: ${i}: ${t.message}`))})})).then(m).catch(r)}else m()}).catch(r)})}(t,n,e,Object.assign({styleUrl:r},s)).then(function(){!function(t,e){function n(){const n=e.get("mapbox-style");if(!n)return;const r=f1(n.layers),i=t.get("mapbox-layers"),s=r.filter(function(t){return i.includes(t.id)}).some(function(t){return!t.layout||!t.layout.visibility||"visible"===t.layout.visibility});t.get("visible")!==s&&t.setVisible(s)}t.on("change",n),n()}(t,i),l()}).catch(c):l()}else c(new Error("Error accessing data for source "+t.get("mapbox-source")))};t.set("mapbox-layers",e);const h=i.getLayers();-1===h.getArray().indexOf(t)&&h.push(t),t.getSource()?u():t.once("change:source",u)})}class N8 extends LB{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");mapInstance;bookmarkSource;searchResultsSource;selectedShapeSource;searchOverlay;searchOverlayElement;selectedPinOverlay;selectedPinElement;crosshairElement;crosshairOverlay;ignoreNextMapClick=!1;setupMap=UB(t=>{if(this.mapInstance)return;const e=new UZ;this.selectedShapeSource=new q0;const n=new R0({source:this.selectedShapeSource,style:new NJ({stroke:new DJ({color:"#3388ff",width:4}),fill:new OJ({color:"rgba(51, 136, 255, 0.1)"})}),zIndex:5});this.bookmarkSource=new q0;const r=new R0({source:this.bookmarkSource,style:t=>{const e=t.get("originalPlace");let n=getComputedStyle(document.documentElement).getPropertyValue("--default-list-color").trim()||"#000000";if(e&&e._listIds&&e._listIds.length>0){const t=e._listIds[0],r=this.storage.lists.find(e=>e.id===t);r&&r.color&&(n=r.color)}return[new NJ({image:new AJ({radius:10,fill:new OJ({color:"rgba(0, 0, 0, 0.2)"}),displacement:[0,-2]})}),new NJ({image:new AJ({radius:9,fill:new OJ({color:n}),stroke:new DJ({color:"#fff",width:2})})})]},zIndex:10});this.searchResultsSource=new q0;const i=new Map,s=new R0({source:this.searchResultsSource,style:t=>{const e=t.get("originalPlace"),n=this.mapUi.selectedPlace;if(n){const t=e.osmId&&n.osmId&&e.osmId===n.osmId,r=e.id&&n.id&&e.id===n.id,i=e.lat===n.lat&&e.lon===n.lon;if(t||r||i)return new NJ({})}const r=Gj(e.osmTags||e),s=r||"default";if(!i.has(s)){const t=getComputedStyle(document.documentElement).getPropertyValue("--marker-color-primary").trim()||"#ea4335";let e=``;if(r){const n=qj(r);if(n){let r=n.trim();const i=r.indexOf("",i)+1,o=r.lastIndexOf("");-1!==i&&-1!==o&&(r=r.substring(s,o)),e=`\n \n \n ${r}\n \n `}}const n=`\n \n \n \n \n \n \n \n ${e}\n \n `;i.set(s,"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(n.trim()))}return new NJ({image:new zJ({src:i.get(s),anchor:[.5,.65],scale:1})})},zIndex:11});let o=[14.21683569,27.060114248],a=2.661,l=!1;try{const t=localStorage.getItem("marco:map-view");if(t){const e=JSON.parse(t);e.center&&Array.isArray(e.center)&&2===e.center.length&&"number"==typeof e.zoom&&(o=e.center,a=e.zoom,l=!0)}}catch(ej){console.warn("Failed to restore map view:",ej)}const c=new _K({center:tG(o),zoom:a,projection:"EPSG:3857"});this.mapInstance=new wQ({target:t,layers:[e,n,s,r],view:c,controls:GK({zoom:!0,rotate:!0,attribution:!0}),interactions:EZ({dragPan:!1})});const u=eG(c.getCenter());this.mapUi.updateCenter(u[1],u[0]),function(t,e,n={}){let r,i;if(PV){if(!(t instanceof wQ||t instanceof UZ))throw new Error("ol-mapbox-style in a web worker requires a Map or a LayerGroup as first argument");i=t}else i="string"==typeof t||t instanceof HTMLElement?new wQ({target:t}):t;{const t=e.startsWith("data:")?location.href:l4(e,n.accessToken);n=M8(t,n),r=new Promise(function(r,s){S4(e,n).then(function(e){(function(t,e,n,r){const i=[];let s=null;if(e instanceof wQ){if(s=e.getView(),!s.isDef()&&!s.getRotation()&&!s.getResolutions()){const t=r.projection?YH(r.projection):s.getProjection();s=new _K(Object.assign(s.getProperties(),{maxResolution:v4[0]/eH[t.getUnits()],projection:r.projection||s.getProjection()})),e.setView(s)}"center"in t&&!s.getCenter()&&s.setCenter(tG(t.center,s.getProjection())),"zoom"in t&&void 0===s.getZoom()&&s.setResolution(v4[0]/eH[s.getProjection().getUnits()]/Math.pow(2,t.zoom)),s.getCenter()&&void 0!==s.getZoom()||s.fit(s.getProjection().getExtent(),{nearest:!0,size:e.getSize()})}e.set("mapbox-style",t),e.set("mapbox-metadata",{styleUrl:n,options:r});const o=t.layers;let a,l,c,u=[];for(let h=0,d=o.length;h';const d=document.createElement("div");d.className="selected-pin-shadow",this.selectedPinElement.appendChild(h),this.selectedPinElement.appendChild(d),this.selectedPinOverlay=new EQ({element:this.selectedPinElement,positioning:"bottom-center",stopEvent:!1}),this.mapInstance.addOverlay(this.selectedPinOverlay),this.crosshairElement=document.createElement("div"),this.crosshairElement.className="map-crosshair",this.crosshairElement.innerHTML='\n \n \n \n \n ',t.appendChild(this.crosshairElement),this.locationOverlayElement=document.createElement("div"),this.locationOverlayElement.className="search-pulse blue",this.locationOverlay=new EQ({element:this.locationOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.locationOverlay),t.addEventListener("pointerdown",()=>{this.mapUi.searchBoxHasFocus&&(this.ignoreNextMapClick=!0)},!0);const p=new h1({trackingOptions:{enableHighAccuracy:!0},projection:c.getProjection()}),f=new TQ;f.setStyle(new NJ({image:new AJ({radius:6,fill:new OJ({color:"#3399CC"}),stroke:new DJ({color:"#fff",width:2})})}));const g=new q0({features:[f]}),m=new R0({source:g,zIndex:15});p.on("change:position",function(){const t=p.getPosition();f.setGeometry(t?new XG(t):null)});const y=document.createElement("div");y.className="ol-control ol-locate";const v=document.createElement("button");let b,w;v.style.display="flex",v.style.alignItems="center",v.style.justifyContent="center",v.innerHTML=`${qj("navigation")}`,v.title="Locate Me",y.appendChild(v);const _=()=>{b&&(clearTimeout(b),b=null);try{w&&(p.un("change:position",x),w=null)}catch{}this.locationOverlayElement&&this.locationOverlayElement.classList.remove("active")},x=()=>{const t=p.getPosition(),e=p.getAccuracyGeometry(),n=p.getAccuracy();if(console.debug("Geolocation change:",{coordinates:t,accuracy:n}),!t)return;const r=this.mapInstance.getSize(),i=this.mapInstance.getView();let s=null;if(this.locationOverlayElement){const e=i.getResolution(),r=2*(n||50)/XH(i.getProjection(),e,t);this.locationOverlayElement.style.width=`${r}px`,this.locationOverlayElement.style.height=`${r}px`,this.locationOverlay.setPosition(t)}if(n&&n<=20&&_(),e){const t=e.getExtent();s=3.162*i.getResolutionForExtent(t,r)}else n&&(s=6.325*n/Math.min(r[0],r[1])/XH(i.getProjection(),1,t));let o={center:t,duration:1e3};if(s){const t=i.getResolutionForZoom(17);o.resolution=Math.max(s,t)}else o.zoom=16;this.mapInstance.getView().animate(o)},C=()=>{console.debug("Getting current geolocation..."),_(),p.setTracking(!0);const t=p.getPosition();this.locationOverlayElement&&this.locationOverlayElement.classList.add("active"),t&&x(),w=p.on("change:position",x),b=setTimeout(()=>{_()},1e4)};v.addEventListener("click",C);const S=new qK({element:y});this.mapInstance.addLayer(m),this.mapInstance.addControl(S),l||"index"!==this.router.currentRouteName||C(),this.mapInstance.on("singleclick",this.handleMapClick),this.mapInstance.on("moveend",this.handleMapMove),this.mapInstance.on("pointermove",t=>{const e=this.mapInstance.getEventPixel(t.originalEvent),n=this.mapInstance.hasFeatureAtPixel(e,{hitTolerance:10});this.mapInstance.getTarget().style.cursor=n?"pointer":""}),this.storage.rs.on("ready",()=>{this.handleMapMove()})});updateInteractions=UB(()=>{if(!this.mapInstance)return;this.mapInstance.getInteractions().getArray().slice().forEach(t=>{t instanceof hZ&&this.mapInstance.removeInteraction(t)});const t=!!this.settings.mapKinetic&&new KK(-.005,.05,100);this.settings.mapKinetic&&window.innerWidth<=768&&(t.minVelocity_=.25),this.mapInstance.addInteraction(new hZ({kinetic:t}))});updateSearchResults=UB(()=>{if(!this.searchResultsSource)return;this.searchResultsSource.clear();const t=this.mapUi.searchResults;if(!t||0===t.length)return;const e=[];t.forEach(t=>{if(t.lat&&t.lon){const n=new TQ({geometry:new XG(tG([t.lon,t.lat])),name:t.title,id:t.id,isSearchResult:!0,originalPlace:t});e.push(n)}}),e.length>0&&this.searchResultsSource.addFeatures(e)});updateSelectedPin=UB(()=>{const t=this.mapUi.selectedPlace,e=this.mapUi.selectionOptions||{};if(this.searchResultsSource&&this.searchResultsSource.changed(),this.selectedPinOverlay&&this.selectedPinElement)if(this.selectedShapeSource&&this.selectedShapeSource.clear(),t&&t.lat&&t.lon){const n=tG([t.lon,t.lat]);if(this.selectedPinOverlay.setPosition(n),this.selectedPinElement.classList.remove("active"),this.selectedPinElement.offsetWidth,this.selectedPinElement.classList.add("active"),t.geojson&&this.selectedShapeSource)try{const e=(new X0).readFeature(t.geojson,{featureProjection:"EPSG:3857"});this.selectedShapeSource.addFeature(e)}catch(ej){console.warn("Failed to render selected place shape:",ej)}e.preventZoom?this.handlePinVisibility(n,{maintainZoom:!0}):t.bbox?this.zoomToBbox(t.bbox):this.handlePinVisibility(n)}else this.selectedPinElement.classList.remove("active"),this.selectedPinOverlay.setPosition(void 0)});zoomToBbox(t){if(!this.mapInstance||!t)return;const e=this.mapInstance.getView(),n=this.mapInstance.getSize(),r=[...tG([t.minLon,t.minLat]),...tG([t.maxLon,t.maxLat])];let i=[.15*n[1],.15*n[0],.15*n[1],.15*n[0]];if(n[0]<=768){const t=.5*n[1],e=.15*t,r=.5*n[1]+.15*t;i[0]=e,i[2]=r}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),e=parseInt(t,10)||360,r=n[0]-e;i[3]=e+.15*r,i[1]=.15*r}const s=e.getZoom();e.fit(r,{padding:i,duration:1e3,easing:t=>t*(2-t),maxZoom:Math.max(s,18)})}handlePinVisibility(t,e={}){if(!this.mapInstance)return;const n=this.mapInstance.getView().getZoom();if(!e.maintainZoom&&n<16)return void this.animateToSmartCenter(t,16);const r=this.mapInstance.getPixelFromCoordinate(t),i=this.mapInstance.getSize();if(!r||r[0]<0||r[0]>i[0]||r[1]<0||r[1]>i[1]){const n=e.maintainZoom?null:16;this.animateToSmartCenter(t,n)}else this.panIfObscured(t)}animateToSmartCenter(t,e=null){if(!this.mapInstance)return;const n=this.mapInstance.getSize(),r=this.mapInstance.getView();let i=r.getResolution();null!==e&&(i=r.getResolutionForZoom(e));let s=t;if(n[0]<=768){const e=.25*n[1]*i;s=[t[0],t[1]-e]}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),n=(parseInt(e,10)||360)/2*i;s=[t[0]-n,t[1]]}const o={center:s,duration:1e3,easing:t=>t*(2-t)};null!==e&&(o.zoom=e),r.animate(o)}panIfObscured(t){if(!this.mapInstance)return;const e=this.mapInstance.getSize(),n=this.mapInstance.getPixelFromCoordinate(t);if(!n)return;const r=this.mapInstance.getView(),i=r.getCenter(),s=r.getResolution();let o=n[0],a=n[1],l=!1;if(e[0]<=768){const t=e[1],r=t/2;n[1]>r&&(a=.25*t,l=!0)}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),r=parseInt(t,10)||360;n[0]t*(2-t)})}}updateBookmarks=UB(()=>{const t=this.storage.placesInView;this.loadBookmarks(t)});async loadBookmarks(t=[]){try{if(!this.bookmarkSource)return;t&&0!==t.length||(t=this.storage.placesInView),this.bookmarkSource.clear(),t&&Array.isArray(t)&&t.forEach(t=>{if(t.lat&&t.lon){const e=new TQ({geometry:new XG(tG([t.lon,t.lat])),name:t.title,id:t.id,isBookmark:!0,originalPlace:t});this.bookmarkSource.addFeature(e)}})}catch(ej){console.error("Failed to load bookmarks:",ej)}}syncPulse=UB(()=>{this.searchOverlayElement&&(this.mapUi.isSearching?this.searchOverlayElement.classList.add("active"):this.searchOverlayElement.classList.remove("active"))});syncCreationMode=UB(()=>{if(this.crosshairElement&&this.mapInstance)if(this.mapUi.isCreating){this.crosshairElement.classList.add("visible");const t=this.mapUi.creationCoordinates;if(t&&t.lat&&t.lon){const e=tG([t.lon,t.lat]);this.animateToCrosshair(e)}}else this.crosshairElement.classList.remove("visible")});animateToCrosshair(t){if(!this.mapInstance||!this.crosshairElement)return;const e=this.mapInstance.getTargetElement().getBoundingClientRect(),n=this.crosshairElement.getBoundingClientRect(),r=n.left+n.width/2-e.left,i=n.top+n.height/2-e.top,s=this.mapInstance.getSize(),o=r-s[0]/2,a=i-s[1]/2,l=this.mapInstance.getView(),c=l.getResolution(),u=o*c,h=-a*c,d=t[0]-u,p=t[1]-h,f=l.getCenter();Math.sqrt(Math.pow(f[0]-d,2)+Math.pow(f[1]-p,2))>5*c&&l.animate({center:[d,p],duration:800,easing:t=>t*(2-t)})}handleMapMove=async()=>{if(!this.mapInstance||this.isDestroying||this.isDestroyed)return;const t=eG(this.mapInstance.getView().getCenter());if(this.mapUi.updateCenter(t[1],t[0]),this.mapUi.isCreating){const t=this.mapInstance.getTargetElement().getBoundingClientRect(),e=this.crosshairElement.getBoundingClientRect(),n=e.left+e.width/2-t.left,r=e.top+e.height/2-t.top,i=eG(this.mapInstance.getCoordinateFromPixel([n,r])),s=parseFloat(i[1].toFixed(6)),o=parseFloat(i[0].toFixed(6));this.mapUi.updateCreationCoordinates(s,o),this.router.replaceWith("place.new",{queryParams:{lat:s,lon:o}})}const e=this.mapInstance.getSize(),n=this.mapInstance.getView().calculateExtent(e),[r,i]=eG([n[0],n[1]]),[s,o]=eG([n[2],n[3]]),a={minLat:i,minLon:r,maxLat:o,maxLon:s};this.mapUi.updateBounds(a),await this.storage.loadPlacesInBounds(a),this.nostrData.loadPlacesInBounds(a),this.loadBookmarks(this.storage.placesInView);try{const t=this.mapInstance.getView(),e={center:eG(t.getCenter()),zoom:t.getZoom()};localStorage.setItem("marco:map-view",JSON.stringify(e))}catch(ej){console.warn("Failed to save map view:",ej)}};handleMapClick=async t=>{if(this.ignoreNextMapClick)return void(this.ignoreNextMapClick=!1);const e=this.mapInstance.getFeaturesAtPixel(t.pixel,{hitTolerance:10});let n=null,r=null,i=null;if(e&&e.length>0){console.debug(`Found ${e.length} features in map layer:`);for(const n of e)console.debug(n);const t=e.find(t=>t.get("isBookmark")),s=e.find(t=>t.get("isSearchResult"));t?n=t.get("originalPlace"):s&&(r=s.get("originalPlace"));const o=e[0].getProperties();o.name&&(i=o.name)}const s=t=>{("search"===this.router.currentRouteName||this.mapUi.currentSearch&&this.mapUi.searchResults.length>0)&&(this.mapUi.returnToSearch=!0),this.mapUi.preventNextZoom=!0,this.router.transitionTo("place",t)};if(this.args.isSidebarOpen){const t=n||r;return t?(console.debug("Clicked feature while sidebar open (switching):",t),void s(t)):void(this.args.onOutsideClick&&this.args.onOutsideClick())}if(n)return console.debug("Clicked bookmark:",n),void s(n);if(r)return console.debug("Clicked search result:",r),void s(r);if(this.mapInstance.getView().getZoom()<16)return;const o=eG(t.coordinate),[a,l]=o,c=i?30:50;if(this.searchOverlayElement){const e=this.mapInstance.getView(),n=2*c/XH(e.getProjection(),e.getResolution(),t.coordinate);this.searchOverlayElement.style.width=`${n}px`,this.searchOverlayElement.style.height=`${n}px`,this.searchOverlay.setPosition(t.coordinate)}this.mapUi.startSearch();const u={lat:l.toFixed(6),lon:a.toFixed(6),q:null,category:null,selected:i||null};this.router.transitionTo("search",{queryParams:u})};static{Xr(em({id:null,block:'[[[11,0],[16,0,[29,["map-container ",[52,[30,1],"sidebar-open"]]]],[4,[30,0,["setupMap"]],null,null],[4,[30,0,["updateInteractions"]],null,null],[4,[30,0,["updateBookmarks"]],null,null],[4,[30,0,["updateSearchResults"]],null,null],[4,[30,0,["updateSelectedPin"]],null,null],[4,[30,0,["syncPulse"]],null,null],[4,[30,0,["syncCreationMode"]],null,null],[12],[13]],["@isSidebarOpen"],["if"]]',moduleName:"/home/basti/src/marco/app/components/map.gjs",isStrictMode:!0}),this)}}class j8 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"osmAuth",[$f])}#Gt=void fF(this,"osmAuth");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isNostrConnectModalOpen",[Is],function(){return!1})}#qt=void fF(this,"isNostrConnectModalOpen");connectRS(){this.args.onClose(),this.args.storage.showConnectWidget()}static{pF(this.prototype,"connectRS",[Pu])}disconnectRS(){this.args.storage.disconnect()}static{pF(this.prototype,"disconnectRS",[Pu])}connectOsm(){this.args.onClose(),this.osmAuth.login()}static{pF(this.prototype,"connectOsm",[Pu])}disconnectOsm(){this.osmAuth.logout()}static{pF(this.prototype,"disconnectOsm",[Pu])}openNostrConnectModal(){this.isNostrConnectModalOpen=!0}static{pF(this.prototype,"openNostrConnectModal",[Pu])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{pF(this.prototype,"closeNostrConnectModal",[Pu])}disconnectNostr(){this.nostrAuth.disconnect()}static{pF(this.prototype,"disconnectNostr",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"user-menu-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"account-list"],[12],[1,"\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["remotestorage",18]],null],[1,"\\n "],[10,1],[12],[1,"RemoteStorage"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectRS"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectRS"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[10,"strong"],[12],[1,[30,1,["userAddress"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",18]],null],[1,"\\n "],[10,1],[12],[1,"OpenStreetMap"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectOsm"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectOsm"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[10,"strong"],[12],[1,[30,0,["osmAuth","userDisplayName"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",18]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectNostr"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["openNostrConnectModal"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[10,"strong"],[15,"title",[30,0,["nostrAuth","pubkey"]]],[12],[1,"\\n "],[1,[30,0,["nostrData","userDisplayName"]]],[1,"\\n "],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,2],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,3],null,[["@onConnect"],[[30,0,["closeNostrConnectModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],["@storage"],["if"]]',moduleName:"/home/basti/src/marco/app/components/user-menu.gjs",scope:()=>[DB,Sb,Eq,kq],isStrictMode:!0}),this)}}du.Promise;class B8 extends MU{_deferable(){return KU.defer()}}class U8 extends B8{constructor(t){super(),this.ms=t}onYield(t){let e=_a(()=>t.next(),this.ms);return()=>ka(e)}}class $8 extends LB{static{dF(this.prototype,"photon",[$f])}#Ht=void fF(this,"photon");static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"map",[$f])}#Kt=void fF(this,"map");static{dF(this.prototype,"_internalQuery",[Is],function(){return""})}#Zt=void fF(this,"_internalQuery");static{dF(this.prototype,"results",[Is],function(){return[]})}#Yt=void fF(this,"results");static{dF(this.prototype,"isFocused",[Is],function(){return!1})}#Xt=void fF(this,"isFocused");static{dF(this.prototype,"isLoading",[Is],function(){return!1})}#Jt=void fF(this,"isLoading");get query(){return this.args.query??this._internalQuery}set query(t){this._internalQuery=t}get showPopover(){return this.isFocused&&this.results.length>0}handleInput(t){const e=t.target.value;this.query=e,this.args.onQueryChange&&this.args.onQueryChange(e),e.length<2?this.results=[]:this.searchTask.perform(e)}static{pF(this.prototype,"handleInput",[Pu])}searchTask=i$(()=>({context:this,generator:function*(t){yield new U8(300);const e="string"==typeof t?t:this.query;if(!(e.length<2)){this.isLoading=!0;try{let t,n;this.mapUi.currentCenter&&({lat:t,lon:n}=this.mapUi.currentCenter);const r=e.toLowerCase(),i=PN.filter(t=>t.label.toLowerCase().includes(r)).map(t=>({source:"category",title:t.label,id:t.id,icon:"search"})),s=yield this.photon.search(e,t,n);this.results=[...i,...s]}catch(ej){console.error("Search failed",ej),this.results=[]}finally{this.isLoading=!1}}}}),{restartable:!0},"searchTask");handleFocus(){this.isFocused=!0,this.mapUi.setSearchBoxFocus(!0),this.query.length>=2&&0===this.results.length&&this.searchTask.perform()}static{pF(this.prototype,"handleFocus",[Pu])}handleBlur(){setTimeout(()=>{this.isFocused=!1,this.mapUi.setSearchBoxFocus(!1)},300)}static{pF(this.prototype,"handleBlur",[Pu])}handleSubmit(t){if(t.preventDefault(),!this.query)return;let e={q:this.query,selected:null,category:null};if(this.mapUi.currentCenter){const{lat:t,lon:n}=this.mapUi.currentCenter;e.lat=parseFloat(t).toFixed(4),e.lon=parseFloat(n).toFixed(4)}this.router.transitionTo("search",{queryParams:e}),this.isFocused=!1}static{pF(this.prototype,"handleSubmit",[Pu])}selectResult(t){if("category"===t.source){this.query=t.title,this.args.onQueryChange&&this.args.onQueryChange(t.title),this.results=[];let e=null,n=null;return this.mapUi.currentCenter&&(({lat:e,lon:n}=this.mapUi.currentCenter),e=e?.toString(),n=n?.toString()),void this.router.transitionTo("search",{queryParams:{q:t.title,category:t.id,selected:null,lat:e,lon:n}})}if(this.query=t.title,this.args.onQueryChange&&this.args.onQueryChange(t.title),this.results=[],t.osmId){const e=`osm:${t.osmType}:${t.osmId}`;this.router.transitionTo("place",e)}else this.router.transitionTo("search",{queryParams:{q:t.title,lat:t.lat,lon:t.lon,selected:null,category:null}})}static{pF(this.prototype,"selectResult",[Pu])}clear(){this.searchTask.cancelAll(),this.mapUi.stopLoading(),this.osm.cancelAll(),this.photon.cancelAll(),this.query="",this.results=[],this.args.onQueryChange&&this.args.onQueryChange(""),this.router.transitionTo("index")}static{pF(this.prototype,"clear",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"search-box"],[12],[1,"\\n "],[11,"form"],[24,0,"search-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"menu-btn-integrated"],[24,"aria-label","Menu"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["menu",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"input"],[24,0,"search-input"],[24,"placeholder","Search places..."],[24,"aria-label","Search places"],[16,2,[30,0,["query"]]],[24,"autocomplete","off"],[24,4,"search"],[4,[32,0],["input",[30,0,["handleInput"]]],null],[4,[32,0],["focus",[30,0,["handleFocus"]]],null],[4,[32,0],["blur",[30,0,["handleBlur"]]],null],[12],[13],[1,"\\n\\n "],[10,"button"],[14,0,"search-submit-btn"],[14,"aria-label","Search"],[14,4,"submit"],[12],[1,"\\n"],[41,[28,[32,2],[[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"text"],null],[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"category"],null]],null],[[[1," "],[8,[32,1],null,[["@name","@size"],["loading-ring",20]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#5f6368"]],null],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["query"]],[[[1," "],[11,"button"],[24,0,"search-clear-btn"],[24,"aria-label","Clear"],[24,4,"button"],[4,[32,0],["click",[30,0,["clear"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["showPopover"]],[[[1," "],[10,0],[14,0,"search-results-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"search-results-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,0,["results"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"search-result-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,4],[[30,0,["selectResult"]],[30,2]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"result-icon"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],[[52,[30,2,["icon"]],[30,2,["icon"]],"map-pin"],16,"#666"]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"result-info"],[12],[1,"\\n "],[10,1],[14,0,"result-title"],[12],[1,[30,2,["title"]]],[13],[1,"\\n"],[41,[28,[32,3],[[30,2,["source"]],"osm"],null],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[28,[32,5],[[30,2,["type"]]],null]],[13],[1,"\\n"]],[]],[[[41,[30,2,["description"]],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[30,2,["description"]]],[13],[1,"\\n"]],[]],null]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13]],["@onToggleMenu","result"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/search-box.gjs",scope:()=>[Sb,DB,FB,zB,AB,Lq],isStrictMode:!0}),this)}}class q8 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");get categories(){return PN}searchCategory(t){this.args.onSelect&&this.args.onSelect(t);let e={category:t.id,q:null};if(this.mapUi.currentCenter){const{lat:t,lon:n}=this.mapUi.currentCenter;e.lat=parseFloat(t).toFixed(4),e.lon=parseFloat(n).toFixed(4)}this.router.transitionTo("search",{queryParams:e})}static{pF(this.prototype,"searchCategory",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"category-chips-scroll"],[12],[1,"\\n "],[10,0],[14,0,"category-chips-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["categories"]]],null]],null],null,[[[1," "],[11,"button"],[24,0,"category-chip"],[16,"aria-label",[30,1,["label"]]],[16,"disabled",[28,[32,0],[[28,[32,1],[[30,0,["mapUi","loadingState","type"]],"category"],null],[28,[32,1],[[30,0,["mapUi","loadingState","value"]],[30,1,["id"]]],null]],null]],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,0,["searchCategory"]],[30,1]],null]],null],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size"],[[30,1,["icon"]],16]],null],[1,"\\n "],[10,1],[12],[1,[30,1,["label"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[1]],null],[1," "],[13],[1,"\\n"],[13]],["category"],["each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/category-chips.gjs",scope:()=>[a$,zB,Sb,AB,DB],isStrictMode:!0}),this)}}const V8=UB((t,[e])=>{let n=null;return async function(){if(e)try{const r=await caches.open("nostr-image-cache-v1"),i=await r.match(e);if(i){const e=await i.blob();return n=URL.createObjectURL(e),void(t.src=n)}const s=await fetch(e,{mode:"cors",credentials:"omit"});if(s.ok){const i=s.clone();await r.put(e,i);const o=await s.blob();n=URL.createObjectURL(o),t.src=n}else t.src=e}catch(v5){console.warn(`Failed to cache image ${e}, falling back to standard src`,v5),t.src=e}else t.src=""}(),()=>{n&&(URL.revokeObjectURL(n),n=null)}});class W8 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrAuth",[$f])}#M=void fF(this,"nostrAuth");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"isUserMenuOpen",[Is],function(){return!1})}#Qt=void fF(this,"isUserMenuOpen");static{dF(this.prototype,"searchQuery",[Is],function(){return""})}#te=void fF(this,"searchQuery");get hasQuery(){return!!this.searchQuery}toggleUserMenu(){this.isUserMenuOpen=!this.isUserMenuOpen}static{pF(this.prototype,"toggleUserMenu",[Pu])}closeUserMenu(){this.isUserMenuOpen=!1}static{pF(this.prototype,"closeUserMenu",[Pu])}handleQueryChange(t){this.searchQuery=t}static{pF(this.prototype,"handleQueryChange",[Pu])}handleChipSelect(t){this.searchQuery=t.label}static{pF(this.prototype,"handleChipSelect",[Pu])}static{Xr(em({id:null,block:'[[[10,"header"],[14,0,"app-header"],[12],[1,"\\n "],[10,0],[14,0,"header-left"],[12],[1,"\\n "],[8,[32,0],null,[["@query","@onToggleMenu","@onQueryChange"],[[30,0,["searchQuery"]],[30,1],[30,0,["handleQueryChange"]]]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["settings","showQuickSearchButtons"]],[[[1," "],[10,0],[15,0,[29,["header-center ",[52,[30,0,["hasQuery"]],"searching"]]]],[12],[1,"\\n "],[8,[32,1],null,[["@onSelect"],[[30,0,["handleChipSelect"]]]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,0],[14,0,"header-right"],[12],[1,"\\n "],[10,0],[14,0,"user-menu-container"],[12],[1,"\\n "],[11,"button"],[24,0,"user-btn btn-press"],[24,"aria-label","User Menu"],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleUserMenu"]]],null],[12],[1,"\\n"],[41,[28,[32,3],[[30,0,["nostrAuth","isConnected"]],[30,0,["nostrData","profile","picture"]]],null],[[[1," "],[11,"img"],[24,0,"user-avatar"],[24,"alt","User Avatar"],[4,[32,4],[[30,0,["nostrData","profile","picture"]]],null],[12],[13],[1,"\\n"]],[]],[[[1," "],[10,0],[14,0,"user-avatar-placeholder"],[12],[1,"\\n "],[8,[32,5],null,[["@name","@size","@color"],["user",20,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isUserMenuOpen"]],[[[1," "],[8,[32,6],null,[["@storage","@onClose"],[[30,0,["storage"]],[30,0,["closeUserMenu"]]]],null],[1,"\\n "],[11,0],[24,0,"menu-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["closeUserMenu"]]],null],[12],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onToggleMenu"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-header.gjs",scope:()=>[$8,q8,Sb,a$,V8,DB,j8],isStrictMode:!0}),this)}}const H8=Ny,G8=Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[1,"\\n "],[10,1],[14,0,"app-logo-icon"],[12],[1,"\\n "],[1,[28,[32,0],[[32,1]],null]],[1,"\\n "],[13],[1,"\\n Marco\\n "],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,2],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"ul"],[14,0,"app-menu"],[12],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"settings"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["settings",20]],null],[1,"\\n "],[10,1],[12],[1,"Settings"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"about"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["info",20]],null],[1,"\\n "],[10,1],[12],[1,"About"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onClose","@onNavigate"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/home.gjs",scope:()=>[zw,'\n \x3c!-- Background --\x3e\n \n\n \x3c!-- Subtle map grid (kept well outside safe zone) --\x3e\n \n \n \n \n\n \n \n \n \n\n \x3c!-- Location pin (exact app shape, larger, centered, safe-zone compliant) --\x3e\n \x3c!-- Safe zone target: ~680px diameter --\x3e\n \n \n \n \n\n',Sb,DB,AB],isStrictMode:!0}),H8());class K8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",20]],null],[1,"\\n "],[10,1],[12],[1,"Map & UI"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","show-quick-search"],[12],[1,"Quick search buttons visible"],[13],[1,"\\n "],[11,"select"],[24,1,"show-quick-search"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"showQuickSearchButtons"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","showQuickSearchButtons"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","showQuickSearchButtons"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","map-kinetic"],[12],[1,"Map Inertia (Kinetic Panning)"],[13],[1,"\\n "],[11,"select"],[24,1,"map-kinetic"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"mapKinetic"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","mapKinetic"]],"selected"]],[12],[1,"\\n On\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","mapKinetic"]]],"selected"]],[12],[1,"\\n Off\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange"],["if","unless"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/map-ui.gjs",scope:()=>[DB,Sb,AB],isStrictMode:!0}),this)}}class Z8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["server",20]],null],[1,"\\n "],[10,1],[12],[1,"API Providers"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","overpass-api"],[12],[1,"Overpass API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"overpass-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"overpassApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","overpassApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,2,["url"]]],[15,"selected",[52,[28,[32,3],[[30,2,["url"]],[30,0,["settings","overpassApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,2,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","photon-api"],[12],[1,"Photon API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"photon-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"photonApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","photonApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,3,["url"]]],[15,"selected",[52,[28,[32,3],[[30,3,["url"]],[30,0,["settings","photonApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,3,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","api","api"],["each","-track-array","if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/apis.gjs",scope:()=>[DB,Sb,AB,zB],isStrictMode:!0}),this)}}const Y8=t=>t?t.replace(/^wss?:\/\//,""):"";class X8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");static{dF(this.prototype,"nostrData",[$f])}#L=void fF(this,"nostrData");static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");static{dF(this.prototype,"newReadRelay",[Is],function(){return""})}#ee=void fF(this,"newReadRelay");static{dF(this.prototype,"newWriteRelay",[Is],function(){return""})}#ne=void fF(this,"newWriteRelay");updateNewReadRelay(t){this.newReadRelay=t.target.value}static{pF(this.prototype,"updateNewReadRelay",[Pu])}updateNewWriteRelay(t){this.newWriteRelay=t.target.value}static{pF(this.prototype,"updateNewWriteRelay",[Pu])}addReadRelay(){const t=AD(this.newReadRelay);if(!t)return;const e=this.settings.nostrReadRelays||this.nostrData.defaultReadRelays,n=new Set([...e,t]);this.settings.update("nostrReadRelays",Array.from(n)),this.newReadRelay=""}static{pF(this.prototype,"addReadRelay",[Pu])}removeReadRelay(t){const e=(this.settings.nostrReadRelays||this.nostrData.defaultReadRelays).filter(e=>e!==t);this.settings.update("nostrReadRelays",e)}static{pF(this.prototype,"removeReadRelay",[Pu])}handleReadRelayKeydown(t){"Enter"===t.key&&this.addReadRelay()}static{pF(this.prototype,"handleReadRelayKeydown",[Pu])}handleWriteRelayKeydown(t){"Enter"===t.key&&this.addWriteRelay()}static{pF(this.prototype,"handleWriteRelayKeydown",[Pu])}resetReadRelays(){this.settings.update("nostrReadRelays",null)}static{pF(this.prototype,"resetReadRelays",[Pu])}addWriteRelay(){const t=AD(this.newWriteRelay);if(!t)return;const e=this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays,n=new Set([...e,t]);this.settings.update("nostrWriteRelays",Array.from(n)),this.newWriteRelay=""}static{pF(this.prototype,"addWriteRelay",[Pu])}removeWriteRelay(t){const e=(this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays).filter(e=>e!==t);this.settings.update("nostrWriteRelays",e)}static{pF(this.prototype,"removeWriteRelay",[Pu])}resetWriteRelays(){this.settings.update("nostrWriteRelays",null)}static{pF(this.prototype,"resetWriteRelays",[Pu])}async clearCache(){try{await this.nostrData.clearCache(),this.toast.show("Nostr cache cleared")}catch(ej){this.toast.show(`Failed to clear Nostr cache: ${ej.message}`)}}static{pF(this.prototype,"clearCache",[Pu])}static{Xr(em({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",20]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","nostr-photo-fallback-uploads"],[12],[1,"Upload photos to fallback\\n servers"],[13],[1,"\\n "],[11,"select"],[24,1,"nostr-photo-fallback-uploads"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"nostrPhotoFallbackUploads"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","nostrPhotoFallbackUploads"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","nostrPhotoFallbackUploads"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-read-relay"],[12],[1,"Read Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeReadRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,2]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeReadRelay"]],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-read-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newReadRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewReadRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleReadRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addReadRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrReadRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetReadRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-write-relay"],[12],[1,"Write Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeWriteRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,3]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeWriteRelay"]],[30,3]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-write-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newWriteRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewWriteRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleWriteRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addWriteRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrWriteRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetWriteRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[12],[1,"Cached data"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline btn-full"],[24,4,"button"],[4,[32,1],["click",[30,0,["clearCache"]]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["database",18,"var(--danger-color)"]],null],[1,"\\n Clear profiles, photos, and reviews\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","relay","relay"],["if","unless","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/nostr.gjs",scope:()=>[DB,Sb,AB,Y8],isStrictMode:!0}),this)}}class J8 extends LB{static{dF(this.prototype,"settings",[$f])}#I=void fF(this,"settings");updateSetting(t,e){let n=e.target.value;"true"===n&&(n=!0),"false"===n&&(n=!1),this.settings.update(t,n)}static{pF(this.prototype,"updateSetting",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"Settings"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"settings-section"],[12],[1,"\\n "],[8,[32,2],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,3],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,4],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings.gjs",scope:()=>[Sb,DB,K8,Z8,X8],isStrictMode:!0}),this)}}const Q8=Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"About"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"about-section"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Marco"],[13],[1,"\\n (as in\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/Marco_Polo"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"Marco Polo"],[13],[1,") is an unhosted maps application that respects your\\n privacy and choices.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n Connect your own\\n "],[10,3],[14,6,"https://remotestorage.io/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"remote storage"],[13],[1,"\\n to sync place bookmarks across apps and devices.\\n "],[13],[1,"\\n\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["gift",20]],null],[1,"\\n "],[10,1],[12],[1,"Open Source"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,"table"],[12],[1,"\\n "],[10,"thead"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"th"],[12],[1,"Source"],[13],[1,"\\n "],[10,"th"],[12],[1,"License"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tbody"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://gitea.kosmos.org/raucao/marco"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Marco App\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/GNU_Affero_General_Public_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","GNU Affero General Public License"],[12],[1,"AGPL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://openstreetmap.org/copyright"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Map Data\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://opendatacommons.org/licenses/odbl/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","Open Data Commons Open Database License"],[12],[1,"ODbL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/feathericons/feather"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Feather Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/MIT_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","MIT License"],[12],[1,"MIT"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://pinhead.ink/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Pinhead Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/waysidemapping/pinhead?tab=readme-ov-file#where-the-icons-are-from"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Various\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["heart",20,"#e5533d"]],null],[1,"\\n "],[10,1],[12],[1,"Contribute"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most impactful:"],[13],[1,"\\n Add and improve data for points of interest in\\n "],[10,3],[14,6,"https://www.openstreetmap.org"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"OpenStreetMap"],[13],[1,".\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most appreciated:"],[13],[1,"\\n Use this app as much as you can and\\n "],[10,3],[14,6,"https://community.remotestorage.io/t/marco-an-unhosted-maps-app/941"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"submit feedback"],[13],[1,"\\n about your experience, problems, feature wishes, etc.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most supportive:"],[13],[1,"\\n Tell others about this app, on social media, in blog posts,\\n educational videos, etc.\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/about.gjs",scope:()=>[Sb,DB],isStrictMode:!0}),H8());class t7 extends LB{static{dF(this.prototype,"currentView",[Is],function(){return"menu"})}#re=void fF(this,"currentView");setView(t){this.currentView=t}static{pF(this.prototype,"setView",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar app-menu-pane"],[12],[1,"\\n"],[41,[28,[32,0],[[30,0,["currentView"]],"menu"],null],[[[1," "],[8,[32,1],null,[["@onNavigate","@onClose"],[[30,0,["setView"]],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"settings"],null],[[[1," "],[8,[32,2],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"about"],null],[[[1," "],[8,[32,4],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n "]],[]],null]],[]]]],[]]],[13]],["@onClose"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/index.gjs",scope:()=>[zB,G8,J8,AB,Q8],isStrictMode:!0}),this)}}class e7 extends LB{static{dF(this.prototype,"toast",[$f])}#Mt=void fF(this,"toast");static{Xr(em({id:null,block:'[[[41,[30,0,["toast","isVisible"]],[[[1," "],[10,0],[14,0,"toast-notification"],[12],[1,"\\n "],[1,[30,0,["toast","message"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/toast.gjs",isStrictMode:!0}),this)}}class n7 extends LB{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"isAppMenuOpen",[Is],function(){return!1})}#ie=void fF(this,"isAppMenuOpen");get isSidebarOpen(){return"place"===this.router.currentRouteName||"place.new"===this.router.currentRouteName||"search"===this.router.currentRouteName}constructor(){super(...arguments),console.debug("Application component constructed"),this.storage}toggleAppMenu(){this.isAppMenuOpen=!this.isAppMenuOpen}static{pF(this.prototype,"toggleAppMenu",[Pu])}closeAppMenu(){this.isAppMenuOpen=!1}static{pF(this.prototype,"closeAppMenu",[Pu])}handleOutsideClick(){this.isAppMenuOpen?this.closeAppMenu():("search"===this.router.currentRouteName||"place"===this.router.currentRouteName)&&this.router.transitionTo("index")}static{pF(this.prototype,"handleOutsideClick",[Pu])}refreshBookmarks(){this.storage.notifyChange()}static{pF(this.prototype,"refreshBookmarks",[Pu])}static{Xr(em({id:null,block:'[[[1,[28,[32,0],["Marco"],null]],[1,"\\n\\n"],[8,[32,1],null,[["@onToggleMenu"],[[30,0,["toggleAppMenu"]]]],null],[1,"\\n\\n"],[10,0],[14,1,"rs-widget-container"],[15,0,[52,[30,0,["storage","isWidgetOpen"]],"visible"]],[12],[13],[1,"\\n\\n"],[41,[30,0,["storage","isWidgetOpen"]],[[[1," "],[11,0],[24,0,"rs-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["storage","closeWidget"]]],null],[12],[13],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,3],null,[["@isSidebarOpen","@onOutsideClick"],[[28,[32,4],[[30,0,["isSidebarOpen"]],[30,0,["isAppMenuOpen"]]],null],[30,0,["handleOutsideClick"]]]],null],[1,"\\n\\n"],[41,[30,0,["isAppMenuOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeAppMenu"]]]],null],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,6],null,null,null],[1,"\\n\\n"],[46,[28,[31,2],null,null],null,null,null]],[],["if","component","-outlet"]]',moduleName:"/home/basti/src/marco/app/templates/application.gjs",scope:()=>[Bq,W8,Sb,N8,FB,t7,e7],isStrictMode:!0}),this)}}const r7=Object.freeze(Object.defineProperty({__proto__:null,default:n7},Symbol.toStringTag,{value:"Module"}));class i7 extends kp{static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage")}const s7=Object.freeze(Object.defineProperty({__proto__:null,default:i7},Symbol.toStringTag,{value:"Module"}));class o7 extends kp{static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");activate(){this.mapUi.clearSearchResults()}}const a7=Object.freeze(Object.defineProperty({__proto__:null,default:o7},Symbol.toStringTag,{value:"Module"}));class l7 extends kp{static{dF(this.prototype,"osmAuth",[$f])}#Gt=void fF(this,"osmAuth");static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");async model(){try{await this.osmAuth.handleCallback()}catch(ej){console.error("Failed to handle OSM OAuth callback",ej)}finally{this.router.transitionTo("index")}}}const c7=Object.freeze(Object.defineProperty({__proto__:null,default:l7},Symbol.toStringTag,{value:"Module"}));class u7 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");static{dF(this.prototype,"localPlace",[Is],function(){return null})}#se=void fF(this,"localPlace");constructor(){super(...arguments),this.localPlace=this.args.model}get place(){const t=this.args.model,e=t.osmId||t.id;return this.storage.findPlaceById(e)||(!this.localPlace||this.localPlace.osmId!==e&&this.localPlace.id!==e?t.createdAt?{...t,id:void 0,createdAt:void 0,geohash:void 0}:t:this.localPlace)}handleUpdate(t){console.debug("Updating local place state:",t),this.localPlace=t,this.storage.notifyChange()}static{pF(this.prototype,"handleUpdate",[Pu])}refreshMap(){this.storage.notifyChange()}static{pF(this.prototype,"refreshMap",[Pu])}navigateBack(t){null===t?this.mapUi.returnToSearch&&this.mapUi.currentSearch?this.router.transitionTo("search",{queryParams:this.mapUi.currentSearch}):this.router.transitionTo("index"):this.router.transitionTo("place",t)}static{pF(this.prototype,"navigateBack",[Pu])}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}static{Xr(em({id:null,block:'[[[8,[32,0],null,[["@selectedPlace","@onClose","@onSelect","@onBookmarkChange","@onUpdate"],[[30,0,["place"]],[30,0,["close"]],[30,0,["navigateBack"]],[30,0,["refreshMap"]],[30,0,["handleUpdate"]]]],null]],[],[]]',moduleName:"/home/basti/src/marco/app/templates/place.gjs",scope:()=>[Iq],isStrictMode:!0}),this)}}const h7=Object.freeze(Object.defineProperty({__proto__:null,default:u7},Symbol.toStringTag,{value:"Module"}));class d7 extends kp{static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"osm",[$f])}#ct=void fF(this,"osm");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");async model(t){const e=t.place_id;let n,r,i=!1;(e.startsWith("osm:node:")||e.startsWith("osm:way:")||e.startsWith("osm:relation:"))&&(i=!0,[,n,r]=e.split(":"),console.debug(`Fetching explicit OSM ${n}:`,r));let s=null;i&&(s=this.loadOsmPlace(r,n)),await this.waitForSync();let o=i?r:e,a=this.storage.findPlaceById(o);return a&&i&&a.osmType!==n&&(a=null),a?(console.debug("Found in bookmarks:",a.title),a):i?(console.debug(`Not in bookmarks, using explicitly fetched OSM ${n}:`,r),await s):(console.warn("Not in bookmarks:",e),null)}async waitForSync(){if(this.storage.initialSyncDone)return;console.debug("Waiting for initial storage sync...");const t=Date.now();for(;!this.storage.initialSyncDone;){if(Date.now()-t>5e3){console.warn("Timed out waiting for initial sync");break}await new Promise(t=>setTimeout(t,100))}}async afterModel(t){if(t&&t.osmId&&t.osmType&&"node"!==t.osmType&&!t.geojson){console.debug("Model missing geometry, fetching full OSM details...");const e=await this.loadOsmPlace(t.osmId,t.osmType);e&&(Object.assign(t,e),console.debug("Enriched model with full OSM details",t))}if(t){const e={preventZoom:this.mapUi.preventNextZoom};this.mapUi.selectPlace(t,e),this.mapUi.preventNextZoom=!1}this.mapUi.stopSearch()}deactivate(){this.mapUi.clearSelection(),this.mapUi.returnToSearch=!1}async loadOsmPlace(t,e=null){try{const n=await this.osm.fetchOsmObject(t,e);if(n)return console.debug("Found OSM POI:",n),n}catch(ej){console.error("Failed to fetch POI",ej)}return null}setupController(t,e){super.setupController(t,e),this.checkUpdates(e)}async checkUpdates(t){if(t&&t.id&&t.osmId&&t.osmType){const e=await this.storage.refreshPlace(t);e&&this.mapUi.selectPlace(e,{preventZoom:!0})}}serialize(t){return t.osmId&&t.osmType?{place_id:`osm:${t.osmType}:${t.osmId}`}:t.id?{place_id:t.id}:{place_id:t.osmId}}}const p7=Object.freeze(Object.defineProperty({__proto__:null,default:d7},Symbol.toStringTag,{value:"Module"}));class f7 extends LB{static{dF(this.prototype,"router",[$f])}#kt=void fF(this,"router");static{dF(this.prototype,"storage",[$f])}#St=void fF(this,"storage");static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");get initialPlace(){return{title:"",description:""}}close(){this.router.transitionTo("index")}static{pF(this.prototype,"close",[Pu])}async savePlace(t){try{const e=this.mapUi.creationCoordinates||{lat:this.args.model.lat,lon:this.args.model.lon},n=parseFloat(e.lat.toFixed(6)),r=parseFloat(e.lon.toFixed(6)),i={title:t.title||"Untitled Place",description:t.description,lat:n,lon:r,tags:[],osmTags:{}},s=await this.storage.storePlace(i);console.debug("Created private place:",s.title),this.router.replaceWith("place",s)}catch(ej){console.error("Failed to create place:",ej),alert("Failed to create place: "+ej.message)}}static{pF(this.prototype,"savePlace",[Pu])}static{Xr(em({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[8,[32,0],null,[["@name","@size","@color"],["plus-circle",20,"#ea4335"]],null],[1,"\\n New Place"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,1],["click",[30,0,["close"]]],null],[12],[8,[32,0],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,2],[14,0,"helper-text"],[12],[1,"\\n Drag the map to position the crosshair.\\n "],[13],[1,"\\n\\n "],[8,[32,2],null,[["@place","@onSave","@onCancel"],[[30,0,["initialPlace"]],[30,0,["savePlace"]],[30,0,["close"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],[],[]]',moduleName:"/home/basti/src/marco/app/templates/place/new.gjs",scope:()=>[DB,Sb,NB],isStrictMode:!0}),this)}}const g7=Object.freeze(Object.defineProperty({__proto__:null,default:f7},Symbol.toStringTag,{value:"Module"}));class m7 extends kp{static{dF(this.prototype,"mapUi",[$f])}#Wt=void fF(this,"mapUi");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0}};model(t){return{lat:parseFloat(t.lat),lon:parseFloat(t.lon)}}setupController(t,e){super.setupController(t,e),e.lat&&e.lon&&this.mapUi.updateCreationCoordinates(e.lat,e.lon),this.mapUi.startCreating()}deactivate(){this.mapUi.stopCreating()}}const y7=Object.freeze(Object.defineProperty({__proto__:null,default:m7},Symbol.toStringTag,{value:"Module"})),v7=Object.assign({},px,{"marco/app":t,"marco/config/environment":vx,"marco/deprecation-workflow":wx,"marco/router":Tx,"marco/services/blossom":vF,"marco/services/image-processor":wF,"marco/services/map-ui":xF,"marco/services/nostr-auth":Rz,"marco/services/nostr-data":VD,"marco/services/nostr-relay":rN,"marco/services/osm-auth":kN,"marco/services/osm":zN,"marco/services/photon":NN,"marco/services/settings":UN,"marco/services/storage":zj,"marco/services/toast":Nj,"marco/utils/device":wz,"marco/utils/format-text":TN,"marco/utils/geo":Bj,"marco/utils/geohash-coverage":jD,"marco/utils/icons":Wj,"marco/utils/nostr":FD,"marco/utils/osm-icons":Kj,"marco/utils/osm":IN,"marco/utils/place-mapping":Yj,"marco/utils/poi-categories":ON,"marco/utils/social-links":Jj,"marco/workers/image-processor":cB,"marco/services/page-title":xB,"marco/templates/search":Aq,"marco/controllers/search":Oq,"marco/routes/search":zq,"marco/templates/application":r7,"marco/routes/application":s7,"marco/routes/index":a7,"marco/routes/oauth/osm-callback":c7,"marco/templates/place":h7,"marco/routes/place":p7,"marco/templates/place/new":g7,"marco/routes/place/new":y7},{});class b7{constructor(t,e,n){this.limit=t,this.func=e,this.store=n,this.size=0,this.misses=0,this.hits=0,this.store=n||new Map}get(t){let e=this.store.get(t);return this.store.has(t)?(this.hits++,this.store.get(t)):(this.misses++,e=this.set(t,this.func(t)),e)}set(t,e){return this.limit>this.size&&(this.size++,this.store.set(t,e)),e}purge(){this.store.clear(),this.size=0,this.hits=0,this.misses=0}}const w7=/[ _]/g,_7=new b7(1e3,t=>{return(e=t,L7.get(e)).replace(w7,"-");var e}),x7=/^(\-|_)+(.)?/,C7=/(.)(\-|\_|\.|\s)+(.)?/g,S7=/(^|\/|\.)([a-z])/g,k7=new b7(1e3,t=>{const e=(t,e,n)=>n?`_${n.toUpperCase()}`:"",n=(t,e,n,r)=>e+(r?r.toUpperCase():""),r=t.split("/");for(let i=0;it.toUpperCase())}),E7=/([a-z\d])([A-Z]+)/g,T7=/\-|\s+/g,R7=new b7(1e3,t=>t.replace(E7,"$1_$2").replace(T7,"_").toLowerCase()),M7=/([a-z\d])([A-Z])/g,L7=new b7(1e3,t=>t.replace(M7,"$1_$2").toLowerCase());class I7{constructor(t){this._entries=t||globalThis.requirejs.entries}moduleNames(){return Object.keys(this._entries)}has(t){return t in this._entries}get(...t){return globalThis.require(...t)}}class P7{static moduleBasedResolver=!0;moduleBasedResolver=!0;_deprecatedPodModulePrefix=!1;_normalizeCache=Object.create(null);static create(t){return new this(t)}moduleNameLookupPatterns=[this.podBasedModuleName,this.podBasedComponentsInSubdir,this.mainModuleName,this.defaultModuleName,this.nestedColocationComponentModuleName];static withModules(t){return class extends(this){static explicitModules=t}}constructor(t){if(Object.assign(this,t),!this._moduleRegistry){let t=this.constructor.explicitModules;t?this._moduleRegistry={moduleNames:()=>Object.keys(t),has:e=>Boolean(t[e]),get:e=>t[e],addModules(e){t=Object.assign({},t,e)}}:(void 0===globalThis.requirejs.entries&&(globalThis.requirejs.entries=globalThis.requirejs._eak_seen),this._moduleRegistry=new I7)}this.pluralizedTypes=this.pluralizedTypes||Object.create(null),this.pluralizedTypes.config||(this.pluralizedTypes.config="config")}makeToString(t,e){return this.namespace.modulePrefix+"@"+e+":"}shouldWrapInClassFactory(){return!1}parseName(t){if(!0===t.parsedName)return t;let e,n,r,i=t.split("@");if(3===i.length){if(0===i[0].length){e=`@${i[1]}`;let t=i[2].split(":");n=t[0],r=t[1]}else e=`@${i[1]}`,n=i[0].slice(0,-1),r=i[2];"template:components"===n&&(r=`components/${r}`,n="template")}else if(2===i.length){let t=i[0].split(":");if(2===t.length)0===t[1].length?(n=t[0],r=`@${i[1]}`):(e=t[1],n=t[0],r=i[1]);else{let t=i[1].split(":");e=i[0],n=t[0],r=t[1]}"template"===n&&0===e.lastIndexOf("components/",0)&&(r=`components/${r}`,e=e.slice(11))}else i=t.split(":"),n=i[0],r=i[1];let s=r,o=this.namespace;return{parsedName:!0,fullName:t,prefix:e||this.prefix({type:n}),type:n,fullNameWithoutType:s,name:r,root:o,resolveMethodName:"resolve"+(a=n,k7.get(a))};var a}resolveOther(t){A7("`modulePrefix` must be defined",this.namespace.modulePrefix);let e=this.findModuleName(t);if(e){let r=this._extractDefaultExport(e,t);if(void 0===r)throw new Error(` Expected to find: '${t.fullName}' within '${e}' but got 'undefined'. Did you forget to 'export default' within '${e}'?`);return this.shouldWrapInClassFactory(r,t)&&(n=r,r={create:t=>"function"==typeof n.extend?n.extend(t):n}),r}var n}normalize(t){return this._normalizeCache[t]||(this._normalizeCache[t]=this._normalize(t))}resolve(t){if("resolver:current"===t)return{create:()=>this};let e,n=this.parseName(t),r=n.resolveMethodName;return"function"==typeof this[r]&&(e=this[r](n)),null==e&&(e=this.resolveOther(n)),e}addModules(t){if(!this._moduleRegistry.addModules)throw new Error("addModules is only supported when your Resolver has been configured to use static modules via Resolver.withModules()");this._moduleRegistry.addModules(t)}_normalize(t){let e=t.split(":");if(e.length>1){let t=e[0];return"component"===t||"helper"===t||"modifier"===t||"template"===t&&0===e[1].indexOf("components/")?t+":"+e[1].replace(/_/g,"-"):t+":"+(n=e[1].replace(/\./g,"/"),_7.get(n))}return t;var n}pluralize(t){return this.pluralizedTypes[t]||(this.pluralizedTypes[t]=t+"s")}podBasedLookupWithPrefix(t,e){let n=e.fullNameWithoutType;return"template"===e.type&&(n=n.replace(/^components\//,"")),t+"/"+n+"/"+e.type}podBasedModuleName(t){let e=this.namespace.podModulePrefix||this.namespace.modulePrefix;return this.podBasedLookupWithPrefix(e,t)}podBasedComponentsInSubdir(t){let e=this.namespace.podModulePrefix||this.namespace.modulePrefix;if(e+="/components","component"===t.type||/^components/.test(t.fullNameWithoutType))return this.podBasedLookupWithPrefix(e,t)}resolveEngine(t){let e=t.fullNameWithoutType+"/engine";if(this._moduleRegistry.has(e))return this._extractDefaultExport(e)}resolveRouteMap(t){let e=t.fullNameWithoutType,n=e+"/routes";if(this._moduleRegistry.has(n)){let t=this._extractDefaultExport(n);return A7(`The route map for ${e} should be wrapped by 'buildRoutes' before exporting.`,t.isRouteMap),t}}resolveTemplate(t){return this.resolveOther(t)}mainModuleName(t){if("main"===t.fullNameWithoutType)return t.prefix+"/"+t.type}defaultModuleName(t){return t.prefix+"/"+this.pluralize(t.type)+"/"+t.fullNameWithoutType}nestedColocationComponentModuleName(t){if("component"===t.type)return t.prefix+"/"+this.pluralize(t.type)+"/"+t.fullNameWithoutType+"/index"}prefix(t){let e=this.namespace.modulePrefix;return this.namespace[t.type+"Prefix"]&&(e=this.namespace[t.type+"Prefix"]),e}findModuleName(t){let e,n=this.moduleNameLookupPatterns;for(let r=0,i=n.length;rr.length+i.length)return t+":"+e.slice(s+r.length,o);let a=n+"/"+this.pluralize(t)+"/";return 0===e.indexOf(a)&&e.length>a.length?t+":"+e.slice(a.length):void 0}_extractDefaultExport(t){let e=this._moduleRegistry.get(t,null,null,!0);return e&&e.default&&(e=e.default),e}}function A7(t,e){if(!e)throw new Error(t)}class O7 extends hx{modulePrefix=yx.modulePrefix;podModulePrefix=yx.podModulePrefix;Resolver=P7.withModules(v7);inspector=function(t){!function(t){globalThis.emberInspectorApps||(globalThis.emberInspectorApps=[]),globalThis.emberInspectorApps.push({app:t,name:`app-${globalThis.emberInspectorApps.length}`,loadCompatInspector:()=>MD(()=>import("./modules-4-12-CktBxFgZ.js"),[])}),globalThis.dispatchEvent&&globalThis.dispatchEvent(new Event("Ember"))}(t)}(this)}O7.create(yx.APP);export{Ci as $,Wi as A,as as B,Si as C,Ms as D,Fi as E,po as F,ho as G,ts as H,Os as I,Js as J,Ui as K,Ts as L,xs as M,ao as N,Ls as O,rs as P,Pi as Q,gs as R,Vi as S,As as T,Ve as U,xi as V,mo as W,Rs as X,Ri as Y,mi as Z,ks as _,Cs as a,Xl as a$,ss as a0,di as a1,$i as a2,go as a3,fo as a4,Xs as a5,ji as a6,uo as a7,Gi as a8,Hs as a9,du as aA,$c as aB,Ic as aC,Zc as aD,Nc as aE,Bc as aF,Vc as aG,hu as aH,uu as aI,zc as aJ,Hc as aK,Wc as aL,Uc as aM,et as aN,nd as aO,g as aP,d as aQ,m as aR,p as aS,u as aT,f as aU,ne as aV,Qt as aW,Jt as aX,ae as aY,oe as aZ,se as a_,Ks as aa,Ji as ab,Bi as ac,Ai as ad,yo as ae,Qs as af,vo as ag,gi as ah,fi as ai,Is as aj,Ds as ak,qb as al,ew as am,jr as an,Ew as ao,Jr as ap,pj as aq,Xr as ar,oc as as,Mc as at,Ac as au,Fc as av,Jc as aw,cu as ax,lu as ay,lc as az,us as b,Cx as b$,Yl as b0,Zl as b1,nc as b2,pu as b3,Gl as b4,ic as b5,tc as b6,Jl as b7,fu as b8,si as b9,Ah as bA,ex as bB,Ph as bC,eh as bD,kb as bE,_h as bF,Zu as bG,Wu as bH,Hu as bI,zu as bJ,Ku as bK,Uu as bL,Du as bM,Qu as bN,Yu as bO,Ju as bP,$u as bQ,Nu as bR,Fu as bS,qu as bT,Vu as bU,dx as bV,Y_ as bW,od as bX,_j as bY,hd as bZ,W as b_,Q as ba,at as bb,K_ as bc,st as bd,cl as be,St as bf,tt as bg,nt as bh,no as bi,H as bj,Ct as bk,G as bl,ei as bm,vt as bn,dt as bo,ft as bp,eo as bq,pt as br,ni as bs,_t as bt,bt as bu,kt as bv,wt as bw,Rt as bx,Z as by,mt as bz,$e as c,Ou as c0,rc as c1,gh as c2,Eu as c3,rh as c4,Ru as c5,Ej as c6,Cj as c7,Ta as c8,Vf as c9,ll as ca,ai as cb,IB as cc,Qr as cd,rr as ce,Cb as cf,En as cg,cn as ch,NP as ci,lP as cj,hP as ck,Rx as cl,ZA as cm,eA as cn,PA as co,YP as cp,lo as d,_s as e,Ss as f,qe as g,zs as h,Ki as i,Ys as j,Ni as k,co as l,Hi as m,Ns as n,Vs as o,qs as p,fs as q,os as r,Fs as s,ls as t,ps as u,ys as v,ms as w,vs as x,Ii as y,Li as z}; diff --git a/release/assets/modules-4-12-CyDF3xZj.js b/release/assets/modules-4-12-CktBxFgZ.js similarity index 98% rename from release/assets/modules-4-12-CyDF3xZj.js rename to release/assets/modules-4-12-CktBxFgZ.js index 10638d3..760e97a 100644 --- a/release/assets/modules-4-12-CyDF3xZj.js +++ b/release/assets/modules-4-12-CktBxFgZ.js @@ -1 +1 @@ -import{c as e,g as a,a as s,s as t,A as r,C as o,b as n,D as i,L as l,N as b,d as c,P as p,e as d,S as m,T as u,_ as g,f as y,h as _,i as O,j as S,k as f,l as C,m as P,n as h,o as v,p as j,q as E,r as M,t as D,u as N,v as V,w as A,x as w,y as T,z as I,B as x,E as R,F as k,G as F,H as L,I as z,J as G,K as U,M as B,O as W,Q as Y,R as H,U as J,V as K,W as X,X as q,Y as Q,Z,$,a0 as ee,a1 as ae,a2 as se,a3 as te,a4 as re,a5 as oe,a6 as ne,a7 as ie,a8 as le,a9 as be,aa as pe,ab as de,ac as me,ad as ue,ae as ge,af as ye,ag as _e,ah as Oe,ai as Se,aj as fe,ak as Ce,al as Pe,am as he,an as ve,ao as je,ap as Ee,aq as Me,ar as De,as as Ne,at as Ve,au as Ae,av as we,aw as Te,ax as Ie,ay as xe,az as Re,aA as ke,aB as Fe,aC as Le,aD as ze,aE as Ge,aF as Ue,aG as Be,aH as We,aI as Ye,aJ as He,aK as Je,aL as Ke,aM as Xe,aN as qe,aO as Qe,aP as Ze,aQ as $e,aR as ea,aS as aa,aT as sa,aU as ta,aV as ra,aW as oa,aX as na,aY as ia,aZ as la,a_ as ba,a$ as pa,b0 as da,b1 as ma,b2 as ua,b3 as ga,b4 as ya,b5 as _a,b6 as Oa,b7 as Sa,b8 as fa,b9 as Ca,ba as Pa,bb as ha,bc as va,bd as ja,be as Ea,bf as Ma,bg as Da,bh as Na,bi as Va,bj as Aa,bk as wa,bl as Ta,bm as Ia,bn as xa,bo as Ra,bp as ka,bq as Fa,br as La,bs as za,bt as Ga,bu as Ua,bv as Ba,bw as Wa,bx as Ya,by as Ha,bz as Ja,bA as Ka,bB as Xa,bC as qa,bD as Qa,bE as Za,bF as $a,bG as es,bH as as,bI as ss,bJ as ts,bK as rs,bL as os,bM as ns,bN as is,bO as ls,bP as bs,bQ as cs,bR as ps,bS as ds,bT as ms,bU as us}from"./main-AsE4IKjj.js";export{bV as Application,bW as ApplicationNamespace,bX as Array,bY as ArrayProxy,bZ as Controller,b_ as Debug,b$ as EmberDestroyable,c0 as EmberObject,c1 as EnumerableMutable,cc as GlimmerComponent,cd as GlimmerManager,ce as GlimmerReference,cf as GlimmerRuntime,cg as GlimmerUtil,ch as GlimmerValidator,c2 as Instrumentation,c0 as Object,c3 as ObjectCore,c4 as ObjectEvented,c5 as ObjectObservable,c6 as ObjectPromiseProxyMixin,c7 as ObjectProxy,ca as Owner,c8 as Runloop,c9 as Service,cb as VERSION}from"./main-AsE4IKjj.js";const gs=new WeakMap,ys=Object.freeze(Object.defineProperty({__proto__:null,ASYNC_OBSERVERS:r,ComputedDescriptor:o,ComputedProperty:n,DEBUG_INJECTION_FUNCTIONS:i,Libraries:l,NAMESPACES:b,NAMESPACES_BY_ID:c,PROPERTY_DID_CHANGE:p,PROXY_CONTENT:d,SYNC_OBSERVERS:m,TrackedDescriptor:u,_getPath:g,_getProp:y,_setProp:_,activateObserver:O,addArrayObserver:S,addListener:f,addNamespace:C,addObserver:P,alias:h,arrayContentDidChange:v,arrayContentWillChange:j,autoComputed:E,beginPropertyChanges:M,cached:(...s)=>{const[t,r,o]=s,n=new WeakMap,i=o.get;o.get=function(){return n.has(this)||n.set(this,e(i.bind(this))),a(n.get(this))}},changeProperties:D,computed:N,createCache:e,defineDecorator:V,defineProperty:A,defineValue:w,deprecateProperty:function(e,a,r){Object.defineProperty(e,a,{configurable:!0,enumerable:!1,set(e){t(this,r,e)},get(){return s(this,r)}})},descriptorForDecorator:T,descriptorForProperty:I,eachProxyArrayDidChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayDidChange(e,a,s,t)},eachProxyArrayWillChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayWillChange(e,a,s,t)},endPropertyChanges:x,expandProperties:R,findNamespace:k,findNamespaces:F,flushAsyncObservers:L,get:s,getCachedValueFor:z,getProperties:G,getValue:a,hasListeners:U,hasUnknownProperty:B,inject:W,isClassicDecorator:Y,isComputed:H,isConst:J,isElementDescriptor:K,isNamespaceSearchDisabled:X,libraries:q,makeComputedDecorator:Q,markObjectAsDirty:Z,nativeDescDecorator:$,notifyPropertyChange:ee,objectAt:ae,on:se,processAllNamespaces:te,processNamespace:re,removeArrayObserver:oe,removeListener:ne,removeNamespace:ie,removeObserver:le,replace:be,replaceInNativeArray:pe,revalidateObservers:de,sendEvent:me,set:t,setClassicDecorator:ue,setNamespaceSearchDisabled:ge,setProperties:ye,setUnprocessedMixins:_e,tagForObject:Oe,tagForProperty:Se,tracked:fe,trySet:Ce},Symbol.toStringTag,{value:"Module"})),_s=Object.freeze(Object.defineProperty({__proto__:null,Input:Pe,Textarea:he,capabilities:ve,default:je,getComponentTemplate:Ee,setComponentManager:Me,setComponentTemplate:De},Symbol.toStringTag,{value:"Module"})),Os=Object.freeze(Object.defineProperty({__proto__:null,EventTarget:Ne,Promise:Ve,all:Ae,allSettled:we,asap:Te,async:Ie,cast:xe,configure:Re,default:ke,defer:Fe,denodeify:Le,filter:ze,hash:Ge,hashSettled:Ue,map:Be,off:We,on:Ye,race:He,reject:Je,resolve:Ke,rethrow:Xe},Symbol.toStringTag,{value:"Module"})),Ss=Object.freeze(Object.defineProperty({__proto__:null,cacheFor:z,guidFor:qe},Symbol.toStringTag,{value:"Module"})),fs=Object.freeze(Object.defineProperty({__proto__:null,default:Qe},Symbol.toStringTag,{value:"Module"})),Cs=Object.freeze(Object.defineProperty({__proto__:null,ENV:Ze,context:$e,getENV:ea,getLookup:aa,global:sa,setLookup:ta},Symbol.toStringTag,{value:"Module"})),Ps=Object.freeze(Object.defineProperty({__proto__:null,Meta:ra,UNDEFINED:oa,counters:na,meta:ia,peekMeta:la,setMeta:ba},Symbol.toStringTag,{value:"Module"})),hs=Object.freeze(Object.defineProperty({__proto__:null,ActionHandler:pa,Comparable:da,ContainerProxyMixin:ma,MutableEnumerable:ua,RSVP:ga,RegistryProxyMixin:ya,TargetActionSupport:_a,_ProxyMixin:Oa,_contentFor:Sa,onerrorDefault:fa},Symbol.toStringTag,{value:"Module"})),vs=Object.freeze(Object.defineProperty({__proto__:null,Cache:Ca,GUID_KEY:Pa,ROOT:ha,canInvoke:va,checkHasSuper:ja,dictionary:Ea,enumerableSymbol:Ma,generateGuid:Da,getDebugName:Na,getName:Va,guidFor:qe,intern:Aa,isInternalSymbol:wa,isObject:Ta,isProxy:Ia,lookupDescriptor:xa,observerListenerMetaFor:Ra,setListeners:ka,setName:Fa,setObservers:La,setProxy:za,setWithMandatorySetter:Ga,setupMandatorySetter:Ua,symbol:Ba,teardownMandatorySetter:Wa,toString:Ya,uuid:Ha,wrap:Ja},Symbol.toStringTag,{value:"Module"})),js=Object.freeze(Object.defineProperty({__proto__:null,ActionSupport:Ka,ComponentLookup:Xa,CoreView:qa,EventDispatcher:Qa,MUTABLE_CELL:Za,ViewStates:$a,addChildView:es,clearElementView:as,clearViewElement:ss,constructStyleDeprecationMessage:ts,getChildViews:rs,getElementView:os,getRootViews:ns,getViewBoundingClientRect:is,getViewBounds:ls,getViewClientRects:bs,getViewElement:cs,getViewId:ps,isSimpleClick:ds,setElementView:ms,setViewElement:us},Symbol.toStringTag,{value:"Module"}));export{fs as ArrayMutable,_s as Component,Cs as InternalsEnvironment,Ps as InternalsMeta,ys as InternalsMetal,hs as InternalsRuntime,vs as InternalsUtils,js as InternalsViews,Ss as ObjectInternals,Os as RSVP}; +import{c as e,g as a,a as s,s as t,A as r,C as o,b as n,D as i,L as l,N as b,d as c,P as p,e as d,S as m,T as u,_ as g,f as y,h as _,i as O,j as S,k as f,l as C,m as P,n as h,o as v,p as j,q as E,r as M,t as D,u as N,v as V,w as A,x as w,y as T,z as I,B as x,E as R,F as k,G as F,H as L,I as z,J as G,K as U,M as B,O as W,Q as Y,R as H,U as J,V as K,W as X,X as q,Y as Q,Z,$,a0 as ee,a1 as ae,a2 as se,a3 as te,a4 as re,a5 as oe,a6 as ne,a7 as ie,a8 as le,a9 as be,aa as pe,ab as de,ac as me,ad as ue,ae as ge,af as ye,ag as _e,ah as Oe,ai as Se,aj as fe,ak as Ce,al as Pe,am as he,an as ve,ao as je,ap as Ee,aq as Me,ar as De,as as Ne,at as Ve,au as Ae,av as we,aw as Te,ax as Ie,ay as xe,az as Re,aA as ke,aB as Fe,aC as Le,aD as ze,aE as Ge,aF as Ue,aG as Be,aH as We,aI as Ye,aJ as He,aK as Je,aL as Ke,aM as Xe,aN as qe,aO as Qe,aP as Ze,aQ as $e,aR as ea,aS as aa,aT as sa,aU as ta,aV as ra,aW as oa,aX as na,aY as ia,aZ as la,a_ as ba,a$ as pa,b0 as da,b1 as ma,b2 as ua,b3 as ga,b4 as ya,b5 as _a,b6 as Oa,b7 as Sa,b8 as fa,b9 as Ca,ba as Pa,bb as ha,bc as va,bd as ja,be as Ea,bf as Ma,bg as Da,bh as Na,bi as Va,bj as Aa,bk as wa,bl as Ta,bm as Ia,bn as xa,bo as Ra,bp as ka,bq as Fa,br as La,bs as za,bt as Ga,bu as Ua,bv as Ba,bw as Wa,bx as Ya,by as Ha,bz as Ja,bA as Ka,bB as Xa,bC as qa,bD as Qa,bE as Za,bF as $a,bG as es,bH as as,bI as ss,bJ as ts,bK as rs,bL as os,bM as ns,bN as is,bO as ls,bP as bs,bQ as cs,bR as ps,bS as ds,bT as ms,bU as us}from"./main-CGySSjv6.js";export{bV as Application,bW as ApplicationNamespace,bX as Array,bY as ArrayProxy,bZ as Controller,b_ as Debug,b$ as EmberDestroyable,c0 as EmberObject,c1 as EnumerableMutable,cc as GlimmerComponent,cd as GlimmerManager,ce as GlimmerReference,cf as GlimmerRuntime,cg as GlimmerUtil,ch as GlimmerValidator,c2 as Instrumentation,c0 as Object,c3 as ObjectCore,c4 as ObjectEvented,c5 as ObjectObservable,c6 as ObjectPromiseProxyMixin,c7 as ObjectProxy,ca as Owner,c8 as Runloop,c9 as Service,cb as VERSION}from"./main-CGySSjv6.js";const gs=new WeakMap,ys=Object.freeze(Object.defineProperty({__proto__:null,ASYNC_OBSERVERS:r,ComputedDescriptor:o,ComputedProperty:n,DEBUG_INJECTION_FUNCTIONS:i,Libraries:l,NAMESPACES:b,NAMESPACES_BY_ID:c,PROPERTY_DID_CHANGE:p,PROXY_CONTENT:d,SYNC_OBSERVERS:m,TrackedDescriptor:u,_getPath:g,_getProp:y,_setProp:_,activateObserver:O,addArrayObserver:S,addListener:f,addNamespace:C,addObserver:P,alias:h,arrayContentDidChange:v,arrayContentWillChange:j,autoComputed:E,beginPropertyChanges:M,cached:(...s)=>{const[t,r,o]=s,n=new WeakMap,i=o.get;o.get=function(){return n.has(this)||n.set(this,e(i.bind(this))),a(n.get(this))}},changeProperties:D,computed:N,createCache:e,defineDecorator:V,defineProperty:A,defineValue:w,deprecateProperty:function(e,a,r){Object.defineProperty(e,a,{configurable:!0,enumerable:!1,set(e){t(this,r,e)},get(){return s(this,r)}})},descriptorForDecorator:T,descriptorForProperty:I,eachProxyArrayDidChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayDidChange(e,a,s,t)},eachProxyArrayWillChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayWillChange(e,a,s,t)},endPropertyChanges:x,expandProperties:R,findNamespace:k,findNamespaces:F,flushAsyncObservers:L,get:s,getCachedValueFor:z,getProperties:G,getValue:a,hasListeners:U,hasUnknownProperty:B,inject:W,isClassicDecorator:Y,isComputed:H,isConst:J,isElementDescriptor:K,isNamespaceSearchDisabled:X,libraries:q,makeComputedDecorator:Q,markObjectAsDirty:Z,nativeDescDecorator:$,notifyPropertyChange:ee,objectAt:ae,on:se,processAllNamespaces:te,processNamespace:re,removeArrayObserver:oe,removeListener:ne,removeNamespace:ie,removeObserver:le,replace:be,replaceInNativeArray:pe,revalidateObservers:de,sendEvent:me,set:t,setClassicDecorator:ue,setNamespaceSearchDisabled:ge,setProperties:ye,setUnprocessedMixins:_e,tagForObject:Oe,tagForProperty:Se,tracked:fe,trySet:Ce},Symbol.toStringTag,{value:"Module"})),_s=Object.freeze(Object.defineProperty({__proto__:null,Input:Pe,Textarea:he,capabilities:ve,default:je,getComponentTemplate:Ee,setComponentManager:Me,setComponentTemplate:De},Symbol.toStringTag,{value:"Module"})),Os=Object.freeze(Object.defineProperty({__proto__:null,EventTarget:Ne,Promise:Ve,all:Ae,allSettled:we,asap:Te,async:Ie,cast:xe,configure:Re,default:ke,defer:Fe,denodeify:Le,filter:ze,hash:Ge,hashSettled:Ue,map:Be,off:We,on:Ye,race:He,reject:Je,resolve:Ke,rethrow:Xe},Symbol.toStringTag,{value:"Module"})),Ss=Object.freeze(Object.defineProperty({__proto__:null,cacheFor:z,guidFor:qe},Symbol.toStringTag,{value:"Module"})),fs=Object.freeze(Object.defineProperty({__proto__:null,default:Qe},Symbol.toStringTag,{value:"Module"})),Cs=Object.freeze(Object.defineProperty({__proto__:null,ENV:Ze,context:$e,getENV:ea,getLookup:aa,global:sa,setLookup:ta},Symbol.toStringTag,{value:"Module"})),Ps=Object.freeze(Object.defineProperty({__proto__:null,Meta:ra,UNDEFINED:oa,counters:na,meta:ia,peekMeta:la,setMeta:ba},Symbol.toStringTag,{value:"Module"})),hs=Object.freeze(Object.defineProperty({__proto__:null,ActionHandler:pa,Comparable:da,ContainerProxyMixin:ma,MutableEnumerable:ua,RSVP:ga,RegistryProxyMixin:ya,TargetActionSupport:_a,_ProxyMixin:Oa,_contentFor:Sa,onerrorDefault:fa},Symbol.toStringTag,{value:"Module"})),vs=Object.freeze(Object.defineProperty({__proto__:null,Cache:Ca,GUID_KEY:Pa,ROOT:ha,canInvoke:va,checkHasSuper:ja,dictionary:Ea,enumerableSymbol:Ma,generateGuid:Da,getDebugName:Na,getName:Va,guidFor:qe,intern:Aa,isInternalSymbol:wa,isObject:Ta,isProxy:Ia,lookupDescriptor:xa,observerListenerMetaFor:Ra,setListeners:ka,setName:Fa,setObservers:La,setProxy:za,setWithMandatorySetter:Ga,setupMandatorySetter:Ua,symbol:Ba,teardownMandatorySetter:Wa,toString:Ya,uuid:Ha,wrap:Ja},Symbol.toStringTag,{value:"Module"})),js=Object.freeze(Object.defineProperty({__proto__:null,ActionSupport:Ka,ComponentLookup:Xa,CoreView:qa,EventDispatcher:Qa,MUTABLE_CELL:Za,ViewStates:$a,addChildView:es,clearElementView:as,clearViewElement:ss,constructStyleDeprecationMessage:ts,getChildViews:rs,getElementView:os,getRootViews:ns,getViewBoundingClientRect:is,getViewBounds:ls,getViewClientRects:bs,getViewElement:cs,getViewId:ps,isSimpleClick:ds,setElementView:ms,setViewElement:us},Symbol.toStringTag,{value:"Module"}));export{fs as ArrayMutable,_s as Component,Cs as InternalsEnvironment,Ps as InternalsMeta,ys as InternalsMetal,hs as InternalsRuntime,vs as InternalsUtils,js as InternalsViews,Ss as ObjectInternals,Os as RSVP}; diff --git a/release/assets/negentropy-Baf3_xbt.js b/release/assets/negentropy-CkK5_v5U.js similarity index 99% rename from release/assets/negentropy-Baf3_xbt.js rename to release/assets/negentropy-CkK5_v5U.js index 2c8e08c..a17e9bf 100644 --- a/release/assets/negentropy-Baf3_xbt.js +++ b/release/assets/negentropy-CkK5_v5U.js @@ -1,2 +1,2 @@ -import{ci as t,cj as e,ck as i,cl as r,cm as n,cn as s,co as o,cp as a}from"./main-AsE4IKjj.js";var h=Array.isArray;function u(){for(var r,n=[],s=0;s0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function c(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function d(...t){for(let e=0;e>>e}function p(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),l(t),t}class m{}function w(t){const e=e=>t().update(p(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function b(t,e,i){return t&e^~t&i}function y(t,e,i){return t&e^t&i^e&i}class E extends m{constructor(t,e,i,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=f(this.buffer)}update(t){c(this),l(t=p(t));const{view:e,buffer:i,blockLen:r}=this,n=t.length;for(let s=0;sr-s&&(this.process(i,0),s=0);for(let l=s;l>n&s),a=Number(i&s),h=r?4:0,u=r?0:4;t.setUint32(e+h,o,r),t.setUint32(e+u,a,r)}(i,r-8,BigInt(8*this.length),n),this.process(i,0);const o=f(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=a/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l>>3,r=g(e,17)^g(e,19)^e>>>10;A[l]=r+A[l-7]+i+A[l-16]|0}let{A:i,B:r,C:n,D:s,E:o,F:a,G:h,H:u}=this;for(let l=0;l<64;l++){const t=u+(g(o,6)^g(o,11)^g(o,25))+b(o,a,h)+x[l]+A[l]|0,e=(g(i,2)^g(i,13)^g(i,22))+y(i,r,n)|0;u=h,h=a,a=o,o=s+t|0,s=n,n=r,r=i,i=t+e|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,h=h+this.G|0,u=u+this.H|0,this.set(i,r,n,s,o,a,h,u)}roundClean(){d(A)}destroy(){this.set(0,0,0,0,0,0,0,0),d(this.buffer)}}const U=w(()=>new L),I=32;class B{_raw;length;constructor(t){this._raw=new Uint8Array(t||512),this.length=t?t.length:0}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof B&&(t=t.unwrap()),"number"!=typeof t.length)throw Error("bad length");const e=t.length+this.length;if(this.capacity>>=7;e.reverse();for(let i=0;iU.create().update(t).digest()}setToZero(){this.buf=new Uint8Array(I)}add(t){let e=0,i=0,r=new DataView(this.buf.buffer),n=new DataView(t.buffer);for(let s=0;s<8;s++){let t=4*s,o=r.getUint32(t,!0);o+=e,o+=n.getUint32(t,!0),o>4294967295&&(i=1),r.setUint32(t,4294967295&o,!0),e=i,i=0}}negate(){let t=new DataView(this.buf.buffer);for(let i=0;i<8;i++){let e=4*i;t.setUint32(e,~t.getUint32(e,!0))}let e=new Uint8Array(I);e[0]=1,this.add(e)}async getFingerprint(t){let e=new B;return e.extend(this.buf),e.extend(T(t)),(await this.sha256(e.unwrap())).subarray(0,16)}}class k{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");if((e=M(e)).byteLength!==I)throw Error("bad id size for added item");this.items.push({timestamp:t,id:e})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(G);for(let t=1;t=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,i){this._checkSealed(),this._checkBounds(t,e);for(let r=t;rG(t,i)<0)}async fingerprint(t,e){let i=new S;return i.setToZero(),this.iterate(t,e,t=>(i.add(t.id),!0)),await i.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,i,r){let n=i-e;for(;n>0;){let i=e,s=Math.floor(n/2);i+=s,r(t[i])?(e=++i,n-=s+1):n=s}return e}}class v{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;isInitiator;wantUint8ArrayOutput;constructor(t,e=0){if(0!==e&&e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}async initiate(){if(this.isInitiator)throw Error("already initiated");this.isInitiator=!0;let t=new B;return t.extend([97]),await this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),this._renderOutput(t)}setInitiator(){this.isInitiator=!0}async reconcile(t){let e=[],i=[],r=new B(M(t));this.lastTimestampIn=this.lastTimestampOut=0;let n=new B;n.extend([97]);let s=N(r,1)[0];if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(97!==s){if(this.isInitiator)throw Error("unsupported negentropy protocol version requested: "+(s-96));return[this._renderOutput(n),e,i]}let o=this.storage.size(),a=this._bound(0),h=0,u=!1;for(;0!==r.length;){let t=new B,s=()=>{u&&(u=!1,t.extend(this.encodeBound(a)),t.extend(T(0)))},l=this.decodeBound(r),c=O(r),d=h,f=this.storage.findLowerBound(h,o,l);if(0===c)u=!0;else if(1===c)0!==F(N(r,16),await this.storage.fingerprint(d,f))?(s(),await this.splitRange(d,f,l,t)):u=!0;else{if(2!==c)throw Error("unexpected mode");{let o=O(r),a={};for(let t=0;t{let i=t.id;return a[i]?delete a[i]:this.isInitiator&&e.push(this.wantUint8ArrayOutput?i:z(i)),!0});for(let t of Object.values(a))i.push(this.wantUint8ArrayOutput?t:z(t))}else{s();let e=new B,i=0,r=l;this.storage.iterate(d,f,(t,s)=>this.exceededFrameSizeLimit(n.length+e.length)?(r=t,f=s,!1):(e.extend(t.id),i++,!0)),t.extend(this.encodeBound(r)),t.extend(T(2)),t.extend(T(i)),t.extend(e),n.extend(t),t=new B}}}if(this.exceededFrameSizeLimit(n.length+t.length)){let t=await this.storage.fingerprint(f,o);n.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),n.extend(T(1)),n.extend(t);break}n.extend(t),h=f,a=l}return[1===n.length&&this.isInitiator?null:this._renderOutput(n),e,i]}async splitRange(t,e,i,r){let n=e-t;if(n<32)r.extend(this.encodeBound(i)),r.extend(T(2)),r.extend(T(n)),this.storage.iterate(t,e,t=>(r.extend(t.id),!0));else{let s=Math.floor(n/16),o=n%16,a=t;for(let t=0;t<16;t++){let n,h=s+(t(r===a-1?t=i:e=i,!0)),n=this.getMinimalBound(t,e)}r.extend(this.encodeBound(n)),r.extend(T(1)),r.extend(u)}}}_renderOutput(t){let e=t.unwrap();return this.wantUint8ArrayOutput?e:z(e)}exceededFrameSizeLimit(t){return this.frameSizeLimit&&t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=O(t);return e=0===e?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),i=O(t);if(i>I)throw Error("bound key too long");return{timestamp:e,id:N(t,i)}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,T(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,T(t+1)}encodeBound(t){let e=new B;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(T(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let i=0,r=e.id,n=t.id;for(let t=0;t>>4&15]+t[15&e]}function z(t){let e="";for(let i=0,r=t.length;ie[i])return 1}return t.byteLength>e.byteLength?1:t.byteLength(C("Sending initial message",c,n,f),["NEG-OPEN",c,n,f]),()=>(C("Closing sync",c),["NEG-CLOSE",c]),t=>("NEG-MSG"===t[0]||"NEG-ERR"===t[0])&&t[1]===c).pipe(s(t=>{if("NEG-ERR"===t[0])throw new Error(t[2]);return t[2]}),o());if(l?.signal?.aborted)return!1;const m=new e(t=>{if(l?.signal?.aborted)return t.next("abort"),void t.complete();const e=()=>{t.next("abort"),t.complete()};return l?.signal?.addEventListener("abort",e),()=>l?.signal?.removeEventListener("abort",e)}),w=p.subscribe({next:t=>C(t),error:()=>{}});try{for(;g&&!0!==l?.signal?.aborted;)try{const t=await a(u(p.pipe(s(t=>({type:"message",data:t}))),m.pipe(s(()=>({type:"abort"})))));if("abort"===t.type||l?.signal?.aborted)return w.unsubscribe(),!1;const[e,i,r]=await d.reconcile(t.data);await h(i,r),g=e}catch(b){if(l?.signal?.aborted)return w.unsubscribe(),!1;throw b}}catch(b){throw w.unsubscribe(),b}finally{w.unsubscribe()}return!0}export{D as buildStorageFromFilter,X as buildStorageVector,H as negentropySync}; diff --git a/release/index.html b/release/index.html index 128007a..7985d34 100644 --- a/release/index.html +++ b/release/index.html @@ -39,7 +39,7 @@ - +