diff --git a/assets/index.c2bf15d9.js b/assets/index.1caf8556.js similarity index 89% rename from assets/index.c2bf15d9.js rename to assets/index.1caf8556.js index e6f784c..7fe91b6 100644 --- a/assets/index.c2bf15d9.js +++ b/assets/index.1caf8556.js @@ -1,4 +1,4 @@ -var Gl=Object.defineProperty;var ql=(e,t,r)=>t in e?Gl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ye=(e,t,r)=>(ql(e,typeof t!="symbol"?t+"":t,r),r),ga=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var Jt=(e,t,r)=>(ga(e,t,"read from private field"),r?r.call(e):t.get(e)),_r=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},wn=(e,t,r,n)=>(ga(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vr=(e,t,r)=>(ga(e,t,"access private method"),r);var cc=Xl((exports,module)=>{(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerpolicy&&(a.referrerPolicy=o.referrerpolicy),o.crossorigin==="use-credentials"?a.credentials="include":o.crossorigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(o){if(o.ep)return;o.ep=!0;const a=r(o);fetch(o.href,a)}})();var commonjsGlobal$2=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){var t=e.default;if(typeof t=="function"){var r=function(){return t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}),r}var buffer={},base64Js={};base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code$4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i$1=0,len=code$4.length;i$10)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function byteLength(e){var t=getLens(e),r=t[0],n=t[1];return(r+n)*3/4-n}function _byteLength(e,t,r){return(t+r)*3/4-r}function toByteArray(e){var t,r=getLens(e),n=r[0],o=r[1],a=new Arr(_byteLength(e,n,o)),l=0,c=o>0?n-4:n,u;for(u=0;u>16&255,a[l++]=t>>8&255,a[l++]=t&255;return o===2&&(t=revLookup[e.charCodeAt(u)]<<2|revLookup[e.charCodeAt(u+1)]>>4,a[l++]=t&255),o===1&&(t=revLookup[e.charCodeAt(u)]<<10|revLookup[e.charCodeAt(u+1)]<<4|revLookup[e.charCodeAt(u+2)]>>2,a[l++]=t>>8&255,a[l++]=t&255),a}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,r){for(var n,o=[],a=t;ac?c:l+a));return n===1?(t=e[r-1],o.push(lookup[t>>2]+lookup[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],o.push(lookup[t>>10]+lookup[t>>4&63]+lookup[t<<2&63]+"=")),o.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ieee754.read=function(e,t,r,n,o){var a,l,c=o*8-n-1,u=(1<>1,b=-7,x=r?o-1:0,E=r?-1:1,I=e[t+x];for(x+=E,a=I&(1<<-b)-1,I>>=-b,b+=c;b>0;a=a*256+e[t+x],x+=E,b-=8);for(l=a&(1<<-b)-1,a>>=-b,b+=n;b>0;l=l*256+e[t+x],x+=E,b-=8);if(a===0)a=1-_;else{if(a===u)return l?NaN:(I?-1:1)*(1/0);l=l+Math.pow(2,n),a=a-_}return(I?-1:1)*l*Math.pow(2,a-n)};ieee754.write=function(e,t,r,n,o,a){var l,c,u,_=a*8-o-1,b=(1<<_)-1,x=b>>1,E=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,I=n?0:a-1,k=n?1:-1,T=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,l=b):(l=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-l))<1&&(l--,u*=2),l+x>=1?t+=E/u:t+=E*Math.pow(2,1-x),t*u>=2&&(l++,u/=2),l+x>=b?(c=0,l=b):l+x>=1?(c=(t*u-1)*Math.pow(2,o),l=l+x):(c=t*Math.pow(2,x-1)*Math.pow(2,o),l=0));o>=8;e[r+I]=c&255,I+=k,c/=256,o-=8);for(l=l<0;e[r+I]=l&255,I+=k,l/=256,_-=8);e[r+I-k]|=T*128};/*! +var Gl=Object.defineProperty;var ql=(e,t,r)=>t in e?Gl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ke=(e,t,r)=>(ql(e,typeof t!="symbol"?t+"":t,r),r),ga=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var Jt=(e,t,r)=>(ga(e,t,"read from private field"),r?r.call(e):t.get(e)),_r=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},wn=(e,t,r,n)=>(ga(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vr=(e,t,r)=>(ga(e,t,"access private method"),r);var cc=Xl((exports,module)=>{(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerpolicy&&(a.referrerPolicy=o.referrerpolicy),o.crossorigin==="use-credentials"?a.credentials="include":o.crossorigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(o){if(o.ep)return;o.ep=!0;const a=r(o);fetch(o.href,a)}})();var commonjsGlobal$2=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){var t=e.default;if(typeof t=="function"){var r=function(){return t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}),r}var buffer={},base64Js={};base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code$4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i$1=0,len=code$4.length;i$10)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function byteLength(e){var t=getLens(e),r=t[0],n=t[1];return(r+n)*3/4-n}function _byteLength(e,t,r){return(t+r)*3/4-r}function toByteArray(e){var t,r=getLens(e),n=r[0],o=r[1],a=new Arr(_byteLength(e,n,o)),l=0,c=o>0?n-4:n,u;for(u=0;u>16&255,a[l++]=t>>8&255,a[l++]=t&255;return o===2&&(t=revLookup[e.charCodeAt(u)]<<2|revLookup[e.charCodeAt(u+1)]>>4,a[l++]=t&255),o===1&&(t=revLookup[e.charCodeAt(u)]<<10|revLookup[e.charCodeAt(u+1)]<<4|revLookup[e.charCodeAt(u+2)]>>2,a[l++]=t>>8&255,a[l++]=t&255),a}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,r){for(var n,o=[],a=t;ac?c:l+a));return n===1?(t=e[r-1],o.push(lookup[t>>2]+lookup[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],o.push(lookup[t>>10]+lookup[t>>4&63]+lookup[t<<2&63]+"=")),o.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ieee754.read=function(e,t,r,n,o){var a,l,c=o*8-n-1,u=(1<>1,b=-7,x=r?o-1:0,E=r?-1:1,I=e[t+x];for(x+=E,a=I&(1<<-b)-1,I>>=-b,b+=c;b>0;a=a*256+e[t+x],x+=E,b-=8);for(l=a&(1<<-b)-1,a>>=-b,b+=n;b>0;l=l*256+e[t+x],x+=E,b-=8);if(a===0)a=1-_;else{if(a===u)return l?NaN:(I?-1:1)*(1/0);l=l+Math.pow(2,n),a=a-_}return(I?-1:1)*l*Math.pow(2,a-n)};ieee754.write=function(e,t,r,n,o,a){var l,c,u,_=a*8-o-1,b=(1<<_)-1,x=b>>1,E=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,I=n?0:a-1,k=n?1:-1,T=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,l=b):(l=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-l))<1&&(l--,u*=2),l+x>=1?t+=E/u:t+=E*Math.pow(2,1-x),t*u>=2&&(l++,u/=2),l+x>=b?(c=0,l=b):l+x>=1?(c=(t*u-1)*Math.pow(2,o),l=l+x):(c=t*Math.pow(2,x-1)*Math.pow(2,o),l=0));o>=8;e[r+I]=c&255,I+=k,c/=256,o-=8);for(l=l<0;e[r+I]=l&255,I+=k,l/=256,_-=8);e[r+I-k]|=T*128};/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh @@ -29,7 +29,7 @@ Arguments: `+Array.prototype.slice.call(n).join("")+` hooks.version="2.29.4";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min;hooks.max=max;hooks.now=now;hooks.utc=createUTC;hooks.unix=createUnix;hooks.months=listMonths;hooks.isDate=isDate$2;hooks.locale=getSetGlobalLocale;hooks.invalid=createInvalid;hooks.duration=createDuration;hooks.isMoment=isMoment;hooks.weekdays=listWeekdays;hooks.parseZone=createInZone;hooks.localeData=getLocale;hooks.isDuration=isDuration;hooks.monthsShort=listMonthsShort;hooks.weekdaysMin=listWeekdaysMin;hooks.defineLocale=defineLocale;hooks.updateLocale=updateLocale;hooks.locales=listLocales;hooks.weekdaysShort=listWeekdaysShort;hooks.normalizeUnits=normalizeUnits;hooks.relativeTimeRounding=getSetRelativeTimeRounding;hooks.relativeTimeThreshold=getSetRelativeTimeThreshold;hooks.calendarFormat=getCalendarFormat;hooks.prototype=proto;hooks.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"};var leafletSrc={exports:{}};/* @preserve * Leaflet 1.9.2, a JS library for interactive maps. https://leafletjs.com * (c) 2010-2022 Vladimir Agafonkin, (c) 2010-2011 CloudMade - */(function(e,t){(function(r,n){n(t)})(commonjsGlobal$2,function(r){var n="1.9.2";function o(g){var S,B,_e,Me;for(B=1,_e=arguments.length;B<_e;B++){Me=arguments[B];for(S in Me)g[S]=Me[S]}return g}var a=Object.create||function(){function g(){}return function(S){return g.prototype=S,new g}}();function l(g,S){var B=Array.prototype.slice;if(g.bind)return g.bind.apply(g,B.call(arguments,1));var _e=B.call(arguments,2);return function(){return g.apply(S,_e.length?_e.concat(B.call(arguments)):arguments)}}var c=0;function u(g){return"_leaflet_id"in g||(g._leaflet_id=++c),g._leaflet_id}function _(g,S,B){var _e,Me,Ke,lt;return lt=function(){_e=!1,Me&&(Ke.apply(B,Me),Me=!1)},Ke=function(){_e?Me=arguments:(g.apply(B,arguments),setTimeout(lt,S),_e=!0)},Ke}function b(g,S,B){var _e=S[1],Me=S[0],Ke=_e-Me;return g===_e&&B?g:((g-Me)%Ke+Ke)%Ke+Me}function x(){return!1}function E(g,S){if(S===!1)return g;var B=Math.pow(10,S===void 0?6:S);return Math.round(g*B)/B}function I(g){return g.trim?g.trim():g.replace(/^\s+|\s+$/g,"")}function k(g){return I(g).split(/\s+/)}function T(g,S){Object.prototype.hasOwnProperty.call(g,"options")||(g.options=g.options?a(g.options):{});for(var B in S)g.options[B]=S[B];return g.options}function O(g,S,B){var _e=[];for(var Me in g)_e.push(encodeURIComponent(B?Me.toUpperCase():Me)+"="+encodeURIComponent(g[Me]));return(!S||S.indexOf("?")===-1?"?":"&")+_e.join("&")}var $=/\{ *([\w_ -]+) *\}/g;function D(g,S){return g.replace($,function(B,_e){var Me=S[_e];if(Me===void 0)throw new Error("No value provided for variable "+B);return typeof Me=="function"&&(Me=Me(S)),Me})}var N=Array.isArray||function(g){return Object.prototype.toString.call(g)==="[object Array]"};function H(g,S){for(var B=0;B"u"||!L||!L.Mixin)){g=N(g)?g:[g];for(var S=0;S0?Math.floor(g):Math.ceil(g)};se.prototype={clone:function(){return new se(this.x,this.y)},add:function(g){return this.clone()._add(Pe(g))},_add:function(g){return this.x+=g.x,this.y+=g.y,this},subtract:function(g){return this.clone()._subtract(Pe(g))},_subtract:function(g){return this.x-=g.x,this.y-=g.y,this},divideBy:function(g){return this.clone()._divideBy(g)},_divideBy:function(g){return this.x/=g,this.y/=g,this},multiplyBy:function(g){return this.clone()._multiplyBy(g)},_multiplyBy:function(g){return this.x*=g,this.y*=g,this},scaleBy:function(g){return new se(this.x*g.x,this.y*g.y)},unscaleBy:function(g){return new se(this.x/g.x,this.y/g.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=Se(this.x),this.y=Se(this.y),this},distanceTo:function(g){g=Pe(g);var S=g.x-this.x,B=g.y-this.y;return Math.sqrt(S*S+B*B)},equals:function(g){return g=Pe(g),g.x===this.x&&g.y===this.y},contains:function(g){return g=Pe(g),Math.abs(g.x)<=Math.abs(this.x)&&Math.abs(g.y)<=Math.abs(this.y)},toString:function(){return"Point("+E(this.x)+", "+E(this.y)+")"}};function Pe(g,S,B){return g instanceof se?g:N(g)?new se(g[0],g[1]):g==null?g:typeof g=="object"&&"x"in g&&"y"in g?new se(g.x,g.y):new se(g,S,B)}function Ue(g,S){if(!!g)for(var B=S?[g,S]:g,_e=0,Me=B.length;_e=this.min.x&&B.x<=this.max.x&&S.y>=this.min.y&&B.y<=this.max.y},intersects:function(g){g=Be(g);var S=this.min,B=this.max,_e=g.min,Me=g.max,Ke=Me.x>=S.x&&_e.x<=B.x,lt=Me.y>=S.y&&_e.y<=B.y;return Ke&<},overlaps:function(g){g=Be(g);var S=this.min,B=this.max,_e=g.min,Me=g.max,Ke=Me.x>S.x&&_e.xS.y&&_e.y=S.lat&&Me.lat<=B.lat&&_e.lng>=S.lng&&Me.lng<=B.lng},intersects:function(g){g=ye(g);var S=this._southWest,B=this._northEast,_e=g.getSouthWest(),Me=g.getNorthEast(),Ke=Me.lat>=S.lat&&_e.lat<=B.lat,lt=Me.lng>=S.lng&&_e.lng<=B.lng;return Ke&<},overlaps:function(g){g=ye(g);var S=this._southWest,B=this._northEast,_e=g.getSouthWest(),Me=g.getNorthEast(),Ke=Me.lat>S.lat&&_e.latS.lng&&_e.lng1,yo=function(){var g=!1;try{var S=Object.defineProperty({},"passive",{get:function(){g=!0}});window.addEventListener("testPassiveEventSupport",x,S),window.removeEventListener("testPassiveEventSupport",x,S)}catch{}return g}(),vo=function(){return!!document.createElement("canvas").getContext}(),xi=!!(document.createElementNS&&ke("svg").createSVGRect),_o=!!xi&&function(){var g=document.createElement("div");return g.innerHTML="",(g.firstChild&&g.firstChild.namespaceURI)==="http://www.w3.org/2000/svg"}(),bo=!xi&&function(){try{var g=document.createElement("div");g.innerHTML='';var S=g.firstChild;return S.style.behavior="url(#default#VML)",S&&typeof S.adj=="object"}catch{return!1}}(),ns=navigator.platform.indexOf("Mac")===0,is=navigator.platform.indexOf("Linux")===0;function Tr(g){return navigator.userAgent.toLowerCase().indexOf(g)>=0}var $t={ie:Xe,ielt9:Je,edge:rt,webkit:qe,android:Ve,android23:Ae,androidStock:Ge,opera:Ze,chrome:$e,gecko:me,safari:Ee,phantom:je,opera12:nt,win:ot,ie3d:dt,webkit3d:Ct,gecko3d:St,any3d:kt,mobile:Et,mobileWebkit:Lt,mobileWebkit3d:tr,msPointer:Xt,pointer:wr,touch:dr,touchNative:nr,mobileOpera:pr,mobileGecko:po,retina:go,passiveEvents:yo,canvas:vo,svg:xi,vml:bo,inlineSvg:_o,mac:ns,linux:is},ss=$t.msPointer?"MSPointerDown":"pointerdown",En=$t.msPointer?"MSPointerMove":"pointermove",os=$t.msPointer?"MSPointerUp":"pointerup",Ei=$t.msPointer?"MSPointerCancel":"pointercancel",Si={touchstart:ss,touchmove:En,touchend:os,touchcancel:Ei},ls={touchstart:So,touchmove:Sn,touchend:Sn,touchcancel:Sn},hn={},Ci=!1;function wo(g,S,B){return S==="touchstart"&&Eo(),ls[S]?(B=ls[S].bind(this,B),g.addEventListener(Si[S],B,!1),B):(console.warn("wrong event specified:",S),L.Util.falseFn)}function cs(g,S,B){if(!Si[S]){console.warn("wrong event specified:",S);return}g.removeEventListener(Si[S],B,!1)}function xo(g){hn[g.pointerId]=g}function us(g){hn[g.pointerId]&&(hn[g.pointerId]=g)}function hs(g){delete hn[g.pointerId]}function Eo(){Ci||(document.addEventListener(ss,xo,!0),document.addEventListener(En,us,!0),document.addEventListener(os,hs,!0),document.addEventListener(Ei,hs,!0),Ci=!0)}function Sn(g,S){if(S.pointerType!==(S.MSPOINTER_TYPE_MOUSE||"mouse")){S.touches=[];for(var B in hn)S.touches.push(hn[B]);S.changedTouches=[S],g(S)}}function So(g,S){S.MSPOINTER_TYPE_TOUCH&&S.pointerType===S.MSPOINTER_TYPE_TOUCH&&ur(S),Sn(g,S)}function Co(g){var S={},B,_e;for(_e in g)B=g[_e],S[_e]=B&&B.bind?B.bind(g):B;return g=S,S.type="dblclick",S.detail=2,S.isTrusted=!1,S._simulated=!0,S}var ko=200;function To(g,S){g.addEventListener("dblclick",S);var B=0,_e;function Me(Ke){if(Ke.detail!==1){_e=Ke.detail;return}if(!(Ke.pointerType==="mouse"||Ke.sourceCapabilities&&!Ke.sourceCapabilities.firesTouchEvents)){var lt=ds(Ke);if(!(lt.some(function(yt){return yt instanceof HTMLLabelElement&&yt.attributes.for})&&!lt.some(function(yt){return yt instanceof HTMLInputElement||yt instanceof HTMLSelectElement}))){var mt=Date.now();mt-B<=ko?(_e++,_e===2&&S(Co(Ke))):_e=1,B=mt}}}return g.addEventListener("click",Me),{dblclick:S,simDblclick:Me}}function Ao(g,S){g.removeEventListener("dblclick",S.dblclick),g.removeEventListener("click",S.simDblclick)}var ki=Cn(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),Yr=Cn(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),Kr=Yr==="webkitTransition"||Yr==="OTransition"?Yr+"End":"transitionend";function Gn(g){return typeof g=="string"?document.getElementById(g):g}function Ar(g,S){var B=g.style[S]||g.currentStyle&&g.currentStyle[S];if((!B||B==="auto")&&document.defaultView){var _e=document.defaultView.getComputedStyle(g,null);B=_e?_e[S]:null}return B==="auto"?null:B}function Wt(g,S,B){var _e=document.createElement(g);return _e.className=S||"",B&&B.appendChild(_e),_e}function ir(g){var S=g.parentNode;S&&S.removeChild(g)}function qn(g){for(;g.firstChild;)g.removeChild(g.firstChild)}function fn(g){var S=g.parentNode;S&&S.lastChild!==g&&S.appendChild(g)}function dn(g){var S=g.parentNode;S&&S.firstChild!==g&&S.insertBefore(g,S.firstChild)}function Xn(g,S){if(g.classList!==void 0)return g.classList.contains(S);var B=Zn(g);return B.length>0&&new RegExp("(^|\\s)"+S+"(\\s|$)").test(B)}function Nt(g,S){if(g.classList!==void 0)for(var B=k(S),_e=0,Me=B.length;_e0?2*window.devicePixelRatio:1;function Ni(g){return $t.edge?g.wheelDeltaY/2:g.deltaY&&g.deltaMode===0?-g.deltaY/Di:g.deltaY&&g.deltaMode===1?-g.deltaY*20:g.deltaY&&g.deltaMode===2?-g.deltaY*60:g.deltaX||g.deltaZ?0:g.wheelDelta?(g.wheelDeltaY||g.wheelDelta)/2:g.detail&&Math.abs(g.detail)<32765?-g.detail*20:g.detail?g.detail/-32765*60:0}function Bi(g,S){var B=S.relatedTarget;if(!B)return!0;try{for(;B&&B!==g;)B=B.parentNode}catch{return!1}return B!==g}var Io={__proto__:null,on:Ot,off:Qt,stopPropagation:Xr,disableScrollPropagation:ti,disableClickPropagation:Pr,preventDefault:ur,stop:Zr,getPropagationPath:ds,getMousePosition:ri,getWheelDelta:Ni,isExternalTarget:Bi,addListener:Ot,removeListener:Qt},ps=ge.extend({run:function(g,S,B,_e){this.stop(),this._el=g,this._inProgress=!0,this._duration=B||.25,this._easeOutPower=1/Math.max(_e||.5,.2),this._startPos=qr(g),this._offset=S.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){!this._inProgress||(this._step(!0),this._complete())},_animate:function(){this._animId=ee(this._animate,this),this._step()},_step:function(g){var S=+new Date-this._startTime,B=this._duration*1e3;Sthis.options.maxZoom)?this.setZoom(g):this},panInsideBounds:function(g,S){this._enforcingBounds=!0;var B=this.getCenter(),_e=this._limitCenter(B,this._zoom,ye(g));return B.equals(_e)||this.panTo(_e,S),this._enforcingBounds=!1,this},panInside:function(g,S){S=S||{};var B=Pe(S.paddingTopLeft||S.padding||[0,0]),_e=Pe(S.paddingBottomRight||S.padding||[0,0]),Me=this.project(this.getCenter()),Ke=this.project(g),lt=this.getPixelBounds(),mt=Be([lt.min.add(B),lt.max.subtract(_e)]),yt=mt.getSize();if(!mt.contains(Ke)){this._enforcingBounds=!0;var _t=Ke.subtract(mt.getCenter()),Tt=mt.extend(Ke).getSize().subtract(yt);Me.x+=_t.x<0?-Tt.x:Tt.x,Me.y+=_t.y<0?-Tt.y:Tt.y,this.panTo(this.unproject(Me),S),this._enforcingBounds=!1}return this},invalidateSize:function(g){if(!this._loaded)return this;g=o({animate:!1,pan:!0},g===!0?{animate:!0}:g);var S=this.getSize();this._sizeChanged=!0,this._lastCenter=null;var B=this.getSize(),_e=S.divideBy(2).round(),Me=B.divideBy(2).round(),Ke=_e.subtract(Me);return!Ke.x&&!Ke.y?this:(g.animate&&g.pan?this.panBy(Ke):(g.pan&&this._rawPanBy(Ke),this.fire("move"),g.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(l(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:S,newSize:B}))},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(g){if(g=this._locateOptions=o({timeout:1e4,watch:!1},g),!("geolocation"in navigator))return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var S=l(this._handleGeolocationResponse,this),B=l(this._handleGeolocationError,this);return g.watch?this._locationWatchId=navigator.geolocation.watchPosition(S,B,g):navigator.geolocation.getCurrentPosition(S,B,g),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(g){if(!!this._container._leaflet_id){var S=g.code,B=g.message||(S===1?"permission denied":S===2?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:S,message:"Geolocation error: "+B+"."})}},_handleGeolocationResponse:function(g){if(!!this._container._leaflet_id){var S=g.coords.latitude,B=g.coords.longitude,_e=new Ce(S,B),Me=_e.toBounds(g.coords.accuracy*2),Ke=this._locateOptions;if(Ke.setView){var lt=this.getBoundsZoom(Me);this.setView(_e,Ke.maxZoom?Math.min(lt,Ke.maxZoom):lt)}var mt={latlng:_e,bounds:Me,timestamp:g.timestamp};for(var yt in g.coords)typeof g.coords[yt]=="number"&&(mt[yt]=g.coords[yt]);this.fire("locationfound",mt)}},addHandler:function(g,S){if(!S)return this;var B=this[g]=new S(this);return this._handlers.push(B),this.options[g]&&B.enable(),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch{this._container._leaflet_id=void 0,this._containerId=void 0}this._locationWatchId!==void 0&&this.stopLocate(),this._stop(),ir(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(he(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload");var g;for(g in this._layers)this._layers[g].remove();for(g in this._panes)ir(this._panes[g]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(g,S){var B="leaflet-pane"+(g?" leaflet-"+g.replace("Pane","")+"-pane":""),_e=Wt("div",B,S||this._mapPane);return g&&(this._panes[g]=_e),_e},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var g=this.getPixelBounds(),S=this.unproject(g.getBottomLeft()),B=this.unproject(g.getTopRight());return new fe(S,B)},getMinZoom:function(){return this.options.minZoom===void 0?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===void 0?this._layersMaxZoom===void 0?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(g,S,B){g=ye(g),B=Pe(B||[0,0]);var _e=this.getZoom()||0,Me=this.getMinZoom(),Ke=this.getMaxZoom(),lt=g.getNorthWest(),mt=g.getSouthEast(),yt=this.getSize().subtract(B),_t=Be(this.project(mt,_e),this.project(lt,_e)).getSize(),Tt=$t.any3d?this.options.zoomSnap:1,Mt=yt.x/_t.x,Dt=yt.y/_t.y,br=S?Math.max(Mt,Dt):Math.min(Mt,Dt);return _e=this.getScaleZoom(br,_e),Tt&&(_e=Math.round(_e/(Tt/100))*(Tt/100),_e=S?Math.ceil(_e/Tt)*Tt:Math.floor(_e/Tt)*Tt),Math.max(Me,Math.min(Ke,_e))},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new se(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(g,S){var B=this._getTopLeftPoint(g,S);return new Ue(B,B.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(g){return this.options.crs.getProjectedBounds(g===void 0?this.getZoom():g)},getPane:function(g){return typeof g=="string"?this._panes[g]:g},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(g,S){var B=this.options.crs;return S=S===void 0?this._zoom:S,B.scale(g)/B.scale(S)},getScaleZoom:function(g,S){var B=this.options.crs;S=S===void 0?this._zoom:S;var _e=B.zoom(g*B.scale(S));return isNaN(_e)?1/0:_e},project:function(g,S){return S=S===void 0?this._zoom:S,this.options.crs.latLngToPoint(Le(g),S)},unproject:function(g,S){return S=S===void 0?this._zoom:S,this.options.crs.pointToLatLng(Pe(g),S)},layerPointToLatLng:function(g){var S=Pe(g).add(this.getPixelOrigin());return this.unproject(S)},latLngToLayerPoint:function(g){var S=this.project(Le(g))._round();return S._subtract(this.getPixelOrigin())},wrapLatLng:function(g){return this.options.crs.wrapLatLng(Le(g))},wrapLatLngBounds:function(g){return this.options.crs.wrapLatLngBounds(ye(g))},distance:function(g,S){return this.options.crs.distance(Le(g),Le(S))},containerPointToLayerPoint:function(g){return Pe(g).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(g){return Pe(g).add(this._getMapPanePos())},containerPointToLatLng:function(g){var S=this.containerPointToLayerPoint(Pe(g));return this.layerPointToLatLng(S)},latLngToContainerPoint:function(g){return this.layerPointToContainerPoint(this.latLngToLayerPoint(Le(g)))},mouseEventToContainerPoint:function(g){return ri(g,this._container)},mouseEventToLayerPoint:function(g){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(g))},mouseEventToLatLng:function(g){return this.layerPointToLatLng(this.mouseEventToLayerPoint(g))},_initContainer:function(g){var S=this._container=Gn(g);if(S){if(S._leaflet_id)throw new Error("Map container is already initialized.")}else throw new Error("Map container not found.");Ot(S,"scroll",this._onScroll,this),this._containerId=u(S)},_initLayout:function(){var g=this._container;this._fadeAnimated=this.options.fadeAnimation&&$t.any3d,Nt(g,"leaflet-container"+($t.touch?" leaflet-touch":"")+($t.retina?" leaflet-retina":"")+($t.ielt9?" leaflet-oldie":"")+($t.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":""));var S=Ar(g,"position");S!=="absolute"&&S!=="relative"&&S!=="fixed"&&(g.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var g=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),lr(this._mapPane,new se(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(Nt(g.markerPane,"leaflet-zoom-hide"),Nt(g.shadowPane,"leaflet-zoom-hide"))},_resetView:function(g,S,B){lr(this._mapPane,new se(0,0));var _e=!this._loaded;this._loaded=!0,S=this._limitZoom(S),this.fire("viewprereset");var Me=this._zoom!==S;this._moveStart(Me,B)._move(g,S)._moveEnd(Me),this.fire("viewreset"),_e&&this.fire("load")},_moveStart:function(g,S){return g&&this.fire("zoomstart"),S||this.fire("movestart"),this},_move:function(g,S,B,_e){S===void 0&&(S=this._zoom);var Me=this._zoom!==S;return this._zoom=S,this._lastCenter=g,this._pixelOrigin=this._getNewPixelOrigin(g),_e?B&&B.pinch&&this.fire("zoom",B):((Me||B&&B.pinch)&&this.fire("zoom",B),this.fire("move",B)),this},_moveEnd:function(g){return g&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return he(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(g){lr(this._mapPane,this._getMapPanePos().subtract(g))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(g){this._targets={},this._targets[u(this._container)]=this;var S=g?Qt:Ot;S(this._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&S(window,"resize",this._onResize,this),$t.any3d&&this.options.transform3DLimit&&(g?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){he(this._resizeRequest),this._resizeRequest=ee(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var g=this._getMapPanePos();Math.max(Math.abs(g.x),Math.abs(g.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(g,S){for(var B=[],_e,Me=S==="mouseout"||S==="mouseover",Ke=g.target||g.srcElement,lt=!1;Ke;){if(_e=this._targets[u(Ke)],_e&&(S==="click"||S==="preclick")&&this._draggableMoved(_e)){lt=!0;break}if(_e&&_e.listens(S,!0)&&(Me&&!Bi(Ke,g)||(B.push(_e),Me))||Ke===this._container)break;Ke=Ke.parentNode}return!B.length&&!lt&&!Me&&this.listens(S,!0)&&(B=[this]),B},_isClickDisabled:function(g){for(;g&&g!==this._container;){if(g._leaflet_disable_click)return!0;g=g.parentNode}},_handleDOMEvent:function(g){var S=g.target||g.srcElement;if(!(!this._loaded||S._leaflet_disable_events||g.type==="click"&&this._isClickDisabled(S))){var B=g.type;B==="mousedown"&&Li(S),this._fireDOMEvent(g,B)}},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(g,S,B){if(g.type==="click"){var _e=o({},g);_e.type="preclick",this._fireDOMEvent(_e,_e.type,B)}var Me=this._findEventTargets(g,S);if(B){for(var Ke=[],lt=0;lt0?Math.round(g-S)/2:Math.max(0,Math.ceil(g))-Math.max(0,Math.floor(S))},_limitZoom:function(g){var S=this.getMinZoom(),B=this.getMaxZoom(),_e=$t.any3d?this.options.zoomSnap:1;return _e&&(g=Math.round(g/_e)*_e),Math.max(S,Math.min(B,g))},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){ar(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(g,S){var B=this._getCenterOffset(g)._trunc();return(S&&S.animate)!==!0&&!this.getSize().contains(B)?!1:(this.panBy(B,S),!0)},_createAnimProxy:function(){var g=this._proxy=Wt("div","leaflet-proxy leaflet-zoom-animated");this._panes.mapPane.appendChild(g),this.on("zoomanim",function(S){var B=ki,_e=this._proxy.style[B];Gr(this._proxy,this.project(S.center,S.zoom),this.getZoomScale(S.zoom,1)),_e===this._proxy.style[B]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on("load moveend",this._animMoveEnd,this),this._on("unload",this._destroyAnimProxy,this)},_destroyAnimProxy:function(){ir(this._proxy),this.off("load moveend",this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var g=this.getCenter(),S=this.getZoom();Gr(this._proxy,this.project(g,S),this.getZoomScale(S,1))},_catchTransitionEnd:function(g){this._animatingZoom&&g.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(g,S,B){if(this._animatingZoom)return!0;if(B=B||{},!this._zoomAnimated||B.animate===!1||this._nothingToAnimate()||Math.abs(S-this._zoom)>this.options.zoomAnimationThreshold)return!1;var _e=this.getZoomScale(S),Me=this._getCenterOffset(g)._divideBy(1-1/_e);return B.animate!==!0&&!this.getSize().contains(Me)?!1:(ee(function(){this._moveStart(!0,!1)._animateZoom(g,S,!0)},this),!0)},_animateZoom:function(g,S,B,_e){!this._mapPane||(B&&(this._animatingZoom=!0,this._animateToCenter=g,this._animateToZoom=S,Nt(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:g,zoom:S,noUpdate:_e}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(l(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){!this._animatingZoom||(this._mapPane&&ar(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function gs(g,S){return new Vt(g,S)}var Cr=xe.extend({options:{position:"topright"},initialize:function(g){T(this,g)},getPosition:function(){return this.options.position},setPosition:function(g){var S=this._map;return S&&S.removeControl(this),this.options.position=g,S&&S.addControl(this),this},getContainer:function(){return this._container},addTo:function(g){this.remove(),this._map=g;var S=this._container=this.onAdd(g),B=this.getPosition(),_e=g._controlCorners[B];return Nt(S,"leaflet-control"),B.indexOf("bottom")!==-1?_e.insertBefore(S,_e.firstChild):_e.appendChild(S),this._map.on("unload",this.remove,this),this},remove:function(){return this._map?(ir(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null,this):this},_refocusOnMap:function(g){this._map&&g&&g.screenX>0&&g.screenY>0&&this._map.getContainer().focus()}}),$n=function(g){return new Cr(g)};Vt.include({addControl:function(g){return g.addTo(this),this},removeControl:function(g){return g.remove(),this},_initControlPos:function(){var g=this._controlCorners={},S="leaflet-",B=this._controlContainer=Wt("div",S+"control-container",this._container);function _e(Me,Ke){var lt=S+Me+" "+S+Ke;g[Me+Ke]=Wt("div",lt,B)}_e("top","left"),_e("top","right"),_e("bottom","left"),_e("bottom","right")},_clearControlPos:function(){for(var g in this._controlCorners)ir(this._controlCorners[g]);ir(this._controlContainer),delete this._controlCorners,delete this._controlContainer}});var ys=Cr.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(g,S,B,_e){return B<_e?-1:_e1,this._baseLayersList.style.display=g?"":"none"),this._separator.style.display=S&&g?"":"none",this},_onLayerChange:function(g){this._handlingClick||this._update();var S=this._getLayer(u(g.target)),B=S.overlay?g.type==="add"?"overlayadd":"overlayremove":g.type==="add"?"baselayerchange":null;B&&this._map.fire(B,S)},_createRadioElement:function(g,S){var B='",_e=document.createElement("div");return _e.innerHTML=B,_e.firstChild},_addItem:function(g){var S=document.createElement("label"),B=this._map.hasLayer(g.layer),_e;g.overlay?(_e=document.createElement("input"),_e.type="checkbox",_e.className="leaflet-control-layers-selector",_e.defaultChecked=B):_e=this._createRadioElement("leaflet-base-layers_"+u(this),B),this._layerControlInputs.push(_e),_e.layerId=u(g.layer),Ot(_e,"click",this._onInputClick,this);var Me=document.createElement("span");Me.innerHTML=" "+g.name;var Ke=document.createElement("span");S.appendChild(Ke),Ke.appendChild(_e),Ke.appendChild(Me);var lt=g.overlay?this._overlaysList:this._baseLayersList;return lt.appendChild(S),this._checkDisabledLayers(),S},_onInputClick:function(){var g=this._layerControlInputs,S,B,_e=[],Me=[];this._handlingClick=!0;for(var Ke=g.length-1;Ke>=0;Ke--)S=g[Ke],B=this._getLayer(S.layerId).layer,S.checked?_e.push(B):S.checked||Me.push(B);for(Ke=0;Ke=0;Me--)S=g[Me],B=this._getLayer(S.layerId).layer,S.disabled=B.options.minZoom!==void 0&&_eB.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this}}),$o=function(g,S,B){return new ys(g,S,B)},Fi=Cr.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(g){var S="leaflet-control-zoom",B=Wt("div",S+" leaflet-bar"),_e=this.options;return this._zoomInButton=this._createButton(_e.zoomInText,_e.zoomInTitle,S+"-in",B,this._zoomIn),this._zoomOutButton=this._createButton(_e.zoomOutText,_e.zoomOutTitle,S+"-out",B,this._zoomOut),this._updateDisabled(),g.on("zoomend zoomlevelschange",this._updateDisabled,this),B},onRemove:function(g){g.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(g){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(g.shiftKey?3:1))},_createButton:function(g,S,B,_e,Me){var Ke=Wt("a",B,_e);return Ke.innerHTML=g,Ke.href="#",Ke.title=S,Ke.setAttribute("role","button"),Ke.setAttribute("aria-label",S),Pr(Ke),Ot(Ke,"click",Zr),Ot(Ke,"click",Me,this),Ot(Ke,"click",this._refocusOnMap,this),Ke},_updateDisabled:function(){var g=this._map,S="leaflet-disabled";ar(this._zoomInButton,S),ar(this._zoomOutButton,S),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),(this._disabled||g._zoom===g.getMinZoom())&&(Nt(this._zoomOutButton,S),this._zoomOutButton.setAttribute("aria-disabled","true")),(this._disabled||g._zoom===g.getMaxZoom())&&(Nt(this._zoomInButton,S),this._zoomInButton.setAttribute("aria-disabled","true"))}});Vt.mergeOptions({zoomControl:!0}),Vt.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new Fi,this.addControl(this.zoomControl))});var Lo=function(g){return new Fi(g)},vs=Cr.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(g){var S="leaflet-control-scale",B=Wt("div",S),_e=this.options;return this._addScales(_e,S+"-line",B),g.on(_e.updateWhenIdle?"moveend":"move",this._update,this),g.whenReady(this._update,this),B},onRemove:function(g){g.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(g,S,B){g.metric&&(this._mScale=Wt("div",S,B)),g.imperial&&(this._iScale=Wt("div",S,B))},_update:function(){var g=this._map,S=g.getSize().y/2,B=g.distance(g.containerPointToLatLng([0,S]),g.containerPointToLatLng([this.options.maxWidth,S]));this._updateScales(B)},_updateScales:function(g){this.options.metric&&g&&this._updateMetric(g),this.options.imperial&&g&&this._updateImperial(g)},_updateMetric:function(g){var S=this._getRoundNum(g),B=S<1e3?S+" m":S/1e3+" km";this._updateScale(this._mScale,B,S/g)},_updateImperial:function(g){var S=g*3.2808399,B,_e,Me;S>5280?(B=S/5280,_e=this._getRoundNum(B),this._updateScale(this._iScale,_e+" mi",_e/B)):(Me=this._getRoundNum(S),this._updateScale(this._iScale,Me+" ft",Me/S))},_updateScale:function(g,S,B){g.style.width=Math.round(this.options.maxWidth*B)+"px",g.innerHTML=S},_getRoundNum:function(g){var S=Math.pow(10,(Math.floor(g)+"").length-1),B=g/S;return B=B>=10?10:B>=5?5:B>=3?3:B>=2?2:1,S*B}}),_s=function(g){return new vs(g)},Ro='',Ui=Cr.extend({options:{position:"bottomright",prefix:''+($t.inlineSvg?Ro+" ":"")+"Leaflet"},initialize:function(g){T(this,g),this._attributions={}},onAdd:function(g){g.attributionControl=this,this._container=Wt("div","leaflet-control-attribution"),Pr(this._container);for(var S in g._layers)g._layers[S].getAttribution&&this.addAttribution(g._layers[S].getAttribution());return this._update(),g.on("layeradd",this._addAttribution,this),this._container},onRemove:function(g){g.off("layeradd",this._addAttribution,this)},_addAttribution:function(g){g.layer.getAttribution&&(this.addAttribution(g.layer.getAttribution()),g.layer.once("remove",function(){this.removeAttribution(g.layer.getAttribution())},this))},setPrefix:function(g){return this.options.prefix=g,this._update(),this},addAttribution:function(g){return g?(this._attributions[g]||(this._attributions[g]=0),this._attributions[g]++,this._update(),this):this},removeAttribution:function(g){return g?(this._attributions[g]&&(this._attributions[g]--,this._update()),this):this},_update:function(){if(!!this._map){var g=[];for(var S in this._attributions)this._attributions[S]&&g.push(S);var B=[];this.options.prefix&&B.push(this.options.prefix),g.length&&B.push(g.join(", ")),this._container.innerHTML=B.join(' ')}}});Vt.mergeOptions({attributionControl:!0}),Vt.addInitHook(function(){this.options.attributionControl&&new Ui().addTo(this)});var Mo=function(g){return new Ui(g)};Cr.Layers=ys,Cr.Zoom=Fi,Cr.Scale=vs,Cr.Attribution=Ui,$n.layers=$o,$n.zoom=Lo,$n.scale=_s,$n.attribution=Mo;var Ir=xe.extend({initialize:function(g){this._map=g},enable:function(){return this._enabled?this:(this._enabled=!0,this.addHooks(),this)},disable:function(){return this._enabled?(this._enabled=!1,this.removeHooks(),this):this},enabled:function(){return!!this._enabled}});Ir.addTo=function(g,S){return g.addHandler(S,this),this};var Oo={Events:ae},bs=$t.touch?"touchstart mousedown":"mousedown",Vr=ge.extend({options:{clickTolerance:3},initialize:function(g,S,B,_e){T(this,_e),this._element=g,this._dragStartTarget=S||g,this._preventOutline=B},enable:function(){this._enabled||(Ot(this._dragStartTarget,bs,this._onDown,this),this._enabled=!0)},disable:function(){!this._enabled||(Vr._dragging===this&&this.finishDrag(!0),Qt(this._dragStartTarget,bs,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(g){if(!!this._enabled&&(this._moved=!1,!Xn(this._element,"leaflet-zoom-anim"))){if(g.touches&&g.touches.length!==1){Vr._dragging===this&&this.finishDrag();return}if(!(Vr._dragging||g.shiftKey||g.which!==1&&g.button!==1&&!g.touches)&&(Vr._dragging=this,this._preventOutline&&Li(this._element),Pi(),kn(),!this._moving)){this.fire("down");var S=g.touches?g.touches[0]:g,B=Ri(this._element);this._startPoint=new se(S.clientX,S.clientY),this._startPos=qr(this._element),this._parentScale=ei(B);var _e=g.type==="mousedown";Ot(document,_e?"mousemove":"touchmove",this._onMove,this),Ot(document,_e?"mouseup":"touchend touchcancel",this._onUp,this)}}},_onMove:function(g){if(!!this._enabled){if(g.touches&&g.touches.length>1){this._moved=!0;return}var S=g.touches&&g.touches.length===1?g.touches[0]:g,B=new se(S.clientX,S.clientY)._subtract(this._startPoint);!B.x&&!B.y||Math.abs(B.x)+Math.abs(B.y)Ke&&(lt=mt,Ke=yt);Ke>B&&(S[lt]=1,Vi(g,S,B,_e,lt),Vi(g,S,B,lt,Me))}function No(g,S){for(var B=[g[0]],_e=1,Me=0,Ke=g.length;_eS&&(B.push(g[_e]),Me=_e);return MeS.max.x&&(B|=2),g.yS.max.y&&(B|=8),B}function Bo(g,S){var B=S.x-g.x,_e=S.y-g.y;return B*B+_e*_e}function Rn(g,S,B,_e){var Me=S.x,Ke=S.y,lt=B.x-Me,mt=B.y-Ke,yt=lt*lt+mt*mt,_t;return yt>0&&(_t=((g.x-Me)*lt+(g.y-Ke)*mt)/yt,_t>1?(Me=B.x,Ke=B.y):_t>0&&(Me+=lt*_t,Ke+=mt*_t)),lt=g.x-Me,mt=g.y-Ke,_e?lt*lt+mt*mt:new se(Me,Ke)}function Er(g){return!N(g[0])||typeof g[0][0]!="object"&&typeof g[0][0]<"u"}function ks(g){return console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead."),Er(g)}function Ts(g,S){var B,_e,Me,Ke,lt,mt,yt,_t;if(!g||g.length===0)throw new Error("latlngs not passed");Er(g)||(console.warn("latlngs are not flat! Only the first ring will be used"),g=g[0]);var Tt=[];for(var Mt in g)Tt.push(S.project(Le(g[Mt])));var Dt=Tt.length;for(B=0,_e=0;B_e){yt=(Ke-_e)/Me,_t=[mt.x-yt*(mt.x-lt.x),mt.y-yt*(mt.y-lt.y)];break}return S.unproject(Pe(_t))}var As={__proto__:null,simplify:ws,pointToSegmentDistance:xs,closestPointOnSegment:Do,clipSegment:Cs,_getEdgeIntersection:Ln,_getBitCode:Qr,_sqClosestPointOnSegment:Rn,isFlat:Er,_flat:ks,polylineCenter:Ts};function Mn(g,S,B){var _e,Me=[1,4,2,8],Ke,lt,mt,yt,_t,Tt,Mt,Dt;for(Ke=0,Tt=g.length;Ke1e-7;mt++)_t=Me*Math.sin(lt),_t=Math.pow((1-_t)/(1+_t),Me/2),yt=Math.PI/2-2*Math.atan(Ke*_t)-lt,lt+=yt;return new Ce(lt*S,g.x*S/B)}},Fo={__proto__:null,LonLat:Hi,Mercator:ii,SphericalMercator:Re},Is=o({},Oe,{code:"EPSG:3395",projection:ii,transformation:function(){var g=.5/(Math.PI*ii.R);return we(g,.5,-g,.5)}()}),$s=o({},Oe,{code:"EPSG:4326",projection:Hi,transformation:we(1/180,1,-1/180,.5)}),On=o({},Fe,{projection:Hi,transformation:we(1,0,-1,0),scale:function(g){return Math.pow(2,g)},zoom:function(g){return Math.log(g)/Math.LN2},distance:function(g,S){var B=S.lng-g.lng,_e=S.lat-g.lat;return Math.sqrt(B*B+_e*_e)},infinite:!0});Fe.Earth=Oe,Fe.EPSG3395=Is,Fe.EPSG3857=oe,Fe.EPSG900913=pe,Fe.EPSG4326=$s,Fe.Simple=On;var kr=ge.extend({options:{pane:"overlayPane",attribution:null,bubblingMouseEvents:!0},addTo:function(g){return g.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(g){return g&&g.removeLayer(this),this},getPane:function(g){return this._map.getPane(g?this.options[g]||g:this.options.pane)},addInteractiveTarget:function(g){return this._map._targets[u(g)]=this,this},removeInteractiveTarget:function(g){return delete this._map._targets[u(g)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(g){var S=g.target;if(!!S.hasLayer(this)){if(this._map=S,this._zoomAnimated=S._zoomAnimated,this.getEvents){var B=this.getEvents();S.on(B,this),this.once("remove",function(){S.off(B,this)},this)}this.onAdd(S),this.fire("add"),S.fire("layeradd",{layer:this})}}});Vt.include({addLayer:function(g){if(!g._layerAdd)throw new Error("The provided object is not a Layer.");var S=u(g);return this._layers[S]?this:(this._layers[S]=g,g._mapToAdd=this,g.beforeAdd&&g.beforeAdd(this),this.whenReady(g._layerAdd,g),this)},removeLayer:function(g){var S=u(g);return this._layers[S]?(this._loaded&&g.onRemove(this),delete this._layers[S],this._loaded&&(this.fire("layerremove",{layer:g}),g.fire("remove")),g._map=g._mapToAdd=null,this):this},hasLayer:function(g){return u(g)in this._layers},eachLayer:function(g,S){for(var B in this._layers)g.call(S,this._layers[B]);return this},_addLayers:function(g){g=g?N(g)?g:[g]:[];for(var S=0,B=g.length;Sthis._layersMaxZoom&&this.setZoom(this._layersMaxZoom),this.options.minZoom===void 0&&this._layersMinZoom&&this.getZoom()=2&&S[0]instanceof Ce&&S[0].equals(S[B-1])&&S.pop(),S},_setLatLngs:function(g){$r.prototype._setLatLngs.call(this,g),Er(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return Er(this._latlngs[0])?this._latlngs[0]:this._latlngs[0][0]},_clipPoints:function(){var g=this._renderer._bounds,S=this.options.weight,B=new se(S,S);if(g=new Ue(g.min.subtract(B),g.max.add(B)),this._parts=[],!(!this._pxBounds||!this._pxBounds.intersects(g))){if(this.options.noClip){this._parts=this._rings;return}for(var _e=0,Me=this._rings.length,Ke;_eg.y!=Me.y>g.y&&g.x<(Me.x-_e.x)*(g.y-_e.y)/(Me.y-_e.y)+_e.x&&(S=!S);return S||$r.prototype._containsPoint.call(this,g,!0)}});function oi(g,S){return new en(g,S)}var Rr=Jr.extend({initialize:function(g,S){T(this,S),this._layers={},g&&this.addData(g)},addData:function(g){var S=N(g)?g:g.features,B,_e,Me;if(S){for(B=0,_e=S.length;B<_e;B++)Me=S[B],(Me.geometries||Me.geometry||Me.features||Me.coordinates)&&this.addData(Me);return this}var Ke=this.options;if(Ke.filter&&!Ke.filter(g))return this;var lt=Fn(g,Ke);return lt?(lt.feature=tn(g),lt.defaultOptions=lt.options,this.resetStyle(lt),Ke.onEachFeature&&Ke.onEachFeature(g,lt),this.addLayer(lt)):this},resetStyle:function(g){return g===void 0?this.eachLayer(this.resetStyle,this):(g.options=o({},g.defaultOptions),this._setLayerStyle(g,this.options.style),this)},setStyle:function(g){return this.eachLayer(function(S){this._setLayerStyle(S,g)},this)},_setLayerStyle:function(g,S){g.setStyle&&(typeof S=="function"&&(S=S(g.feature)),g.setStyle(S))}});function Fn(g,S){var B=g.type==="Feature"?g.geometry:g,_e=B?B.coordinates:null,Me=[],Ke=S&&S.pointToLayer,lt=S&&S.coordsToLatLng||zi,mt,yt,_t,Tt;if(!_e&&!B)return null;switch(B.type){case"Point":return mt=lt(_e),Ds(Ke,g,mt,S);case"MultiPoint":for(_t=0,Tt=_e.length;_t0?_e:[S.src];return}N(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(S.style,"objectFit")&&(S.style.objectFit="fill"),S.autoplay=!!this.options.autoplay,S.loop=!!this.options.loop,S.muted=!!this.options.muted,S.playsInline=!!this.options.playsInline;for(var Ke=0;KeMe?(S.height=Me+"px",Nt(g,Ke)):ar(g,Ke),this._containerWidth=this._container.offsetWidth},_animateZoom:function(g){var S=this._map._latLngToNewLayerPoint(this._latlng,g.zoom,g.center),B=this._getAnchor();lr(this._container,S.add(B))},_adjustPan:function(g){if(!!this.options.autoPan){this._map._panAnim&&this._map._panAnim.stop();var S=this._map,B=parseInt(Ar(this._container,"marginBottom"),10)||0,_e=this._container.offsetHeight+B,Me=this._containerWidth,Ke=new se(this._containerLeft,-_e-this._containerBottom);Ke._add(qr(this._container));var lt=S.layerPointToContainerPoint(Ke),mt=Pe(this.options.autoPanPadding),yt=Pe(this.options.autoPanPaddingTopLeft||mt),_t=Pe(this.options.autoPanPaddingBottomRight||mt),Tt=S.getSize(),Mt=0,Dt=0;lt.x+Me+_t.x>Tt.x&&(Mt=lt.x+Me-Tt.x+_t.x),lt.x-Mt-yt.x<0&&(Mt=lt.x-yt.x),lt.y+_e+_t.y>Tt.y&&(Dt=lt.y+_e-Tt.y+_t.y),lt.y-Dt-yt.y<0&&(Dt=lt.y-yt.y),(Mt||Dt)&&S.fire("autopanstart").panBy([Mt,Dt],{animate:g&&g.type==="moveend"})}},_getAnchor:function(){return Pe(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}}),Ko=function(g,S){return new rn(g,S)};Vt.mergeOptions({closePopupOnClick:!0}),Vt.include({openPopup:function(g,S,B){return this._initOverlay(rn,g,S,B).openOn(this),this},closePopup:function(g){return g=arguments.length?g:this._popup,g&&g.close(),this}}),kr.include({bindPopup:function(g,S){return this._popup=this._initOverlay(rn,this._popup,g,S),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(g){return this._popup&&this._popup._prepareOpen(g||this._latlng)&&this._popup.openOn(this._map),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return this._popup?this._popup.isOpen():!1},setPopupContent:function(g){return this._popup&&this._popup.setContent(g),this},getPopup:function(){return this._popup},_openPopup:function(g){if(!(!this._popup||!this._map)){Zr(g);var S=g.layer||g.target;if(this._popup._source===S&&!(S instanceof Hr)){this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(g.latlng);return}this._popup._source=S,this.openPopup(g.latlng)}},_movePopup:function(g){this._popup.setLatLng(g.latlng)},_onKeyPress:function(g){g.originalEvent.keyCode===13&&this._openPopup(g)}});var ci=Lr.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(g){Lr.prototype.onAdd.call(this,g),this.setOpacity(this.options.opacity),g.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(g){Lr.prototype.onRemove.call(this,g),g.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var g=Lr.prototype.getEvents.call(this);return this.options.permanent||(g.preclick=this.close),g},_initLayout:function(){var g="leaflet-tooltip",S=g+" "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=Wt("div",S),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+u(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(g){var S,B,_e=this._map,Me=this._container,Ke=_e.latLngToContainerPoint(_e.getCenter()),lt=_e.layerPointToContainerPoint(g),mt=this.options.direction,yt=Me.offsetWidth,_t=Me.offsetHeight,Tt=Pe(this.options.offset),Mt=this._getAnchor();mt==="top"?(S=yt/2,B=_t):mt==="bottom"?(S=yt/2,B=0):mt==="center"?(S=yt/2,B=_t/2):mt==="right"?(S=0,B=_t/2):mt==="left"?(S=yt,B=_t/2):lt.xthis.options.maxZoom||B_e?this._retainParent(Me,Ke,lt,_e):!1)},_retainChildren:function(g,S,B,_e){for(var Me=2*g;Me<2*g+2;Me++)for(var Ke=2*S;Ke<2*S+2;Ke++){var lt=new se(Me,Ke);lt.z=B+1;var mt=this._tileCoordsToKey(lt),yt=this._tiles[mt];if(yt&&yt.active){yt.retain=!0;continue}else yt&&yt.loaded&&(yt.retain=!0);B+1<_e&&this._retainChildren(Me,Ke,B+1,_e)}},_resetView:function(g){var S=g&&(g.pinch||g.flyTo);this._setView(this._map.getCenter(),this._map.getZoom(),S,S)},_animateZoom:function(g){this._setView(g.center,g.zoom,!0,g.noUpdate)},_clampZoom:function(g){var S=this.options;return S.minNativeZoom!==void 0&&gthis.options.maxZoom||this.options.minZoom!==void 0&&Me1){this._setView(g,B);return}for(var Mt=Me.min.y;Mt<=Me.max.y;Mt++)for(var Dt=Me.min.x;Dt<=Me.max.x;Dt++){var br=new se(Dt,Mt);if(br.z=this._tileZoom,!!this._isValidTile(br)){var Wr=this._tiles[this._tileCoordsToKey(br)];Wr?Wr.current=!0:lt.push(br)}}if(lt.sort(function(Or,Wn){return Or.distanceTo(Ke)-Wn.distanceTo(Ke)}),lt.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var fi=document.createDocumentFragment();for(Dt=0;DtB.max.x)||!S.wrapLat&&(g.yB.max.y))return!1}if(!this.options.bounds)return!0;var _e=this._tileCoordsToBounds(g);return ye(this.options.bounds).overlaps(_e)},_keyToBounds:function(g){return this._tileCoordsToBounds(this._keyToTileCoords(g))},_tileCoordsToNwSe:function(g){var S=this._map,B=this.getTileSize(),_e=g.scaleBy(B),Me=_e.add(B),Ke=S.unproject(_e,g.z),lt=S.unproject(Me,g.z);return[Ke,lt]},_tileCoordsToBounds:function(g){var S=this._tileCoordsToNwSe(g),B=new fe(S[0],S[1]);return this.options.noWrap||(B=this._map.wrapLatLngBounds(B)),B},_tileCoordsToKey:function(g){return g.x+":"+g.y+":"+g.z},_keyToTileCoords:function(g){var S=g.split(":"),B=new se(+S[0],+S[1]);return B.z=+S[2],B},_removeTile:function(g){var S=this._tiles[g];!S||(ir(S.el),delete this._tiles[g],this.fire("tileunload",{tile:S.el,coords:this._keyToTileCoords(g)}))},_initTile:function(g){Nt(g,"leaflet-tile");var S=this.getTileSize();g.style.width=S.x+"px",g.style.height=S.y+"px",g.onselectstart=x,g.onmousemove=x,$t.ielt9&&this.options.opacity<1&&xr(g,this.options.opacity)},_addTile:function(g,S){var B=this._getTilePos(g),_e=this._tileCoordsToKey(g),Me=this.createTile(this._wrapCoords(g),l(this._tileReady,this,g));this._initTile(Me),this.createTile.length<2&&ee(l(this._tileReady,this,g,null,Me)),lr(Me,B),this._tiles[_e]={el:Me,coords:g,current:!0},S.appendChild(Me),this.fire("tileloadstart",{tile:Me,coords:g})},_tileReady:function(g,S,B){S&&this.fire("tileerror",{error:S,tile:B,coords:g});var _e=this._tileCoordsToKey(g);B=this._tiles[_e],B&&(B.loaded=+new Date,this._map._fadeAnimated?(xr(B.el,0),he(this._fadeFrame),this._fadeFrame=ee(this._updateOpacity,this)):(B.active=!0,this._pruneTiles()),S||(Nt(B.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:B.el,coords:g})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),$t.ielt9||!this._map._fadeAnimated?ee(this._pruneTiles,this):setTimeout(l(this._pruneTiles,this),250)))},_getTilePos:function(g){return g.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(g){var S=new se(this._wrapX?b(g.x,this._wrapX):g.x,this._wrapY?b(g.y,this._wrapY):g.y);return S.z=g.z,S},_pxBoundsToTileRange:function(g){var S=this.getTileSize();return new Ue(g.min.unscaleBy(S).floor(),g.max.unscaleBy(S).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var g in this._tiles)if(!this._tiles[g].loaded)return!1;return!0}});function qo(g){return new Vn(g)}var nn=Vn.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(g,S){this._url=g,S=T(this,S),S.detectRetina&&$t.retina&&S.maxZoom>0?(S.tileSize=Math.floor(S.tileSize/2),S.zoomReverse?(S.zoomOffset--,S.minZoom=Math.min(S.maxZoom,S.minZoom+1)):(S.zoomOffset++,S.maxZoom=Math.max(S.minZoom,S.maxZoom-1)),S.minZoom=Math.max(0,S.minZoom)):S.zoomReverse?S.minZoom=Math.min(S.maxZoom,S.minZoom):S.maxZoom=Math.max(S.minZoom,S.maxZoom),typeof S.subdomains=="string"&&(S.subdomains=S.subdomains.split("")),this.on("tileunload",this._onTileRemove)},setUrl:function(g,S){return this._url===g&&S===void 0&&(S=!0),this._url=g,S||this.redraw(),this},createTile:function(g,S){var B=document.createElement("img");return Ot(B,"load",l(this._tileOnLoad,this,S,B)),Ot(B,"error",l(this._tileOnError,this,S,B)),(this.options.crossOrigin||this.options.crossOrigin==="")&&(B.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),typeof this.options.referrerPolicy=="string"&&(B.referrerPolicy=this.options.referrerPolicy),B.alt="",B.src=this.getTileUrl(g),B},getTileUrl:function(g){var S={r:$t.retina?"@2x":"",s:this._getSubdomain(g),x:g.x,y:g.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var B=this._globalTileRange.max.y-g.y;this.options.tms&&(S.y=B),S["-y"]=B}return D(this._url,o(S,this.options))},_tileOnLoad:function(g,S){$t.ielt9?setTimeout(l(g,this,null,S),0):g(null,S)},_tileOnError:function(g,S,B){var _e=this.options.errorTileUrl;_e&&S.getAttribute("src")!==_e&&(S.src=_e),g(B,S)},_onTileRemove:function(g){g.tile.onload=null},_getZoomForUrl:function(){var g=this._tileZoom,S=this.options.maxZoom,B=this.options.zoomReverse,_e=this.options.zoomOffset;return B&&(g=S-g),g+_e},_getSubdomain:function(g){var S=Math.abs(g.x+g.y)%this.options.subdomains.length;return this.options.subdomains[S]},_abortLoading:function(){var g,S;for(g in this._tiles)if(this._tiles[g].coords.z!==this._tileZoom&&(S=this._tiles[g].el,S.onload=x,S.onerror=x,!S.complete)){S.src=ie;var B=this._tiles[g].coords;ir(S),delete this._tiles[g],this.fire("tileabort",{tile:S,coords:B})}},_removeTile:function(g){var S=this._tiles[g];if(!!S)return S.el.setAttribute("src",ie),Vn.prototype._removeTile.call(this,g)},_tileReady:function(g,S,B){if(!(!this._map||B&&B.getAttribute("src")===ie))return Vn.prototype._tileReady.call(this,g,S,B)}});function Ki(g,S){return new nn(g,S)}var Us=nn.extend({defaultWmsParams:{service:"WMS",request:"GetMap",layers:"",styles:"",format:"image/jpeg",transparent:!1,version:"1.1.1"},options:{crs:null,uppercase:!1},initialize:function(g,S){this._url=g;var B=o({},this.defaultWmsParams);for(var _e in S)_e in this.options||(B[_e]=S[_e]);S=T(this,S);var Me=S.detectRetina&&$t.retina?2:1,Ke=this.getTileSize();B.width=Ke.x*Me,B.height=Ke.y*Me,this.wmsParams=B},onAdd:function(g){this._crs=this.options.crs||g.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var S=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[S]=this._crs.code,nn.prototype.onAdd.call(this,g)},getTileUrl:function(g){var S=this._tileCoordsToNwSe(g),B=this._crs,_e=Be(B.project(S[0]),B.project(S[1])),Me=_e.min,Ke=_e.max,lt=(this._wmsVersion>=1.3&&this._crs===$s?[Me.y,Me.x,Ke.y,Ke.x]:[Me.x,Me.y,Ke.x,Ke.y]).join(","),mt=nn.prototype.getTileUrl.call(this,g);return mt+O(this.wmsParams,mt,this.options.uppercase)+(this.options.uppercase?"&BBOX=":"&bbox=")+lt},setParams:function(g,S){return o(this.wmsParams,g),S||this.redraw(),this}});function Xo(g,S){return new Us(g,S)}nn.WMS=Us,Ki.wms=Xo;var Mr=kr.extend({options:{padding:.1},initialize:function(g){T(this,g),u(this),this._layers=this._layers||{}},onAdd:function(){this._container||(this._initContainer(),this._zoomAnimated&&Nt(this._container,"leaflet-zoom-animated")),this.getPane().appendChild(this._container),this._update(),this.on("update",this._updatePaths,this)},onRemove:function(){this.off("update",this._updatePaths,this),this._destroyContainer()},getEvents:function(){var g={viewreset:this._reset,zoom:this._onZoom,moveend:this._update,zoomend:this._onZoomEnd};return this._zoomAnimated&&(g.zoomanim=this._onAnimZoom),g},_onAnimZoom:function(g){this._updateTransform(g.center,g.zoom)},_onZoom:function(){this._updateTransform(this._map.getCenter(),this._map.getZoom())},_updateTransform:function(g,S){var B=this._map.getZoomScale(S,this._zoom),_e=this._map.getSize().multiplyBy(.5+this.options.padding),Me=this._map.project(this._center,S),Ke=_e.multiplyBy(-B).add(Me).subtract(this._map._getNewPixelOrigin(g,S));$t.any3d?Gr(this._container,Ke,B):lr(this._container,Ke)},_reset:function(){this._update(),this._updateTransform(this._center,this._zoom);for(var g in this._layers)this._layers[g]._reset()},_onZoomEnd:function(){for(var g in this._layers)this._layers[g]._project()},_updatePaths:function(){for(var g in this._layers)this._layers[g]._update()},_update:function(){var g=this.options.padding,S=this._map.getSize(),B=this._map.containerPointToLayerPoint(S.multiplyBy(-g)).round();this._bounds=new Ue(B,B.add(S.multiplyBy(1+g*2)).round()),this._center=this._map.getCenter(),this._zoom=this._map.getZoom()}}),Vs=Mr.extend({options:{tolerance:0},getEvents:function(){var g=Mr.prototype.getEvents.call(this);return g.viewprereset=this._onViewPreReset,g},_onViewPreReset:function(){this._postponeUpdatePaths=!0},onAdd:function(){Mr.prototype.onAdd.call(this),this._draw()},_initContainer:function(){var g=this._container=document.createElement("canvas");Ot(g,"mousemove",this._onMouseMove,this),Ot(g,"click dblclick mousedown mouseup contextmenu",this._onClick,this),Ot(g,"mouseout",this._handleMouseOut,this),g._leaflet_disable_events=!0,this._ctx=g.getContext("2d")},_destroyContainer:function(){he(this._redrawRequest),delete this._ctx,ir(this._container),Qt(this._container),delete this._container},_updatePaths:function(){if(!this._postponeUpdatePaths){var g;this._redrawBounds=null;for(var S in this._layers)g=this._layers[S],g._update();this._redraw()}},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Mr.prototype._update.call(this);var g=this._bounds,S=this._container,B=g.getSize(),_e=$t.retina?2:1;lr(S,g.min),S.width=_e*B.x,S.height=_e*B.y,S.style.width=B.x+"px",S.style.height=B.y+"px",$t.retina&&this._ctx.scale(2,2),this._ctx.translate(-g.min.x,-g.min.y),this.fire("update")}},_reset:function(){Mr.prototype._reset.call(this),this._postponeUpdatePaths&&(this._postponeUpdatePaths=!1,this._updatePaths())},_initPath:function(g){this._updateDashArray(g),this._layers[u(g)]=g;var S=g._order={layer:g,prev:this._drawLast,next:null};this._drawLast&&(this._drawLast.next=S),this._drawLast=S,this._drawFirst=this._drawFirst||this._drawLast},_addPath:function(g){this._requestRedraw(g)},_removePath:function(g){var S=g._order,B=S.next,_e=S.prev;B?B.prev=_e:this._drawLast=_e,_e?_e.next=B:this._drawFirst=B,delete g._order,delete this._layers[u(g)],this._requestRedraw(g)},_updatePath:function(g){this._extendRedrawBounds(g),g._project(),g._update(),this._requestRedraw(g)},_updateStyle:function(g){this._updateDashArray(g),this._requestRedraw(g)},_updateDashArray:function(g){if(typeof g.options.dashArray=="string"){var S=g.options.dashArray.split(/[, ]+/),B=[],_e,Me;for(Me=0;Me')}}catch{}return function(g){return document.createElement("<"+g+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),Zo={_initContainer:function(){this._container=Wt("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Mr.prototype._update.call(this),this.fire("update"))},_initPath:function(g){var S=g._container=Hn("shape");Nt(S,"leaflet-vml-shape "+(this.options.className||"")),S.coordsize="1 1",g._path=Hn("path"),S.appendChild(g._path),this._updateStyle(g),this._layers[u(g)]=g},_addPath:function(g){var S=g._container;this._container.appendChild(S),g.options.interactive&&g.addInteractiveTarget(S)},_removePath:function(g){var S=g._container;ir(S),g.removeInteractiveTarget(S),delete this._layers[u(g)]},_updateStyle:function(g){var S=g._stroke,B=g._fill,_e=g.options,Me=g._container;Me.stroked=!!_e.stroke,Me.filled=!!_e.fill,_e.stroke?(S||(S=g._stroke=Hn("stroke")),Me.appendChild(S),S.weight=_e.weight+"px",S.color=_e.color,S.opacity=_e.opacity,_e.dashArray?S.dashStyle=N(_e.dashArray)?_e.dashArray.join(" "):_e.dashArray.replace(/( *, *)/g," "):S.dashStyle="",S.endcap=_e.lineCap.replace("butt","flat"),S.joinstyle=_e.lineJoin):S&&(Me.removeChild(S),g._stroke=null),_e.fill?(B||(B=g._fill=Hn("fill")),Me.appendChild(B),B.color=_e.fillColor||_e.color,B.opacity=_e.fillOpacity):B&&(Me.removeChild(B),g._fill=null)},_updateCircle:function(g){var S=g._point.round(),B=Math.round(g._radius),_e=Math.round(g._radiusY||B);this._setPath(g,g._empty()?"M0 0":"AL "+S.x+","+S.y+" "+B+","+_e+" 0,"+65535*360)},_setPath:function(g,S){g._path.v=S},_bringToFront:function(g){fn(g._container)},_bringToBack:function(g){dn(g._container)}},hi=$t.vml?Hn:ke,zn=Mr.extend({_initContainer:function(){this._container=hi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=hi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){ir(this._container),Qt(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Mr.prototype._update.call(this);var g=this._bounds,S=g.getSize(),B=this._container;(!this._svgSize||!this._svgSize.equals(S))&&(this._svgSize=S,B.setAttribute("width",S.x),B.setAttribute("height",S.y)),lr(B,g.min),B.setAttribute("viewBox",[g.min.x,g.min.y,S.x,S.y].join(" ")),this.fire("update")}},_initPath:function(g){var S=g._path=hi("path");g.options.className&&Nt(S,g.options.className),g.options.interactive&&Nt(S,"leaflet-interactive"),this._updateStyle(g),this._layers[u(g)]=g},_addPath:function(g){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(g._path),g.addInteractiveTarget(g._path)},_removePath:function(g){ir(g._path),g.removeInteractiveTarget(g._path),delete this._layers[u(g)]},_updatePath:function(g){g._project(),g._update()},_updateStyle:function(g){var S=g._path,B=g.options;!S||(B.stroke?(S.setAttribute("stroke",B.color),S.setAttribute("stroke-opacity",B.opacity),S.setAttribute("stroke-width",B.weight),S.setAttribute("stroke-linecap",B.lineCap),S.setAttribute("stroke-linejoin",B.lineJoin),B.dashArray?S.setAttribute("stroke-dasharray",B.dashArray):S.removeAttribute("stroke-dasharray"),B.dashOffset?S.setAttribute("stroke-dashoffset",B.dashOffset):S.removeAttribute("stroke-dashoffset")):S.setAttribute("stroke","none"),B.fill?(S.setAttribute("fill",B.fillColor||B.color),S.setAttribute("fill-opacity",B.fillOpacity),S.setAttribute("fill-rule",B.fillRule||"evenodd")):S.setAttribute("fill","none"))},_updatePoly:function(g,S){this._setPath(g,Ne(g._parts,S))},_updateCircle:function(g){var S=g._point,B=Math.max(Math.round(g._radius),1),_e=Math.max(Math.round(g._radiusY),1)||B,Me="a"+B+","+_e+" 0 1,0 ",Ke=g._empty()?"M0 0":"M"+(S.x-B)+","+S.y+Me+B*2+",0 "+Me+-B*2+",0 ";this._setPath(g,Ke)},_setPath:function(g,S){g._path.setAttribute("d",S)},_bringToFront:function(g){fn(g._path)},_bringToBack:function(g){dn(g._path)}});$t.vml&&zn.include(Zo);function zs(g){return $t.svg||$t.vml?new zn(g):null}Vt.include({getRenderer:function(g){var S=g.options.renderer||this._getPaneRenderer(g.options.pane)||this.options.renderer||this._renderer;return S||(S=this._renderer=this._createRenderer()),this.hasLayer(S)||this.addLayer(S),S},_getPaneRenderer:function(g){if(g==="overlayPane"||g===void 0)return!1;var S=this._paneRenderers[g];return S===void 0&&(S=this._createRenderer({pane:g}),this._paneRenderers[g]=S),S},_createRenderer:function(g){return this.options.preferCanvas&&Hs(g)||zs(g)}});var Ws=en.extend({initialize:function(g,S){en.prototype.initialize.call(this,this._boundsToLatLngs(g),S)},setBounds:function(g){return this.setLatLngs(this._boundsToLatLngs(g))},_boundsToLatLngs:function(g){return g=ye(g),[g.getSouthWest(),g.getNorthWest(),g.getNorthEast(),g.getSouthEast()]}});function Qo(g,S){return new Ws(g,S)}zn.create=hi,zn.pointsToPath=Ne,Rr.geometryToLayer=Fn,Rr.coordsToLatLng=zi,Rr.coordsToLatLngs=ai,Rr.latLngToCoords=Wi,Rr.latLngsToCoords=li,Rr.getFeature=zr,Rr.asFeature=tn,Vt.mergeOptions({boxZoom:!0});var js=Ir.extend({initialize:function(g){this._map=g,this._container=g._container,this._pane=g._panes.overlayPane,this._resetStateTimeout=0,g.on("unload",this._destroy,this)},addHooks:function(){Ot(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){Qt(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){ir(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){this._resetStateTimeout!==0&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(g){if(!g.shiftKey||g.which!==1&&g.button!==1)return!1;this._clearDeferredResetState(),this._resetState(),kn(),Pi(),this._startPoint=this._map.mouseEventToContainerPoint(g),Ot(document,{contextmenu:Zr,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(g){this._moved||(this._moved=!0,this._box=Wt("div","leaflet-zoom-box",this._container),Nt(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(g);var S=new Ue(this._point,this._startPoint),B=S.getSize();lr(this._box,S.min),this._box.style.width=B.x+"px",this._box.style.height=B.y+"px"},_finish:function(){this._moved&&(ir(this._box),ar(this._container,"leaflet-crosshair")),Tn(),Ii(),Qt(document,{contextmenu:Zr,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(g){if(!(g.which!==1&&g.button!==1)&&(this._finish(),!!this._moved)){this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(l(this._resetState,this),0);var S=new fe(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point));this._map.fitBounds(S).fire("boxzoomend",{boxZoomBounds:S})}},_onKeyDown:function(g){g.keyCode===27&&(this._finish(),this._clearDeferredResetState(),this._resetState())}});Vt.addInitHook("addHandler","boxZoom",js),Vt.mergeOptions({doubleClickZoom:!0});var Ys=Ir.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(g){var S=this._map,B=S.getZoom(),_e=S.options.zoomDelta,Me=g.originalEvent.shiftKey?B-_e:B+_e;S.options.doubleClickZoom==="center"?S.setZoom(Me):S.setZoomAround(g.containerPoint,Me)}});Vt.addInitHook("addHandler","doubleClickZoom",Ys),Vt.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0});var Gi=Ir.extend({addHooks:function(){if(!this._draggable){var g=this._map;this._draggable=new Vr(g._mapPane,g._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),g.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),g.on("zoomend",this._onZoomEnd,this),g.whenReady(this._onZoomEnd,this))}Nt(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){ar(this._map._container,"leaflet-grab"),ar(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var g=this._map;if(g._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity){var S=ye(this._map.options.maxBounds);this._offsetLimit=Be(this._map.latLngToContainerPoint(S.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(S.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))}else this._offsetLimit=null;g.fire("movestart").fire("dragstart"),g.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(g){if(this._map.options.inertia){var S=this._lastTime=+new Date,B=this._lastPos=this._draggable._absPos||this._draggable._newPos;this._positions.push(B),this._times.push(S),this._prunePositions(S)}this._map.fire("move",g).fire("drag",g)},_prunePositions:function(g){for(;this._positions.length>1&&g-this._times[0]>50;)this._positions.shift(),this._times.shift()},_onZoomEnd:function(){var g=this._map.getSize().divideBy(2),S=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=S.subtract(g).x,this._worldWidth=this._map.getPixelWorldBounds().getSize().x},_viscousLimit:function(g,S){return g-(g-S)*this._viscosity},_onPreDragLimit:function(){if(!(!this._viscosity||!this._offsetLimit)){var g=this._draggable._newPos.subtract(this._draggable._startPos),S=this._offsetLimit;g.xS.max.x&&(g.x=this._viscousLimit(g.x,S.max.x)),g.y>S.max.y&&(g.y=this._viscousLimit(g.y,S.max.y)),this._draggable._newPos=this._draggable._startPos.add(g)}},_onPreDragWrap:function(){var g=this._worldWidth,S=Math.round(g/2),B=this._initialWorldOffset,_e=this._draggable._newPos.x,Me=(_e-S+B)%g+S-B,Ke=(_e+S+B)%g-S-B,lt=Math.abs(Me+B)0?Ke:-Ke))-S;this._delta=0,this._startTime=null,lt&&(g.options.scrollWheelZoom==="center"?g.setZoom(S+lt):g.setZoomAround(this._lastMousePos,S+lt))}});Vt.addInitHook("addHandler","scrollWheelZoom",Ks);var Gs=600;Vt.mergeOptions({tapHold:$t.touchNative&&$t.safari&&$t.mobile,tapTolerance:15});var qs=Ir.extend({addHooks:function(){Ot(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){Qt(this._map._container,"touchstart",this._onDown,this)},_onDown:function(g){if(clearTimeout(this._holdTimeout),g.touches.length===1){var S=g.touches[0];this._startPos=this._newPos=new se(S.clientX,S.clientY),this._holdTimeout=setTimeout(l(function(){this._cancel(),this._isTapValid()&&(Ot(document,"touchend",ur),Ot(document,"touchend touchcancel",this._cancelClickPrevent),this._simulateEvent("contextmenu",S))},this),Gs),Ot(document,"touchend touchcancel contextmenu",this._cancel,this),Ot(document,"touchmove",this._onMove,this)}},_cancelClickPrevent:function g(){Qt(document,"touchend",ur),Qt(document,"touchend touchcancel",g)},_cancel:function(){clearTimeout(this._holdTimeout),Qt(document,"touchend touchcancel contextmenu",this._cancel,this),Qt(document,"touchmove",this._onMove,this)},_onMove:function(g){var S=g.touches[0];this._newPos=new se(S.clientX,S.clientY)},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_simulateEvent:function(g,S){var B=new MouseEvent(g,{bubbles:!0,cancelable:!0,view:window,screenX:S.screenX,screenY:S.screenY,clientX:S.clientX,clientY:S.clientY});B._simulated=!0,S.target.dispatchEvent(B)}});Vt.addInitHook("addHandler","tapHold",qs),Vt.mergeOptions({touchZoom:$t.touch,bounceAtZoomLimits:!0});var Xs=Ir.extend({addHooks:function(){Nt(this._map._container,"leaflet-touch-zoom"),Ot(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){ar(this._map._container,"leaflet-touch-zoom"),Qt(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(g){var S=this._map;if(!(!g.touches||g.touches.length!==2||S._animatingZoom||this._zooming)){var B=S.mouseEventToContainerPoint(g.touches[0]),_e=S.mouseEventToContainerPoint(g.touches[1]);this._centerPoint=S.getSize()._divideBy(2),this._startLatLng=S.containerPointToLatLng(this._centerPoint),S.options.touchZoom!=="center"&&(this._pinchStartLatLng=S.containerPointToLatLng(B.add(_e)._divideBy(2))),this._startDist=B.distanceTo(_e),this._startZoom=S.getZoom(),this._moved=!1,this._zooming=!0,S._stop(),Ot(document,"touchmove",this._onTouchMove,this),Ot(document,"touchend touchcancel",this._onTouchEnd,this),ur(g)}},_onTouchMove:function(g){if(!(!g.touches||g.touches.length!==2||!this._zooming)){var S=this._map,B=S.mouseEventToContainerPoint(g.touches[0]),_e=S.mouseEventToContainerPoint(g.touches[1]),Me=B.distanceTo(_e)/this._startDist;if(this._zoom=S.getScaleZoom(Me,this._startZoom),!S.options.bounceAtZoomLimits&&(this._zoomS.getMaxZoom()&&Me>1)&&(this._zoom=S._limitZoom(this._zoom)),S.options.touchZoom==="center"){if(this._center=this._startLatLng,Me===1)return}else{var Ke=B._add(_e)._divideBy(2)._subtract(this._centerPoint);if(Me===1&&Ke.x===0&&Ke.y===0)return;this._center=S.unproject(S.project(this._pinchStartLatLng,this._zoom).subtract(Ke),this._zoom)}this._moved||(S._moveStart(!0,!1),this._moved=!0),he(this._animRequest);var lt=l(S._move,S,this._center,this._zoom,{pinch:!0,round:!1},void 0);this._animRequest=ee(lt,this,!0),ur(g)}},_onTouchEnd:function(){if(!this._moved||!this._zooming){this._zooming=!1;return}this._zooming=!1,he(this._animRequest),Qt(document,"touchmove",this._onTouchMove,this),Qt(document,"touchend touchcancel",this._onTouchEnd,this),this._map.options.zoomAnimation?this._map._animateZoom(this._center,this._map._limitZoom(this._zoom),!0,this._map.options.zoomSnap):this._map._resetView(this._center,this._map._limitZoom(this._zoom))}});Vt.addInitHook("addHandler","touchZoom",Xs),Vt.BoxZoom=js,Vt.DoubleClickZoom=Ys,Vt.Drag=Gi,Vt.Keyboard=qi,Vt.ScrollWheelZoom=Ks,Vt.TapHold=qs,Vt.TouchZoom=Xs,r.Bounds=Ue,r.Browser=$t,r.CRS=Fe,r.Canvas=Vs,r.Circle=Bn,r.CircleMarker=si,r.Class=xe,r.Control=Cr,r.DivIcon=ui,r.DivOverlay=Lr,r.DomEvent=Io,r.DomUtil=Po,r.Draggable=Vr,r.Evented=ge,r.FeatureGroup=Jr,r.GeoJSON=Rr,r.GridLayer=Vn,r.Handler=Ir,r.Icon=mn,r.ImageOverlay=gn,r.LatLng=Ce,r.LatLngBounds=fe,r.Layer=kr,r.LayerGroup=pn,r.LineUtil=As,r.Map=Vt,r.Marker=Nn,r.Mixin=Oo,r.Path=Hr,r.Point=se,r.PolyUtil=Ps,r.Polygon=en,r.Polyline=$r,r.Popup=rn,r.PosAnimation=ps,r.Projection=Fo,r.Rectangle=Ws,r.Renderer=Mr,r.SVG=zn,r.SVGOverlay=ji,r.TileLayer=nn,r.Tooltip=ci,r.Transformation=Ie,r.Util=ne,r.VideoOverlay=Bs,r.bind=l,r.bounds=Be,r.canvas=Hs,r.circle=Ms,r.circleMarker=zo,r.control=$n,r.divIcon=Go,r.extend=o,r.featureGroup=Vo,r.geoJSON=Ns,r.geoJson=Wo,r.gridLayer=qo,r.icon=Ho,r.imageOverlay=jo,r.latLng=Le,r.latLngBounds=ye,r.layerGroup=Uo,r.map=gs,r.marker=Rs,r.point=Pe,r.polygon=oi,r.polyline=Os,r.popup=Ko,r.rectangle=Qo,r.setOptions=T,r.stamp=u,r.svg=zs,r.svgOverlay=Yi,r.tileLayer=Ki,r.tooltip=Fs,r.transformation=we,r.version=n,r.videoOverlay=Yo;var sn=window.L;r.noConflict=function(){return window.L=sn,this},window.L=r})})(leafletSrc,leafletSrc.exports);const L$2=leafletSrc.exports;(function(e){typeof e>"u"&&(e={getCenter:L.Map.prototype.getCenter,setView:L.Map.prototype.setView,flyTo:L.Map.prototype.flyTo,setZoomAround:L.Map.prototype.setZoomAround,getBoundsZoom:L.Map.prototype.getBoundsZoom,PopupAdjustPan:L.Popup.prototype._adjustPan,RendererUpdate:L.Renderer.prototype._update}),L.Map.include({getBounds:function(){if(this._viewport)return this.getViewportLatLngBounds();var t=this.getPixelBounds(),r=this.unproject(t.getBottomLeft()),n=this.unproject(t.getTopRight());return new L.LatLngBounds(r,n)},getViewport:function(){return this._viewport},getViewportBounds:function(){var t=this._viewport,r=L.point(t.offsetLeft,t.offsetTop),n=L.point(t.clientWidth,t.clientHeight);return(n.x===0||n.y===0)&&(t=this.getContainer(),t&&(r=L.point(0,0),n=L.point(t.clientWidth,t.clientHeight))),L.bounds(r,r.add(n))},getViewportLatLngBounds:function(){var t=this.getViewportBounds();return L.latLngBounds(this.containerPointToLatLng(t.min),this.containerPointToLatLng(t.max))},getOffset:function(){var t=this.getSize().divideBy(2),r=this.getViewportBounds().getCenter();return t.subtract(r)},getCenter:function(t){var r=e.getCenter.call(this);if(this.getViewport()&&!t){var n=this.getZoom(),o=this.project(r,n);o=o.subtract(this.getOffset()),r=this.unproject(o,n)}return r},setView:function(t,r,n){if(t=L.latLng(t),r=r===void 0?this._zoom:this._limitZoom(r),this.getViewport()){var o=this.project(t,this._limitZoom(r));o=o.add(this.getOffset()),t=this.unproject(o,this._limitZoom(r))}return e.setView.call(this,t,r,n)},flyTo:function(t,r,n){if(t=L.latLng(t),r=r===void 0?u:r,this.getViewport()){var o=this.project(t,this._limitZoom(r));o=o.add(this.getOffset()),t=this.unproject(o,this._limitZoom(r))}if(n=n||{},n.animate===!1||!L.Browser.any3d)return this.setView(t,r,n);this._stop();var a=this.project(e.getCenter.call(this)),l=this.project(t),c=this.getSize(),u=this._zoom,_=Math.max(c.x,c.y),b=_*this.getZoomScale(u,r),x=l.distanceTo(a)||1,E=1.42,I=E*E;function k(ve){var ee=ve?-1:1,he=ve?b:_,ne=b*b-_*_+ee*I*I*x*x,xe=2*he*I*x,te=ne/xe,ae=Math.sqrt(te*te+1)-te,ge=ae<1e-9?-18:Math.log(ae);return ge}function T(ve){return(Math.exp(ve)-Math.exp(-ve))/2}function O(ve){return(Math.exp(ve)+Math.exp(-ve))/2}function $(ve){return T(ve)/O(ve)}var D=k(0);function N(ve){return _*(O(D)/O(D+E*ve))}function H(ve){return _*(O(D)*$(D+E*ve)-T(D))/I}function ie(ve){return 1-Math.pow(1-ve,1.5)}var ue=Date.now(),de=(k(1)-D)/E,le=n.duration?1e3*n.duration:1e3*de*.8;function ce(){var ve=(Date.now()-ue)/le,ee=ie(ve)*de;ve<=1?(this._flyToFrame=L.Util.requestAnimFrame(ce,this),this._move(this.unproject(a.add(l.subtract(a).multiplyBy(H(ee)/x)),u),this.getScaleZoom(_/N(ee),u),{flyTo:!0})):this._move(t,r)._moveEnd(!0)}return this._moveStart(!0,n.noMoveStart),ce.call(this),this},setZoomAround:function(t,r,n){var o=this.getViewport();if(o){var a=this.getZoomScale(r),l=this.getViewportBounds().getCenter(),c=t instanceof L.Point?t:this.latLngToContainerPoint(t),u=c.subtract(l).multiplyBy(1-1/a),_=this.containerPointToLatLng(l.add(u));return this.setView(_,r,{zoom:n})}else return e.setZoomAround.call(this,t,r,n)},getBoundsZoom:function(t,r,n){t=L.latLngBounds(t),n=L.point(n||[0,0]);var o=this.getZoom()||0,a=this.getMinZoom(),l=this.getMaxZoom(),c=t.getNorthWest(),u=t.getSouthEast(),_=this.getViewport(),b=(_?L.point(_.clientWidth,_.clientHeight):this.getSize()).subtract(n),x=this.project(u,o).subtract(this.project(c,o)),E=L.Browser.any3d?this.options.zoomSnap:1,I=b.x/x.x,k=b.y/x.y,T=r?Math.max(I,k):Math.min(I,k);return o=this.getScaleZoom(T,o),E&&(o=Math.round(o/(E/100))*(E/100),o=r?Math.ceil(o/E)*E:Math.floor(o/E)*E),Math.max(a,Math.min(l,o))},setActiveArea:function(t,r,n){var o;if(r&&this._zoom&&(o=this.getCenter()),!this._viewport){var a=this.getContainer();this._viewport=L.DomUtil.create("div",""),a.insertBefore(this._viewport,a.firstChild)}return typeof t=="string"?this._viewport.className=t:L.extend(this._viewport.style,t),o&&this.setView(o,this.getZoom(),{animate:!!n}),this}}),L.Renderer.include({_onZoom:function(){this._updateTransform(this._map.getCenter(!0),this._map.getZoom())},_update:function(){e.RendererUpdate.call(this),this._center=this._map.getCenter(!0)}}),L.GridLayer.include({_updateLevels:function(){var t=this._tileZoom,r=this.options.maxZoom;if(t!==void 0){for(var n in this._levels)n=Number(n),this._levels[n].el.children.length||n===t?(this._levels[n].el.style.zIndex=r-Math.abs(t-n),this._onUpdateLevel(n)):(L.DomUtil.remove(this._levels[n].el),this._removeTilesAtZoom(n),this._onRemoveLevel(n),delete this._levels[n]);var o=this._levels[t],a=this._map;return o||(o=this._levels[t]={},o.el=L.DomUtil.create("div","leaflet-tile-container leaflet-zoom-animated",this._container),o.el.style.zIndex=r,o.origin=a.project(a.unproject(a.getPixelOrigin()),t).round(),o.zoom=t,this._setZoomTransform(o,a.getCenter(!0),a.getZoom()),L.Util.falseFn(o.el.offsetWidth),this._onCreateLevel(o)),this._level=o,o}},_resetView:function(t){var r=t&&(t.pinch||t.flyTo);this._setView(this._map.getCenter(!0),this._map.getZoom(),r,r)},_update:function(t){var r=this._map;if(!!r){var n=this._clampZoom(r.getZoom());if(t===void 0&&(t=r.getCenter(!0)),this._tileZoom!==void 0){var o=this._getTiledPixelBounds(t),a=this._pxBoundsToTileRange(o),l=a.getCenter(),c=[],u=this.options.keepBuffer,_=new L.Bounds(a.getBottomLeft().subtract([u,-u]),a.getTopRight().add([u,-u]));if(!(isFinite(a.min.x)&&isFinite(a.min.y)&&isFinite(a.max.x)&&isFinite(a.max.y)))throw new Error("Attempted to load an infinite number of tiles");for(var b in this._tiles){var x=this._tiles[b].coords;(x.z!==this._tileZoom||!_.contains(new L.Point(x.x,x.y)))&&(this._tiles[b].current=!1)}if(Math.abs(n-this._tileZoom)>1){this._setView(t,n);return}for(var E=a.min.y;E<=a.max.y;E++)for(var I=a.min.x;I<=a.max.x;I++){var k=new L.Point(I,E);if(k.z=this._tileZoom,!!this._isValidTile(k)){var T=this._tiles[this._tileCoordsToKey(k)];T?T.current=!0:c.push(k)}}if(c.sort(function($,D){return $.distanceTo(l)-D.distanceTo(l)}),c.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var O=document.createDocumentFragment();for(I=0;Ix.x&&(E=c.x+o-x.x+b.x),c.x-E-_.x<0&&(E=c.x-_.x),c.y+n+b.y>x.y&&(I=c.y+n-x.y+b.y),c.y-I-_.y<0&&(I=c.y-_.y),(E||I)&&t.fire("autopanstart").panBy([E,I])}}})})(window.leafletActiveAreaPreviousMethods);L.TileLayer.ColorFilter=L.TileLayer.extend({intialize:function(e,t){L.TileLayer.prototype.initialize.call(this,e,t)},colorFilter:function(){var e=["blur:px","brightness:%","bright:brightness:%","bri:brightness:%","contrast:%","con:contrast:%","grayscale:%","gray:grayscale:%","hue-rotate:deg","hue:hue-rotate:deg","hue-rotation:hue-rotate:deg","invert:%","inv:invert:%","opacity:%","op:opacity:%","saturate:%","saturation:saturate:%","sat:saturate:%","sepia:%","sep:sepia:%"];return(this.options.filter?this.options.filter:[]).map(function(t){var r=t.toLowerCase().split(":");if(r.length===2){var n=e.find(function(o){return o.split(":")[0]===r[0]});if(n)return n=n.split(":"),r[1]+=/^\d+$/.test(r[1])?n[n.length-1]:"","".concat(n[n.length-2],"(").concat(r[1],")")}return""}).join(" ")},_initContainer:function(){L.TileLayer.prototype._initContainer.call(this),this._container.style.filter=this.colorFilter()},updateFilter:function(e){this.options.filter=e,this._container&&(this._container.style.filter=this.colorFilter())}}),L.tileLayer.colorFilter=function(e,t){return new L.TileLayer.ColorFilter(e,t)};const leaflet="";let map$3,usermarker;const attrs$1={attribution:'© OpenStreetMap contributors'},layerMapLight=L$2.tileLayer.colorFilter("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{...attrs$1,filter:["grayscale:50%","saturate:70%"]}),layerMapDark=L$2.tileLayer.colorFilter("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{...attrs$1,filter:["invert:100%","grayscale:100%","bright:100%","saturate:0%","sepia:10%"]});function instanceMap(){if(map$3)return map$3;throw new Error("Must be initialized before using the mapd.")}function removeMap(){map$3.remove(),map$3=void 0}function init$3(e,t,r="light"){return map$3=L$2.map("map",{minZoom:3}),setTheme(r),map$3.attributionControl.setPrefix(""),map$3.setView(e,t),map$3.zoomControl.remove(),map$3}function setTheme(e){const t=instanceMap();e==="light"?(t.removeLayer(layerMapDark),t.addLayer(layerMapLight)):(t.removeLayer(layerMapLight),t.addLayer(layerMapDark))}function setview(e,t){const r=instanceMap();r&&r.setView(e,t)}function drawuser(e,t){const r=instanceMap();let n=100;r&&(usermarker&&r.removeLayer(usermarker),t>0&&(n=10*t),t>4&&(n=5*t),t>7&&(n=2*t),usermarker=new L$2.circleMarker(e,{radius:n,opacity:.2}),usermarker.addTo(r))}const scriptRel="modulepreload",assetsURL=function(e){return"/"+e},seen={},__vitePreload=function(t,r,n){if(!r||r.length===0)return t();const o=document.getElementsByTagName("link");return Promise.all(r.map(a=>{if(a=assetsURL(a),a in seen)return;seen[a]=!0;const l=a.endsWith(".css"),c=l?'[rel="stylesheet"]':"";if(!!n)for(let b=o.length-1;b>=0;b--){const x=o[b];if(x.href===a&&(!l||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${c}`))return;const _=document.createElement("link");if(_.rel=l?"stylesheet":scriptRel,l||(_.as="script",_.crossOrigin=""),_.href=a,document.head.appendChild(_),l)return new Promise((b,x)=>{_.addEventListener("load",b),_.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${a}`)))})})).then(()=>t())},__variableDynamicImportRuntimeHelper=(e,t)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t)))})};function Queue(e){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:l},next:{enumerable:!0,writable:!1,value:c},clear:{enumerable:!0,writable:!1,value:n},contents:{enumerable:!1,get:o,set:a},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var t=[],r=!1;function n(){return t=[],t}function o(){return t}function a(u){return t=u,t}function l(){for(var u in arguments)t.push(arguments[u]);!r&&!this.stop&&this.autoRun&&this.next()}function c(){if(r=!0,t.length<1||this.stop){r=!1;return}t.shift().bind(this)()}}var queue$1=Queue,leaflet_geometryutil={exports:{}};(function(e){(function(t){var r;r=leafletSrc.exports,e.exports=t(r)})(function(t){return t.Polyline._flat=t.LineUtil.isFlat||t.Polyline._flat||function(r){return!t.Util.isArray(r[0])||typeof r[0][0]!="object"&&typeof r[0][0]<"u"},t.GeometryUtil=t.extend(t.GeometryUtil||{},{distance:function(r,n,o){return r.latLngToLayerPoint(n).distanceTo(r.latLngToLayerPoint(o))},distanceSegment:function(r,n,o,a){var l=r.latLngToLayerPoint(n),c=r.latLngToLayerPoint(o),u=r.latLngToLayerPoint(a);return t.LineUtil.pointToSegmentDistance(l,c,u)},readableDistance:function(r,n){var o=n!=="imperial",a;return o?r>1e3?a=(r/1e3).toFixed(2)+" km":a=r.toFixed(1)+" m":(r*=1.09361,r>1760?a=(r/1760).toFixed(2)+" miles":a=r.toFixed(1)+" yd"),a},belongsSegment:function(r,n,o,a){a=a===void 0?.2:a;var l=n.distanceTo(o),c=n.distanceTo(r)+r.distanceTo(o)-l;return c/l0?n[n.length-1]:0},accumulatedLengths:function(r){if(typeof r.getLatLngs=="function"&&(r=r.getLatLngs()),r.length===0)return[];for(var n=0,o=[0],a=0,l=r.length-1;aa?l.slice(0,a):l},layersWithin:function(r,n,o,a){a=typeof a=="number"?a:1/0;for(var l=[],c=null,u=0,_=0,b=n.length;_a)return null;if(l&&typeof c.layer.getLatLngs=="function"){var u=t.GeometryUtil.closest(r,c.layer,c.latlng,!0);u.distance0&&(u+=c[_-1].distanceTo(c[_]));for(var b=u*o,x=0,E=0,_=0;Ea)return t.GeometryUtil.extract(r,t.GeometryUtil.reverse(n),1-o,1-a);o=Math.max(Math.min(o,1),0),a=Math.max(Math.min(a,1),0);var l=n.getLatLngs(),c=t.GeometryUtil.interpolateOnLine(r,n,o),u=t.GeometryUtil.interpolateOnLine(r,n,a);if(o==a){var _=t.GeometryUtil.interpolateOnLine(r,n,a);return[_.latLng]}c.predecessor==-1&&(c.predecessor=0),u.predecessor==-1&&(u.predecessor=0);var b=l.slice(c.predecessor+1,u.predecessor+1);return b.unshift(c.latLng),b.push(u.latLng),b},isBefore:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs();return o[o.length-1].equals(a[0])},isAfter:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs();return o[0].equals(a[a.length-1])},startsAtExtremity:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs(),l=o[0];return l.equals(a[0])||l.equals(a[a.length-1])},computeAngle:function(r,n){return Math.atan2(n.y-r.y,n.x-r.x)*180/Math.PI},computeSlope:function(r,n){var o=(n.y-r.y)/(n.x-r.x),a=r.y-o*r.x;return{a:o,b:a}},rotatePoint:function(r,n,o,a){var l=r.getMaxZoom();l===1/0&&(l=r.getZoom());var c=o*Math.PI/180,u=r.project(n,l),_=r.project(a,l),b=Math.cos(c)*(u.x-_.x)-Math.sin(c)*(u.y-_.y)+_.x,x=Math.sin(c)*(u.x-_.x)+Math.cos(c)*(u.y-_.y)+_.y;return r.unproject(new t.Point(b,x),l)},bearing:function(r,n){var o=Math.PI/180,a=r.lat*o,l=n.lat*o,c=r.lng*o,u=n.lng*o,_=Math.sin(u-c)*Math.cos(l),b=Math.cos(a)*Math.sin(l)-Math.sin(a)*Math.cos(l)*Math.cos(u-c),x=(Math.atan2(_,b)*180/Math.PI+360)%360;return x>=180?x-360:x},destination:function(r,n,o){n=(n+360)%360;var a=Math.PI/180,l=180/Math.PI,c=6378137,u=r.lng*a,_=r.lat*a,b=n*a,x=Math.sin(_),E=Math.cos(_),I=Math.cos(o/c),k=Math.sin(o/c),T=Math.asin(x*I+E*k*Math.cos(b)),O=u+Math.atan2(Math.sin(b)*k*E,I-x*Math.sin(T));return O=O*l,O=O>180?O-360:O<-180?O+360:O,t.latLng([T*l,O])},angle:function(r,n,o){var a=r.latLngToContainerPoint(n),l=r.latLngToContainerPoint(o),c=Math.atan2(l.y-a.y,l.x-a.x)*180/Math.PI+90;return c+=c<0?360:0,c},destinationOnSegment:function(r,n,o,a){var l=t.GeometryUtil.angle(r,n,o),c=t.GeometryUtil.destination(n,l,a);return t.GeometryUtil.closestOnSegment(r,c,n,o)}}),t.GeometryUtil})})(leaflet_geometryutil);function modulus(e,t){return(e%t+t)%t}function definedProps(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r!==void 0))}function isInMeters(e){return e.toString().trim().slice(e.toString().length-1,e.toString().length)==="m"}function isInPercent(e){return e.toString().trim().slice(e.toString().length-1,e.toString().length)==="%"}function isInPixels(e){return e.toString().trim().slice(e.toString().length-2,e.toString().length)==="px"}function pixelsToMeters(e,t){let r=t.getCenter(),n=t.latLngToLayerPoint(r),o={x:n.x+Number(e),y:n.y},a=t.layerPointToLatLng(o);return t.distance(r,a)}L.Polyline.include({arrowheads:function(e={}){const t={yawn:60,size:"15%",frequency:"allvertices",proportionalToTotal:!1};this.options.noClip=!0;let r=Object.assign({},t,e);return this._arrowheadOptions=r,this._hatsApplied=!0,this},buildVectorHats:function(e){this._arrowheads&&this._arrowheads.remove(),this._ghosts&&this._ghosts.remove();let t=Object.getPrototypeOf(Object.getPrototypeOf(this.options)),r=Object.assign({},t,this.options),n=Object.assign({},r,e);n.smoothFactor=1,n.fillOpacity=1,n.fill=!!e.fill,n.interactive=!1;let o=e.size.toString(),a=[];const{frequency:l,offsets:c}=e;(c?.start||c?.end)&&this._buildGhosts({start:c.start,end:c.end}),(this._ghosts||this)._parts.forEach((b,x)=>{const E=b.map(ue=>this._map.layerPointToLatLng(ue)),I=(()=>{let ue=0;for(var de=0;de{let ue=l.slice(0,l.length-2);return pixelsToMeters(ue,this._map)/I})(),$=1/O,$=Math.floor($),O=1/$):(O=1/l,$=l),e.frequency==="allvertices")T=(()=>{let ue=[];for(var de=1;de=2)k=[E[E.length-1]],T=[L.GeometryUtil.angle(this._map,E[E.length-2],E[E.length-1])+180];else{k=[];let ue=[];for(var D=0;D<$;D++){let de=L.GeometryUtil.interpolateOnLine(this._map,E,O*(D+1));de&&(ue.push(de),k.push(de.latLng))}T=(()=>{let de=[];for(var le=0;le{let le=de.yawn??e.yawn,ce=L.GeometryUtil.destination(k[D],T[D]-le/2,ue),ve=L.GeometryUtil.destination(k[D],T[D]+le/2,ue),ee=[[ce.lat,ce.lng],[k[D].lat,k[D].lng],[ve.lat,ve.lng]],he=e.fill?L.polygon(ee,{...n,...de}):L.polyline(ee,{...n,...de});N.push(he)},ie=(ue,de={})=>{let le=ue.slice(0,ue.length-2),ce=de.yawn??e.yawn,ve=this._map.latLngToLayerPoint(k[D]),ee=T[D],he=(180-ee-ce/2)*(Math.PI/180),ne=(180-ee+ce/2)*(Math.PI/180),xe=le*Math.sin(he),te=le*Math.cos(he),ae=le*Math.sin(ne),ge=le*Math.cos(ne),se={x:ve.x+xe,y:ve.y+te},Se={x:ve.x+ae,y:ve.y+ge},Pe=this._map.layerPointToLatLng(se),Ue=this._map.layerPointToLatLng(Se),Be=[[Pe.lat,Pe.lng],[k[D].lat,k[D].lng],[Ue.lat,Ue.lng]],fe=e.fill?L.polygon(Be,{...n,...de}):L.polyline(Be,{...n,...de});N.push(fe)};for(var D=0;De.frequency==="endonly"&&e.proportionalToTotal?I*ce/100:I/(b.length-1)*ce/100)();H(ve,de)}else isInPixels(o)?ie(e.size,de):console.error("Error: Arrowhead size unit not defined. Check your arrowhead options.")}a.push(...N)});let _=L.layerGroup(a);return this._arrowheads=_,this},getArrowheads:function(){return this._arrowheads?this._arrowheads:console.error("Error: You tried to call '.getArrowheads() on a shape that does not have a arrowhead. Use '.arrowheads()' to add a arrowheads before trying to call '.getArrowheads()'")},_buildGhosts:function({start:e,end:t}){if(e||t){let r=this.getLatLngs();r=Array.isArray(r[0])?r:[r];const n=r.map(o=>{const a=(()=>{let l=0;for(var c=0;c{if(isInMeters(e))return Number(e.slice(0,e.length-1));if(isInPixels(e)){let u=Number(e.slice(0,e.length-2));return pixelsToMeters(u,this._map)}})(),c=L.GeometryUtil.interpolateOnLine(this._map,o,l/a);o=o.slice(c.predecessor===-1?1:c.predecessor+1,o.length),o.unshift(c.latLng)}if(t){let l=(()=>{if(isInMeters(t))return Number(t.slice(0,t.length-1));if(isInPixels(t)){let u=Number(t.slice(0,t.length-2));return pixelsToMeters(u,this._map)}})(),c=L.GeometryUtil.interpolateOnLine(this._map,o,(a-l)/a);o=o.slice(0,c.predecessor+1),o.push(c.latLng)}return o});this._ghosts=L.polyline(n,{...this.options,color:"rgba(0,0,0,0)",stroke:0,smoothFactor:0,interactive:!1}),this._ghosts.addTo(this._map)}},deleteArrowheads:function(){this._arrowheads&&(this._arrowheads.remove(),delete this._arrowheads,delete this._arrowheadOptions,this._hatsApplied=!1),this._ghosts&&this._ghosts.remove()},_update:function(){!this._map||(this._clipPoints(),this._simplifyPoints(),this._updatePath(),this._hatsApplied&&(this.buildVectorHats(this._arrowheadOptions),this._map.addLayer(this._arrowheads)))},remove:function(){return this._arrowheads&&this._arrowheads.remove(),this._ghosts&&this._ghosts.remove(),this.removeFrom(this._map||this._mapToAdd)}});L.LayerGroup.include({removeLayer:function(e){var t=e in this._layers?e:this.getLayerId(e);return this._map&&this._layers[t]&&(this._layers[t]._arrowheads&&this._layers[t]._arrowheads.remove(),this._map.removeLayer(this._layers[t])),delete this._layers[t],this},onRemove:function(e,t){for(var t in this._layers)this._layers[t]&&this._layers[t].remove();this.eachLayer(e.removeLayer,e)}});L.Map.include({removeLayer:function(e){var t=L.Util.stamp(e);return e._arrowheads&&e._arrowheads.remove(),e._ghosts&&e._ghosts.remove(),this._layers[t]?(this._loaded&&e.onRemove(this),e.getAttribution&&this.attributionControl&&this.attributionControl.removeAttribution(e.getAttribution()),delete this._layers[t],this._loaded&&(this.fire("layerremove",{layer:e}),e.fire("remove")),e._map=e._mapToAdd=null,this):this}});L.GeoJSON.include({geometryToLayer:function(e,t){var r=e.type==="Feature"?e.geometry:e,n=r?r.coordinates:null,o=[],a=t&&t.pointToLayer,l=t&&t.coordsToLatLng||L.GeoJSON.coordsToLatLng,c,u,_,b;if(!n&&!r)return null;switch(r.type){case"Point":return c=l(n),this._pointToLayer(a,e,c,t);case"MultiPoint":for(_=0,b=n.length;_=c;)l=l.__parent;return this._currentShownBounds.contains(l.getLatLng())&&(this.options.animateAddingMarkers?this._animationAddLayer(a,l):this._animationAddLayerNonAnimated(a,l)),this},removeLayer:function(a){return a instanceof L.LayerGroup?this.removeLayers([a]):a.getLatLng?this._map?a.__parent?(this._unspiderfy&&(this._unspiderfy(),this._unspiderfyLayer(a)),this._removeLayer(a,!0),this.fire("layerremove",{layer:a}),this._topClusterLevel._recalculateBounds(),this._refreshClustersIcons(),a.off(this._childMarkerEventHandlers,this),this._featureGroup.hasLayer(a)&&(this._featureGroup.removeLayer(a),a.clusterShow&&a.clusterShow()),this):this:(!this._arraySplice(this._needsClustering,a)&&this.hasLayer(a)&&this._needsRemoving.push({layer:a,latlng:a._latlng}),this.fire("layerremove",{layer:a}),this):(this._nonPointGroup.removeLayer(a),this.fire("layerremove",{layer:a}),this)},addLayers:function(a,l){if(!L.Util.isArray(a))return this.addLayer(a);var c=this._featureGroup,u=this._nonPointGroup,_=this.options.chunkedLoading,b=this.options.chunkInterval,x=this.options.chunkProgress,E=a.length,I=0,k=!0,T;if(this._map){var O=new Date().getTime(),$=L.bind(function(){var N=new Date().getTime();for(this._map&&this._unspiderfy&&this._unspiderfy();Ib)break}if(T=a[I],T instanceof L.LayerGroup){k&&(a=a.slice(),k=!1),this._extractNonGroupLayers(T,a),E=a.length;continue}if(!T.getLatLng){u.addLayer(T),l||this.fire("layeradd",{layer:T});continue}if(!this.hasLayer(T)&&(this._addLayer(T,this._maxZoom),l||this.fire("layeradd",{layer:T}),T.__parent&&T.__parent.getChildCount()===2)){var ie=T.__parent.getAllChildMarkers(),ue=ie[0]===T?ie[1]:ie[0];c.removeLayer(ue)}}x&&x(I,E,new Date().getTime()-O),I===E?(this._topClusterLevel._recalculateBounds(),this._refreshClustersIcons(),this._topClusterLevel._recursivelyAddChildrenToMap(null,this._zoom,this._currentShownBounds)):setTimeout($,this.options.chunkDelay)},this);$()}else for(var D=this._needsClustering;I=0;l--)a.extend(this._needsClustering[l].getLatLng());return a.extend(this._nonPointGroup.getBounds()),a},eachLayer:function(a,l){var c=this._needsClustering.slice(),u=this._needsRemoving,_,b,x;for(this._topClusterLevel&&this._topClusterLevel.getAllChildMarkers(c),b=c.length-1;b>=0;b--){for(_=!0,x=u.length-1;x>=0;x--)if(u[x].layer===c[b]){_=!1;break}_&&a.call(l,c[b])}this._nonPointGroup.eachLayer(a,l)},getLayers:function(){var a=[];return this.eachLayer(function(l){a.push(l)}),a},getLayer:function(a){var l=null;return a=parseInt(a,10),this.eachLayer(function(c){L.stamp(c)===a&&(l=c)}),l},hasLayer:function(a){if(!a)return!1;var l,c=this._needsClustering;for(l=c.length-1;l>=0;l--)if(c[l]===a)return!0;for(c=this._needsRemoving,l=c.length-1;l>=0;l--)if(c[l].layer===a)return!1;return!!(a.__parent&&a.__parent._group===this)||this._nonPointGroup.hasLayer(a)},zoomToShowLayer:function(a,l){var c=this._map;typeof l!="function"&&(l=function(){});var u=function(){(c.hasLayer(a)||c.hasLayer(a.__parent))&&!this._inZoomAnimation&&(this._map.off("moveend",u,this),this.off("animationend",u,this),c.hasLayer(a)?l():a.__parent._icon&&(this.once("spiderfied",l,this),a.__parent.spiderfy()))};a._icon&&this._map.getBounds().contains(a.getLatLng())?l():a.__parent._zoom=0;c--)if(a[c]===l)return a.splice(c,1),!0},_removeFromGridUnclustered:function(a,l){for(var c=this._map,u=this._gridUnclustered,_=Math.floor(this._map.getMinZoom());l>=_&&u[l].removeObject(a,c.project(a.getLatLng(),l));l--);},_childMarkerDragStart:function(a){a.target.__dragStart=a.target._latlng},_childMarkerMoved:function(a){if(!this._ignoreMove&&!a.target.__dragStart){var l=a.target._popup&&a.target._popup.isOpen();this._moveChild(a.target,a.oldLatLng,a.latlng),l&&a.target.openPopup()}},_moveChild:function(a,l,c){a._latlng=l,this.removeLayer(a),a._latlng=c,this.addLayer(a)},_childMarkerDragEnd:function(a){var l=a.target.__dragStart;delete a.target.__dragStart,l&&this._moveChild(a.target,l,a.target._latlng)},_removeLayer:function(a,l,c){var u=this._gridClusters,_=this._gridUnclustered,b=this._featureGroup,x=this._map,E=Math.floor(this._map.getMinZoom());l&&this._removeFromGridUnclustered(a,this._maxZoom);var I=a.__parent,k=I._markers,T;for(this._arraySplice(k,a);I&&(I._childCount--,I._boundsNeedUpdate=!0,!(I._zoom"+l+"",className:"marker-cluster"+c,iconSize:new L.Point(40,40)})},_bindEvents:function(){var a=this._map,l=this.options.spiderfyOnMaxZoom,c=this.options.showCoverageOnHover,u=this.options.zoomToBoundsOnClick,_=this.options.spiderfyOnEveryZoom;(l||u||_)&&this.on("clusterclick clusterkeypress",this._zoomOrSpiderfy,this),c&&(this.on("clustermouseover",this._showCoverage,this),this.on("clustermouseout",this._hideCoverage,this),a.on("zoomend",this._hideCoverage,this))},_zoomOrSpiderfy:function(a){var l=a.layer,c=l;if(!(a.type==="clusterkeypress"&&a.originalEvent&&a.originalEvent.keyCode!==13)){for(;c._childClusters.length===1;)c=c._childClusters[0];c._zoom===this._maxZoom&&c._childCount===l._childCount&&this.options.spiderfyOnMaxZoom?l.spiderfy():this.options.zoomToBoundsOnClick&&l.zoomToBounds(),this.options.spiderfyOnEveryZoom&&l.spiderfy(),a.originalEvent&&a.originalEvent.keyCode===13&&this._map._container.focus()}},_showCoverage:function(a){var l=this._map;this._inZoomAnimation||(this._shownPolygon&&l.removeLayer(this._shownPolygon),a.layer.getChildCount()>2&&a.layer!==this._spiderfied&&(this._shownPolygon=new L.Polygon(a.layer.getConvexHull(),this.options.polygonOptions),l.addLayer(this._shownPolygon)))},_hideCoverage:function(){this._shownPolygon&&(this._map.removeLayer(this._shownPolygon),this._shownPolygon=null)},_unbindEvents:function(){var a=this.options.spiderfyOnMaxZoom,l=this.options.showCoverageOnHover,c=this.options.zoomToBoundsOnClick,u=this.options.spiderfyOnEveryZoom,_=this._map;(a||c||u)&&this.off("clusterclick clusterkeypress",this._zoomOrSpiderfy,this),l&&(this.off("clustermouseover",this._showCoverage,this),this.off("clustermouseout",this._hideCoverage,this),_.off("zoomend",this._hideCoverage,this))},_zoomEnd:function(){!this._map||(this._mergeSplitClusters(),this._zoom=Math.round(this._map._zoom),this._currentShownBounds=this._getExpandedVisibleBounds())},_moveEnd:function(){if(!this._inZoomAnimation){var a=this._getExpandedVisibleBounds();this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,Math.floor(this._map.getMinZoom()),this._zoom,a),this._topClusterLevel._recursivelyAddChildrenToMap(null,Math.round(this._map._zoom),a),this._currentShownBounds=a}},_generateInitialClusters:function(){var a=Math.ceil(this._map.getMaxZoom()),l=Math.floor(this._map.getMinZoom()),c=this.options.maxClusterRadius,u=c;typeof c!="function"&&(u=function(){return c}),this.options.disableClusteringAtZoom!==null&&(a=this.options.disableClusteringAtZoom-1),this._maxZoom=a,this._gridClusters={},this._gridUnclustered={};for(var _=a;_>=l;_--)this._gridClusters[_]=new L.DistanceGrid(u(_)),this._gridUnclustered[_]=new L.DistanceGrid(u(_));this._topClusterLevel=new this._markerCluster(this,l-1)},_addLayer:function(a,l){var c=this._gridClusters,u=this._gridUnclustered,_=Math.floor(this._map.getMinZoom()),b,x;for(this.options.singleMarkerMode&&this._overrideMarkerIcon(a),a.on(this._childMarkerEventHandlers,this);l>=_;l--){b=this._map.project(a.getLatLng(),l);var E=c[l].getNearObject(b);if(E){E._addChild(a),a.__parent=E;return}if(E=u[l].getNearObject(b),E){var I=E.__parent;I&&this._removeLayer(E,!1);var k=new this._markerCluster(this,l,E,a);c[l].addObject(k,this._map.project(k._cLatLng,l)),E.__parent=k,a.__parent=k;var T=k;for(x=l-1;x>I._zoom;x--)T=new this._markerCluster(this,x,T),c[x].addObject(T,this._map.project(E.getLatLng(),x));I._addChild(T),this._removeFromGridUnclustered(E,l);return}u[l].addObject(a,b)}this._topClusterLevel._addChild(a),a.__parent=this._topClusterLevel},_refreshClustersIcons:function(){this._featureGroup.eachLayer(function(a){a instanceof L.MarkerCluster&&a._iconNeedsUpdate&&a._updateIcon()})},_enqueue:function(a){this._queue.push(a),this._queueTimeout||(this._queueTimeout=setTimeout(L.bind(this._processQueue,this),300))},_processQueue:function(){for(var a=0;aa?(this._animationStart(),this._animationZoomOut(this._zoom,a)):this._moveEnd()},_getExpandedVisibleBounds:function(){if(this.options.removeOutsideVisibleBounds){if(L.Browser.mobile)return this._checkBoundsMaxLat(this._map.getBounds())}else return this._mapBoundsInfinite;return this._checkBoundsMaxLat(this._map.getBounds().pad(1))},_checkBoundsMaxLat:function(a){var l=this._maxLat;return l!==void 0&&(a.getNorth()>=l&&(a._northEast.lat=1/0),a.getSouth()<=-l&&(a._southWest.lat=-1/0)),a},_animationAddLayerNonAnimated:function(a,l){if(l===a)this._featureGroup.addLayer(a);else if(l._childCount===2){l._addToMap();var c=l.getAllChildMarkers();this._featureGroup.removeLayer(c[0]),this._featureGroup.removeLayer(c[1])}else l._updateIcon()},_extractNonGroupLayers:function(a,l){var c=a.getLayers(),u=0,_;for(l=l||[];u=0;b--)k=I[b],c.contains(k._latlng)||u.removeLayer(k)}),this._forceLayout(),this._topClusterLevel._recursivelyBecomeVisible(c,l),u.eachLayer(function(x){!(x instanceof L.MarkerCluster)&&x._icon&&x.clusterShow()}),this._topClusterLevel._recursively(c,a,l,function(x){x._recursivelyRestoreChildPositions(l)}),this._ignoreMove=!1,this._enqueue(function(){this._topClusterLevel._recursively(c,a,_,function(x){u.removeLayer(x),x.clusterShow()}),this._animationEnd()})},_animationZoomOut:function(a,l){this._animationZoomOutSingle(this._topClusterLevel,a-1,l),this._topClusterLevel._recursivelyAddChildrenToMap(null,l,this._getExpandedVisibleBounds()),this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,Math.floor(this._map.getMinZoom()),a,this._getExpandedVisibleBounds())},_animationAddLayer:function(a,l){var c=this,u=this._featureGroup;u.addLayer(a),l!==a&&(l._childCount>2?(l._updateIcon(),this._forceLayout(),this._animationStart(),a._setPos(this._map.latLngToLayerPoint(l.getLatLng())),a.clusterHide(),this._enqueue(function(){u.removeLayer(a),a.clusterShow(),c._animationEnd()})):(this._forceLayout(),c._animationStart(),c._animationZoomOutSingle(l,this._map.getMaxZoom(),this._zoom)))}},_animationZoomOutSingle:function(a,l,c){var u=this._getExpandedVisibleBounds(),_=Math.floor(this._map.getMinZoom());a._recursivelyAnimateChildrenInAndAddSelfToMap(u,_,l+1,c);var b=this;this._forceLayout(),a._recursivelyBecomeVisible(u,c),this._enqueue(function(){if(a._childCount===1){var x=a._markers[0];this._ignoreMove=!0,x.setLatLng(x.getLatLng()),this._ignoreMove=!1,x.clusterShow&&x.clusterShow()}else a._recursively(u,c,_,function(E){E._recursivelyRemoveChildrenFromMap(u,_,l+1)});b._animationEnd()})},_animationEnd:function(){this._map&&(this._map._mapPane.className=this._map._mapPane.className.replace(" leaflet-cluster-anim","")),this._inZoomAnimation--,this.fire("animationend")},_forceLayout:function(){L.Util.falseFn(document.body.offsetWidth)}}),L.markerClusterGroup=function(a){return new L.MarkerClusterGroup(a)};var o=L.MarkerCluster=L.Marker.extend({options:L.Icon.prototype.options,initialize:function(a,l,c,u){L.Marker.prototype.initialize.call(this,c?c._cLatLng||c.getLatLng():new L.LatLng(0,0),{icon:this,pane:a.options.clusterPane}),this._group=a,this._zoom=l,this._markers=[],this._childClusters=[],this._childCount=0,this._iconNeedsUpdate=!0,this._boundsNeedUpdate=!0,this._bounds=new L.LatLngBounds,c&&this._addChild(c),u&&this._addChild(u)},getAllChildMarkers:function(a,l){a=a||[];for(var c=this._childClusters.length-1;c>=0;c--)this._childClusters[c].getAllChildMarkers(a,l);for(var u=this._markers.length-1;u>=0;u--)l&&this._markers[u].__dragStart||a.push(this._markers[u]);return a},getChildCount:function(){return this._childCount},zoomToBounds:function(a){for(var l=this._childClusters.slice(),c=this._group._map,u=c.getBoundsZoom(this._bounds),_=this._zoom+1,b=c.getZoom(),x;l.length>0&&u>_;){_++;var E=[];for(x=0;x_?this._group._map.setView(this._latlng,_):u<=b?this._group._map.setView(this._latlng,b+1):this._group._map.fitBounds(this._bounds,a)},getBounds:function(){var a=new L.LatLngBounds;return a.extend(this._bounds),a},_updateIcon:function(){this._iconNeedsUpdate=!0,this._icon&&this.setIcon(this)},createIcon:function(){return this._iconNeedsUpdate&&(this._iconObj=this._group.options.iconCreateFunction(this),this._iconNeedsUpdate=!1),this._iconObj.createIcon()},createShadow:function(){return this._iconObj.createShadow()},_addChild:function(a,l){this._iconNeedsUpdate=!0,this._boundsNeedUpdate=!0,this._setClusterCenter(a),a instanceof L.MarkerCluster?(l||(this._childClusters.push(a),a.__parent=this),this._childCount+=a._childCount):(l||this._markers.push(a),this._childCount++),this.__parent&&this.__parent._addChild(a,!0)},_setClusterCenter:function(a){this._cLatLng||(this._cLatLng=a._cLatLng||a._latlng)},_resetBounds:function(){var a=this._bounds;a._southWest&&(a._southWest.lat=1/0,a._southWest.lng=1/0),a._northEast&&(a._northEast.lat=-1/0,a._northEast.lng=-1/0)},_recalculateBounds:function(){var a=this._markers,l=this._childClusters,c=0,u=0,_=this._childCount,b,x,E,I;if(_!==0){for(this._resetBounds(),b=0;b=0;b--)x=_[b],x._icon&&(x._setPos(l),x.clusterHide())},function(u){var _=u._childClusters,b,x;for(b=_.length-1;b>=0;b--)x=_[b],x._icon&&(x._setPos(l),x.clusterHide())})},_recursivelyAnimateChildrenInAndAddSelfToMap:function(a,l,c,u){this._recursively(a,u,l,function(_){_._recursivelyAnimateChildrenIn(a,_._group._map.latLngToLayerPoint(_.getLatLng()).round(),c),_._isSingleParent()&&c-1===u?(_.clusterShow(),_._recursivelyRemoveChildrenFromMap(a,l,c)):_.clusterHide(),_._addToMap()})},_recursivelyBecomeVisible:function(a,l){this._recursively(a,this._group._map.getMinZoom(),l,null,function(c){c.clusterShow()})},_recursivelyAddChildrenToMap:function(a,l,c){this._recursively(c,this._group._map.getMinZoom()-1,l,function(u){if(l!==u._zoom)for(var _=u._markers.length-1;_>=0;_--){var b=u._markers[_];!c.contains(b._latlng)||(a&&(b._backupLatlng=b.getLatLng(),b.setLatLng(a),b.clusterHide&&b.clusterHide()),u._group._featureGroup.addLayer(b))}},function(u){u._addToMap(a)})},_recursivelyRestoreChildPositions:function(a){for(var l=this._markers.length-1;l>=0;l--){var c=this._markers[l];c._backupLatlng&&(c.setLatLng(c._backupLatlng),delete c._backupLatlng)}if(a-1===this._zoom)for(var u=this._childClusters.length-1;u>=0;u--)this._childClusters[u]._restorePosition();else for(var _=this._childClusters.length-1;_>=0;_--)this._childClusters[_]._recursivelyRestoreChildPositions(a)},_restorePosition:function(){this._backupLatlng&&(this.setLatLng(this._backupLatlng),delete this._backupLatlng)},_recursivelyRemoveChildrenFromMap:function(a,l,c,u){var _,b;this._recursively(a,l-1,c-1,function(x){for(b=x._markers.length-1;b>=0;b--)_=x._markers[b],(!u||!u.contains(_._latlng))&&(x._group._featureGroup.removeLayer(_),_.clusterShow&&_.clusterShow())},function(x){for(b=x._childClusters.length-1;b>=0;b--)_=x._childClusters[b],(!u||!u.contains(_._latlng))&&(x._group._featureGroup.removeLayer(_),_.clusterShow&&_.clusterShow())})},_recursively:function(a,l,c,u,_){var b=this._childClusters,x=this._zoom,E,I;if(l<=x&&(u&&u(this),_&&x===c&&_(this)),x=0;E--)I=b[E],I._boundsNeedUpdate&&I._recalculateBounds(),a.intersects(I._bounds)&&I._recursively(a,l,c,u,_)},_isSingleParent:function(){return this._childClusters.length>0&&this._childClusters[0]._childCount===this._childCount}});L.Marker.include({clusterHide:function(){var a=this.options.opacity;return this.setOpacity(0),this.options.opacity=a,this},clusterShow:function(){return this.setOpacity(this.options.opacity)}}),L.DistanceGrid=function(a){this._cellSize=a,this._sqCellSize=a*a,this._grid={},this._objectPoint={}},L.DistanceGrid.prototype={addObject:function(a,l){var c=this._getCoord(l.x),u=this._getCoord(l.y),_=this._grid,b=_[u]=_[u]||{},x=b[c]=b[c]||[],E=L.Util.stamp(a);this._objectPoint[E]=l,x.push(a)},updateObject:function(a,l){this.removeObject(a),this.addObject(a,l)},removeObject:function(a,l){var c=this._getCoord(l.x),u=this._getCoord(l.y),_=this._grid,b=_[u]=_[u]||{},x=b[c]=b[c]||[],E,I;for(delete this._objectPoint[L.Util.stamp(a)],E=0,I=x.length;E=0;b--){if(x=l[b],E=this.getDistant(x,a),E>0)_.push(x);else continue;E>c&&(c=E,u=x)}return{maxPoint:u,newPoints:_}},buildConvexHull:function(a,l){var c=[],u=this.findMostDistantPointFromBaseLine(a,l);return u.maxPoint?(c=c.concat(this.buildConvexHull([a[0],u.maxPoint],u.newPoints)),c=c.concat(this.buildConvexHull([u.maxPoint,a[1]],u.newPoints)),c):[a[0]]},getConvexHull:function(a){var l=!1,c=!1,u=!1,_=!1,b=null,x=null,E=null,I=null,k=null,T=null,O;for(O=a.length-1;O>=0;O--){var $=a[O];(l===!1||$.lat>l)&&(b=$,l=$.lat),(c===!1||$.latu)&&(E=$,u=$.lng),(_===!1||$.lng<_)&&(I=$,_=$.lng)}c!==l?(T=x,k=b):(T=I,k=E);var D=[].concat(this.buildConvexHull([T,k],a),this.buildConvexHull([k,T],a));return D}}}(),L.MarkerCluster.include({getConvexHull:function(){var a=this.getAllChildMarkers(),l=[],c,u;for(u=a.length-1;u>=0;u--)c=a[u].getLatLng(),l.push(c);return L.QuickHull.getConvexHull(l)}}),L.MarkerCluster.include({_2PI:Math.PI*2,_circleFootSeparation:25,_circleStartAngle:0,_spiralFootSeparation:28,_spiralLengthStart:11,_spiralLengthFactor:5,_circleSpiralSwitchover:9,spiderfy:function(){if(!(this._group._spiderfied===this||this._group._inZoomAnimation)){var a=this.getAllChildMarkers(null,!0),l=this._group,c=l._map,u=c.latLngToLayerPoint(this._latlng),_;this._group._unspiderfy(),this._group._spiderfied=this,this._group.options.spiderfyShapePositions?_=this._group.options.spiderfyShapePositions(a.length,u):a.length>=this._circleSpiralSwitchover?_=this._generatePointsSpiral(a.length,u):(u.y+=10,_=this._generatePointsCircle(a.length,u)),this._animationSpiderfy(a,_)}},unspiderfy:function(a){this._group._inZoomAnimation||(this._animationUnspiderfy(a),this._group._spiderfied=null)},_generatePointsCircle:function(a,l){var c=this._group.options.spiderfyDistanceMultiplier*this._circleFootSeparation*(2+a),u=c/this._2PI,_=this._2PI/a,b=[],x,E;for(u=Math.max(u,35),b.length=a,x=0;x=0;I--)I=0;b--)_=u[b],c.removeLayer(_),_._preSpiderfyLatlng&&(_.setLatLng(_._preSpiderfyLatlng),delete _._preSpiderfyLatlng),_.setZIndexOffset&&_.setZIndexOffset(0),_._spiderLeg&&(l.removeLayer(_._spiderLeg),delete _._spiderLeg);a.fire("unspiderfied",{cluster:this,markers:u}),a._ignoreMove=!1,a._spiderfied=null}}),L.MarkerClusterNonAnimated=L.MarkerCluster.extend({_animationSpiderfy:function(a,l){var c=this._group,u=c._map,_=c._featureGroup,b=this._group.options.spiderLegPolylineOptions,x,E,I,k;for(c._ignoreMove=!0,x=0;x=0;O--)ie=_.layerPointToLatLng(l[O]),$=a[O],$._preSpiderfyLatlng=$._latlng,$.setLatLng(ie),$.clusterShow&&$.clusterShow(),I&&(D=$._spiderLeg,N=D._path,N.style.strokeDashoffset=0,D.setStyle({opacity:T}));this.setOpacity(.3),u._ignoreMove=!1,setTimeout(function(){u._animationEnd(),u.fire("spiderfied",{cluster:c,markers:a})},200)},_animationUnspiderfy:function(a){var l=this,c=this._group,u=c._map,_=c._featureGroup,b=a?u._latLngToNewLayerPoint(this._latlng,a.zoom,a.center):u.latLngToLayerPoint(this._latlng),x=this.getAllChildMarkers(null,!0),E=L.Path.SVG,I,k,T,O,$,D;for(c._ignoreMove=!0,c._animationStart(),this.setOpacity(1),k=x.length-1;k>=0;k--)I=x[k],I._preSpiderfyLatlng&&(I.closePopup(),I.setLatLng(I._preSpiderfyLatlng),delete I._preSpiderfyLatlng,D=!0,I._setPos&&(I._setPos(b),D=!1),I.clusterHide&&(I.clusterHide(),D=!1),D&&_.removeLayer(I),E&&(T=I._spiderLeg,O=T._path,$=O.getTotalLength()+.1,O.style.strokeDashoffset=$,T.setStyle({opacity:0})));c._ignoreMove=!1,setTimeout(function(){var N=0;for(k=x.length-1;k>=0;k--)I=x[k],I._spiderLeg&&N++;for(k=x.length-1;k>=0;k--)I=x[k],I._spiderLeg&&(I.clusterShow&&I.clusterShow(),I.setZIndexOffset&&I.setZIndexOffset(0),N>1&&_.removeLayer(I),u.removeLayer(I._spiderLeg),delete I._spiderLeg);c._animationEnd(),c.fire("unspiderfied",{cluster:l,markers:x})},200)}}),L.MarkerClusterGroup.include({_spiderfied:null,unspiderfy:function(){this._unspiderfy.apply(this,arguments)},_spiderfierOnAdd:function(){this._map.on("click",this._unspiderfyWrapper,this),this._map.options.zoomAnimation&&this._map.on("zoomstart",this._unspiderfyZoomStart,this),this._map.on("zoomend",this._noanimationUnspiderfy,this),L.Browser.touch||this._map.getRenderer(this)},_spiderfierOnRemove:function(){this._map.off("click",this._unspiderfyWrapper,this),this._map.off("zoomstart",this._unspiderfyZoomStart,this),this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._map.off("zoomend",this._noanimationUnspiderfy,this),this._noanimationUnspiderfy()},_unspiderfyZoomStart:function(){!this._map||this._map.on("zoomanim",this._unspiderfyZoomAnim,this)},_unspiderfyZoomAnim:function(a){L.DomUtil.hasClass(this._map._mapPane,"leaflet-touching")||(this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._unspiderfy(a))},_unspiderfyWrapper:function(){this._unspiderfy()},_unspiderfy:function(a){this._spiderfied&&this._spiderfied.unspiderfy(a)},_noanimationUnspiderfy:function(){this._spiderfied&&this._spiderfied._noanimationUnspiderfy()},_unspiderfyLayer:function(a){a._spiderLeg&&(this._featureGroup.removeLayer(a),a.clusterShow&&a.clusterShow(),a.setZIndexOffset&&a.setZIndexOffset(0),this._map.removeLayer(a._spiderLeg),delete a._spiderLeg)}}),L.MarkerClusterGroup.include({refreshClusters:function(a){return a?a instanceof L.MarkerClusterGroup?a=a._topClusterLevel.getAllChildMarkers():a instanceof L.LayerGroup?a=a._layers:a instanceof L.MarkerCluster?a=a.getAllChildMarkers():a instanceof L.Marker&&(a=[a]):a=this._topClusterLevel.getAllChildMarkers(),this._flagParentsIconsNeedUpdate(a),this._refreshClustersIcons(),this.options.singleMarkerMode&&this._refreshSingleMarkerModeMarkers(a),this},_flagParentsIconsNeedUpdate:function(a){var l,c;for(l in a)for(c=a[l].__parent;c;)c._iconNeedsUpdate=!0,c=c.__parent},_refreshSingleMarkerModeMarkers:function(a){var l,c;for(l in a)c=a[l],this.hasLayer(c)&&c.setIcon(this._overrideMarkerIcon(c))}}),L.Marker.include({refreshIconOptions:function(a,l){var c=this.options.icon;return L.setOptions(c,a),this.setIcon(c),l&&this.__parent&&this.__parent._group.refreshClusters(this),this}}),r.MarkerClusterGroup=n,r.MarkerCluster=o,Object.defineProperty(r,"__esModule",{value:!0})})})(leaflet_markerclusterSrc,leaflet_markerclusterSrc.exports);const MarkerCluster_Default="",MarkerCluster="",airtemp={label:"Airtemp",unit:"\u2103"},airtempavg={label:"AvgAirtemp",unit:"\u2103"},airtempmax={label:"MaxAirtemp",unit:"\u2103"},airtempmin={label:"MinAirtemp",unit:"\u2103"},co={label:"CO",name:{en:"Carbon monoxide",ru:"\u0423\u0433\u0430\u0440\u043D\u044B\u0439 \u0433\u0430\u0437"},unit:"mg/m3",chartColor:"#c1c1c1",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,2,4,14],zones:[{value:0,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:2,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:4,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,28.01)},info:"\u0421arbon monoxide. It is formed during the incomplete decomposition of organic compounds and during the combustion of biomass during forest fires."},gc={label:"GC",name:{en:"Radiation",ru:"\u0420\u0430\u0434\u0438\u0430\u0446\u0438\u044F"},unit:"\u03BCR/h",chartColor:"#e99152",range:[2,10,100,1e3],zones:[{value:2,color:"#60bc2a",label:{en:"Background",ru:"\u0424\u043E\u043D\u043E\u0432\u0430\u044F"}},{value:10,color:"#03a5ed",label:{en:"Moderate",ru:"\u041D\u0435\u0432\u044B\u0441\u043E\u043A\u0430\u044F"}},{value:100,color:"#ff9d00",label:{en:"Elevated",ru:"\u041F\u043E\u0432\u044B\u0448\u0435\u043D\u043D\u0430\u044F"}},{color:"#ff4d00",label:{en:"High",ru:"\u0412\u044B\u0441\u043E\u043A\u0430\u044F"}}]},humidity={label:"Hm",name:{en:"Humidity",ru:"\u0412\u043B\u0430\u0436\u043D\u043E\u0441\u0442\u044C"},unit:"%",chartColor:"#6fd3ff",range:[30,40,60,70],zones:[{value:30,color:"#ff4d00",label:{en:"Very dry",ru:"\u041E\u0447\u0435\u043D\u044C \u0441\u0443\u0445\u043E"}},{value:40,color:"#ff9d00",label:{en:"Dry",ru:"\u0421\u0443\u0445\u043E"}},{value:60,color:"#03a5ed",label:{en:"Comfortable",ru:"\u041A\u043E\u043C\u0444\u043E\u0440\u0442\u043D\u043E"}},{value:70,color:"#2a5cbc",label:{en:"Humid",ru:"\u0412\u043B\u0430\u0436\u043D\u043E"}},{color:"#7a00da",label:{en:"Very humid",ru:"\u041E\u0447\u0435\u043D\u044C \u0432\u043B\u0430\u0436\u043D\u043E"}}]},nh3={label:"NH3",name:{en:"Ammonia",ru:"\u0410\u043C\u043C\u0438\u0430\u043A"},unit:"mg/m3",icon:"vial-virus",chartColor:"#a1e37a",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,15,40],zones:[{value:15,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:40,color:"#ff9d00",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{color:"#fc0202",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,17.03)}},no2={label:"NO2",name:{en:"Nitrogen Dioxide",ru:"\u0414\u0438\u043E\u043A\u0441\u0438\u0434 \u0430\u0437\u043E\u0442\u0430"},unit:"mg/m3",chartColor:"#d4dd53",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,1,5],zones:[{value:1,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:5,color:"#ff9d00",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{color:"#fc0202",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,46.01)}},pm1={label:"PM1",unit:"\u03BCg/m3",chartColor:"#ff99e9"},pm10={label:"PM10",unit:"\u03BCg/m3",chartColor:"#e8b738",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,51,101,251,350],zones:[{value:50,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:100,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:250,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{value:350,color:"#ff4d00",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Unacceptable",ru:"\u041D\u0435\u043F\u0440\u0438\u0435\u043C\u043B\u0435\u043C\u043E"}}],calculate:function(e){return toFixed(e)},info:"PM10 - suspended particles (PM - particulate matter) of a substance with a diameter of less than 10 micrometers (\u03BCm). Pollen and other allergens."},pm25={label:"PM2.5",unit:"\u03BCg/m3",chartColor:"#89b268",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,36,70,151,251],zones:[{value:36,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:70,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:150,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{value:250,color:"#ff4d00",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Unacceptable",ru:"\u041D\u0435\u043F\u0440\u0438\u0435\u043C\u043B\u0435\u043C\u043E"}}],calculate:function(e){return toFixed(e)},info:"Suspended, solid and liquid particles with a diameter of 2.5 microns are an air pollutant."},pressure={label:"Pr",name:{en:"Atmospheric pressure",ru:"\u0410\u0442\u043C\u043E\u0441\u0444\u0435\u0440\u043D\u043E\u0435 \u0434\u0430\u0432\u043B\u0435\u043D\u0438\u0435"},unit:"mmHg"},rainfall={label:"Rainfall",unit:"mm"},sat10={label:"Sat10",unit:""},sat5={label:"Sat5",unit:""},soiltemp={label:"Soiltemp",unit:"\u2103"},temperature={label:"Tmp",name:{en:"Temperature",ru:"\u0422\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u0430"},unit:"\u2103",chartColor:"#2d7ac7",colors:["#fc0202","#ff9d00","#60bc2a","#ff9d00","#fc0202"],range:[-10,0,10,25],zones:[{value:-9,color:"#7a00da",label:{en:"Very cold",ru:"\u041E\u0447\u0435\u043D\u044C \u0445\u043E\u043B\u043E\u0434\u043D\u043E"}},{value:0,color:"#2a5cbc",label:{en:"Cold",ru:"\u0425\u043E\u043B\u043E\u0434\u043D\u043E"}},{value:10,color:"#03a5ed",label:{en:"Cool",ru:"\u041F\u0440\u043E\u0445\u043B\u0430\u0434\u043D\u043E"}},{value:25,color:"#60bc2a",label:{en:"Warm",ru:"\u0422\u0435\u043F\u043B\u043E"}},{color:"#ff9d00",label:{en:"Very warm",ru:"\u041E\u0447\u0435\u043D\u044C \u0442\u0435\u043F\u043B\u043E"}}],states:["danger","attention","good","attention","danger","neutral"],calculate:function(e){return toFixed(e)},info:"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C \u0442\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u044B \u0432\u043E\u0437\u0434\u0443\u0445\u0430"},windang={label:"Windang",unit:"\xB0",icon:"wind"},windspeed={label:"Windspeed",unit:"m/s",icon:"wind"},windspeedmax={label:"Windspeedmax",unit:"m/s"},measurements={airtemp,airtempavg,airtempmax,airtempmin,co,gc,humidity,nh3,no2,pm1,pm10,pm25,pressure,rainfall,sat10,sat5,soiltemp,temperature,windang,windspeed,windspeedmax};function toFixed(e,t=4){return+(+e||0).toFixed(t)}function converterPpmToMgm3(e,t){return toFixed(e*t/24.05526)}const states=["good","attention","danger","neutral"];function getMeasurementByName(e){return measurements[e]||measurements.pm10}const artesiantlt="/assets/artesiantlt.b6bada62.jpg",atc="/assets/atc.09cec0ab.png",dolinatlt="/assets/dolinatlt.9bfd5fdc.jpg",ekovoz="/assets/ekovoz.af7d8a74.png",panorama="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACGVBMVEUAAACz00SfykaQuUWZx0ZQnEyax0aBu0iBu0iBvElgmUhpsExosEtgm0irz0SawkWrz0aTxUiTxEd2rkeTw0d4uUp6uUp6uEp6uUl6uUpwoUZhrUxTnkuly0ZGnE1Jok6lzUaLwUiNwUiNwEdko0hztUp0tUpztkpcn0lam0qHtUZbqk1ooEebw0ZytUpytUlTmks7iktytkp0tUxAnVBBnk9Ank9Bn088lk8vf0wueUote0s/mk9AnU0sbEgobUl9q0Ztn0d6qUaYw0aeyUaCskeAskdzo0Ztnkeax0eaxkeKu0dknEdRkklYoUtRm0tWnUpPkUlknUeSwUebx0eCu0qCu0mBu0lkoklBhUpAhUpqp0qCvElUmEpiqEtpsExpr0tpsEtYn0pZn0tmrUtVlkl4qUZLjkpJmExQpE5GlkxHlkxIl0xQkkproUeiyEWTw0iTw0dSkkk1iU0ziU0zjE45iUtZmEl3rEeSw0d6uEp6t0pvrkpQkklMjUp0s0pgm0lPlkpirExhrExUnEtWnktdl0ily0aUwEZblkhHjUpClExBlE1JoU5Hnk1EjktgmUiFs0alzEaMwEhloElEjEovf0wvgk1FjEpemkiGukh0tUt0tEpXmUp0tUpvsUpcl0hNkEpUoExbqk1bqUxPm0xPmktbqU1RnEtJjklytUpBi0s8jUxCm048kk1CnE5AiktcoUv///8iSiW7AAAAQHRSTlMAf/7+f/7+f/7+f/7+f3/+f3/+/v5//v7+f3/+/n/+/n9//v5//v7+/n9//v5/f/7v/v5/YL+/v7+/3++/YEA/+66NsgAAAAFiS0dEsq1qz+gAAAEDSURBVBjTY2B0cHRydnFxdWNycXb3YGZkYPH08vbx9fNnDQgMCmYLYWFg5wgNC+eMiIyKDguLieFkZ+CKjYtP4E5MSuaJT0xISeVl4ONPS8/IzMzKzszMyc3LF2AQLCgUEi4qLiktK68QEqkUZBCtqharqqqprasXrxITk5BkkGpolG5qbm6RaZJukm5tk2KQbe/o7JKT7+7p7eufMHGSAoPi5MlKk6dMnTZ9xsxZk5WUFRlUZs9Rna2mrjF3tursebPnazJoLVi4SHvxkqXLli/XXrFSR5dBb5W+weo1a9etW2+4YaPRKmMGE1MzU3MLSytrSxtTILBlgAI7ewZUABcAAE5TTddsyTFjAAAAAElFTkSuQmCC",qvantorium="/assets/qvantorium.d5858788.jpg",sun="/assets/sun.d26ef6d1.png",sensors={"7e071fd9b023ed8f18458a73613a0834f6220bd5cc50357ba3493c6040a9ea8c":{icon:ekovoz,link:"http://ekovoz.ru/"},"162ebfac08a69bc96c0bd569c95026c6750cbecca7a61731dfe1a985a9391176":{icon:atc,link:"http://atcgaz.ru/"},"7c7ffabc786c46ff40d8ca922b1248e1261baefec702eea160001140063f8c53":{icon:atc,link:"http://atcgaz.ru/"},"7cdeafa03331cb330c3993ff0381457f0713a8fd6d0b3dbe93ea24affe5676ac":{icon:artesiantlt,link:"https://www.artesiantlt.ru/"},"217a9ae639e48a9b99de7895c496b224ad6a80f9b679d516557561aedd47c58b":{icon:qvantorium,link:"https://vk.com/kvantoriumtlt"},f5cf0ec44b696400af9b280cb5bedc9e10893f5f961159658a218286f8e97372:{icon:dolinatlt,link:"https://dolinatlt.ru/"},"5bd528a4d708304254d2417b83f8b5c997ed08ccf956fa4e538fc6cfa40f86c0":{icon:panorama,link:"https://panorama-park63.ru/"},e4871acd155431c63fbbc54b89d015bc17bc5fbe44d5846502f7e58566e24a8e:{link:"https://airalab.org/"},"62c86fb3712e2c8e3d8a7a79f62c1cb0dbd4ad2980606dbf8fcf96ce9ed46c8d":{icon:sun}};var chroma$1={exports:{}};/** + */(function(e,t){(function(r,n){n(t)})(commonjsGlobal$2,function(r){var n="1.9.2";function o(g){var S,B,_e,Me;for(B=1,_e=arguments.length;B<_e;B++){Me=arguments[B];for(S in Me)g[S]=Me[S]}return g}var a=Object.create||function(){function g(){}return function(S){return g.prototype=S,new g}}();function l(g,S){var B=Array.prototype.slice;if(g.bind)return g.bind.apply(g,B.call(arguments,1));var _e=B.call(arguments,2);return function(){return g.apply(S,_e.length?_e.concat(B.call(arguments)):arguments)}}var c=0;function u(g){return"_leaflet_id"in g||(g._leaflet_id=++c),g._leaflet_id}function _(g,S,B){var _e,Me,Ye,lt;return lt=function(){_e=!1,Me&&(Ye.apply(B,Me),Me=!1)},Ye=function(){_e?Me=arguments:(g.apply(B,arguments),setTimeout(lt,S),_e=!0)},Ye}function b(g,S,B){var _e=S[1],Me=S[0],Ye=_e-Me;return g===_e&&B?g:((g-Me)%Ye+Ye)%Ye+Me}function x(){return!1}function E(g,S){if(S===!1)return g;var B=Math.pow(10,S===void 0?6:S);return Math.round(g*B)/B}function I(g){return g.trim?g.trim():g.replace(/^\s+|\s+$/g,"")}function k(g){return I(g).split(/\s+/)}function T(g,S){Object.prototype.hasOwnProperty.call(g,"options")||(g.options=g.options?a(g.options):{});for(var B in S)g.options[B]=S[B];return g.options}function O(g,S,B){var _e=[];for(var Me in g)_e.push(encodeURIComponent(B?Me.toUpperCase():Me)+"="+encodeURIComponent(g[Me]));return(!S||S.indexOf("?")===-1?"?":"&")+_e.join("&")}var $=/\{ *([\w_ -]+) *\}/g;function D(g,S){return g.replace($,function(B,_e){var Me=S[_e];if(Me===void 0)throw new Error("No value provided for variable "+B);return typeof Me=="function"&&(Me=Me(S)),Me})}var N=Array.isArray||function(g){return Object.prototype.toString.call(g)==="[object Array]"};function H(g,S){for(var B=0;B"u"||!L||!L.Mixin)){g=N(g)?g:[g];for(var S=0;S0?Math.floor(g):Math.ceil(g)};se.prototype={clone:function(){return new se(this.x,this.y)},add:function(g){return this.clone()._add(Pe(g))},_add:function(g){return this.x+=g.x,this.y+=g.y,this},subtract:function(g){return this.clone()._subtract(Pe(g))},_subtract:function(g){return this.x-=g.x,this.y-=g.y,this},divideBy:function(g){return this.clone()._divideBy(g)},_divideBy:function(g){return this.x/=g,this.y/=g,this},multiplyBy:function(g){return this.clone()._multiplyBy(g)},_multiplyBy:function(g){return this.x*=g,this.y*=g,this},scaleBy:function(g){return new se(this.x*g.x,this.y*g.y)},unscaleBy:function(g){return new se(this.x/g.x,this.y/g.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=Se(this.x),this.y=Se(this.y),this},distanceTo:function(g){g=Pe(g);var S=g.x-this.x,B=g.y-this.y;return Math.sqrt(S*S+B*B)},equals:function(g){return g=Pe(g),g.x===this.x&&g.y===this.y},contains:function(g){return g=Pe(g),Math.abs(g.x)<=Math.abs(this.x)&&Math.abs(g.y)<=Math.abs(this.y)},toString:function(){return"Point("+E(this.x)+", "+E(this.y)+")"}};function Pe(g,S,B){return g instanceof se?g:N(g)?new se(g[0],g[1]):g==null?g:typeof g=="object"&&"x"in g&&"y"in g?new se(g.x,g.y):new se(g,S,B)}function Ue(g,S){if(!!g)for(var B=S?[g,S]:g,_e=0,Me=B.length;_e=this.min.x&&B.x<=this.max.x&&S.y>=this.min.y&&B.y<=this.max.y},intersects:function(g){g=Be(g);var S=this.min,B=this.max,_e=g.min,Me=g.max,Ye=Me.x>=S.x&&_e.x<=B.x,lt=Me.y>=S.y&&_e.y<=B.y;return Ye&<},overlaps:function(g){g=Be(g);var S=this.min,B=this.max,_e=g.min,Me=g.max,Ye=Me.x>S.x&&_e.xS.y&&_e.y=S.lat&&Me.lat<=B.lat&&_e.lng>=S.lng&&Me.lng<=B.lng},intersects:function(g){g=ye(g);var S=this._southWest,B=this._northEast,_e=g.getSouthWest(),Me=g.getNorthEast(),Ye=Me.lat>=S.lat&&_e.lat<=B.lat,lt=Me.lng>=S.lng&&_e.lng<=B.lng;return Ye&<},overlaps:function(g){g=ye(g);var S=this._southWest,B=this._northEast,_e=g.getSouthWest(),Me=g.getNorthEast(),Ye=Me.lat>S.lat&&_e.latS.lng&&_e.lng1,yo=function(){var g=!1;try{var S=Object.defineProperty({},"passive",{get:function(){g=!0}});window.addEventListener("testPassiveEventSupport",x,S),window.removeEventListener("testPassiveEventSupport",x,S)}catch{}return g}(),vo=function(){return!!document.createElement("canvas").getContext}(),xi=!!(document.createElementNS&&ke("svg").createSVGRect),_o=!!xi&&function(){var g=document.createElement("div");return g.innerHTML="",(g.firstChild&&g.firstChild.namespaceURI)==="http://www.w3.org/2000/svg"}(),bo=!xi&&function(){try{var g=document.createElement("div");g.innerHTML='';var S=g.firstChild;return S.style.behavior="url(#default#VML)",S&&typeof S.adj=="object"}catch{return!1}}(),ns=navigator.platform.indexOf("Mac")===0,is=navigator.platform.indexOf("Linux")===0;function Tr(g){return navigator.userAgent.toLowerCase().indexOf(g)>=0}var $t={ie:Xe,ielt9:Je,edge:rt,webkit:qe,android:Ve,android23:Ae,androidStock:Ge,opera:Ze,chrome:$e,gecko:me,safari:Ee,phantom:je,opera12:nt,win:ot,ie3d:dt,webkit3d:Ct,gecko3d:St,any3d:kt,mobile:Et,mobileWebkit:Lt,mobileWebkit3d:tr,msPointer:Xt,pointer:wr,touch:dr,touchNative:nr,mobileOpera:pr,mobileGecko:po,retina:go,passiveEvents:yo,canvas:vo,svg:xi,vml:bo,inlineSvg:_o,mac:ns,linux:is},ss=$t.msPointer?"MSPointerDown":"pointerdown",En=$t.msPointer?"MSPointerMove":"pointermove",os=$t.msPointer?"MSPointerUp":"pointerup",Ei=$t.msPointer?"MSPointerCancel":"pointercancel",Si={touchstart:ss,touchmove:En,touchend:os,touchcancel:Ei},ls={touchstart:So,touchmove:Sn,touchend:Sn,touchcancel:Sn},hn={},Ci=!1;function wo(g,S,B){return S==="touchstart"&&Eo(),ls[S]?(B=ls[S].bind(this,B),g.addEventListener(Si[S],B,!1),B):(console.warn("wrong event specified:",S),L.Util.falseFn)}function cs(g,S,B){if(!Si[S]){console.warn("wrong event specified:",S);return}g.removeEventListener(Si[S],B,!1)}function xo(g){hn[g.pointerId]=g}function us(g){hn[g.pointerId]&&(hn[g.pointerId]=g)}function hs(g){delete hn[g.pointerId]}function Eo(){Ci||(document.addEventListener(ss,xo,!0),document.addEventListener(En,us,!0),document.addEventListener(os,hs,!0),document.addEventListener(Ei,hs,!0),Ci=!0)}function Sn(g,S){if(S.pointerType!==(S.MSPOINTER_TYPE_MOUSE||"mouse")){S.touches=[];for(var B in hn)S.touches.push(hn[B]);S.changedTouches=[S],g(S)}}function So(g,S){S.MSPOINTER_TYPE_TOUCH&&S.pointerType===S.MSPOINTER_TYPE_TOUCH&&ur(S),Sn(g,S)}function Co(g){var S={},B,_e;for(_e in g)B=g[_e],S[_e]=B&&B.bind?B.bind(g):B;return g=S,S.type="dblclick",S.detail=2,S.isTrusted=!1,S._simulated=!0,S}var ko=200;function To(g,S){g.addEventListener("dblclick",S);var B=0,_e;function Me(Ye){if(Ye.detail!==1){_e=Ye.detail;return}if(!(Ye.pointerType==="mouse"||Ye.sourceCapabilities&&!Ye.sourceCapabilities.firesTouchEvents)){var lt=ds(Ye);if(!(lt.some(function(yt){return yt instanceof HTMLLabelElement&&yt.attributes.for})&&!lt.some(function(yt){return yt instanceof HTMLInputElement||yt instanceof HTMLSelectElement}))){var mt=Date.now();mt-B<=ko?(_e++,_e===2&&S(Co(Ye))):_e=1,B=mt}}}return g.addEventListener("click",Me),{dblclick:S,simDblclick:Me}}function Ao(g,S){g.removeEventListener("dblclick",S.dblclick),g.removeEventListener("click",S.simDblclick)}var ki=Cn(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),Kr=Cn(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),Yr=Kr==="webkitTransition"||Kr==="OTransition"?Kr+"End":"transitionend";function Gn(g){return typeof g=="string"?document.getElementById(g):g}function Ar(g,S){var B=g.style[S]||g.currentStyle&&g.currentStyle[S];if((!B||B==="auto")&&document.defaultView){var _e=document.defaultView.getComputedStyle(g,null);B=_e?_e[S]:null}return B==="auto"?null:B}function Wt(g,S,B){var _e=document.createElement(g);return _e.className=S||"",B&&B.appendChild(_e),_e}function ir(g){var S=g.parentNode;S&&S.removeChild(g)}function qn(g){for(;g.firstChild;)g.removeChild(g.firstChild)}function fn(g){var S=g.parentNode;S&&S.lastChild!==g&&S.appendChild(g)}function dn(g){var S=g.parentNode;S&&S.firstChild!==g&&S.insertBefore(g,S.firstChild)}function Xn(g,S){if(g.classList!==void 0)return g.classList.contains(S);var B=Zn(g);return B.length>0&&new RegExp("(^|\\s)"+S+"(\\s|$)").test(B)}function Nt(g,S){if(g.classList!==void 0)for(var B=k(S),_e=0,Me=B.length;_e0?2*window.devicePixelRatio:1;function Ni(g){return $t.edge?g.wheelDeltaY/2:g.deltaY&&g.deltaMode===0?-g.deltaY/Di:g.deltaY&&g.deltaMode===1?-g.deltaY*20:g.deltaY&&g.deltaMode===2?-g.deltaY*60:g.deltaX||g.deltaZ?0:g.wheelDelta?(g.wheelDeltaY||g.wheelDelta)/2:g.detail&&Math.abs(g.detail)<32765?-g.detail*20:g.detail?g.detail/-32765*60:0}function Bi(g,S){var B=S.relatedTarget;if(!B)return!0;try{for(;B&&B!==g;)B=B.parentNode}catch{return!1}return B!==g}var Io={__proto__:null,on:Ot,off:Qt,stopPropagation:Xr,disableScrollPropagation:ti,disableClickPropagation:Pr,preventDefault:ur,stop:Zr,getPropagationPath:ds,getMousePosition:ri,getWheelDelta:Ni,isExternalTarget:Bi,addListener:Ot,removeListener:Qt},ps=ge.extend({run:function(g,S,B,_e){this.stop(),this._el=g,this._inProgress=!0,this._duration=B||.25,this._easeOutPower=1/Math.max(_e||.5,.2),this._startPos=qr(g),this._offset=S.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){!this._inProgress||(this._step(!0),this._complete())},_animate:function(){this._animId=ee(this._animate,this),this._step()},_step:function(g){var S=+new Date-this._startTime,B=this._duration*1e3;Sthis.options.maxZoom)?this.setZoom(g):this},panInsideBounds:function(g,S){this._enforcingBounds=!0;var B=this.getCenter(),_e=this._limitCenter(B,this._zoom,ye(g));return B.equals(_e)||this.panTo(_e,S),this._enforcingBounds=!1,this},panInside:function(g,S){S=S||{};var B=Pe(S.paddingTopLeft||S.padding||[0,0]),_e=Pe(S.paddingBottomRight||S.padding||[0,0]),Me=this.project(this.getCenter()),Ye=this.project(g),lt=this.getPixelBounds(),mt=Be([lt.min.add(B),lt.max.subtract(_e)]),yt=mt.getSize();if(!mt.contains(Ye)){this._enforcingBounds=!0;var _t=Ye.subtract(mt.getCenter()),Tt=mt.extend(Ye).getSize().subtract(yt);Me.x+=_t.x<0?-Tt.x:Tt.x,Me.y+=_t.y<0?-Tt.y:Tt.y,this.panTo(this.unproject(Me),S),this._enforcingBounds=!1}return this},invalidateSize:function(g){if(!this._loaded)return this;g=o({animate:!1,pan:!0},g===!0?{animate:!0}:g);var S=this.getSize();this._sizeChanged=!0,this._lastCenter=null;var B=this.getSize(),_e=S.divideBy(2).round(),Me=B.divideBy(2).round(),Ye=_e.subtract(Me);return!Ye.x&&!Ye.y?this:(g.animate&&g.pan?this.panBy(Ye):(g.pan&&this._rawPanBy(Ye),this.fire("move"),g.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(l(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:S,newSize:B}))},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(g){if(g=this._locateOptions=o({timeout:1e4,watch:!1},g),!("geolocation"in navigator))return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var S=l(this._handleGeolocationResponse,this),B=l(this._handleGeolocationError,this);return g.watch?this._locationWatchId=navigator.geolocation.watchPosition(S,B,g):navigator.geolocation.getCurrentPosition(S,B,g),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(g){if(!!this._container._leaflet_id){var S=g.code,B=g.message||(S===1?"permission denied":S===2?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:S,message:"Geolocation error: "+B+"."})}},_handleGeolocationResponse:function(g){if(!!this._container._leaflet_id){var S=g.coords.latitude,B=g.coords.longitude,_e=new Ce(S,B),Me=_e.toBounds(g.coords.accuracy*2),Ye=this._locateOptions;if(Ye.setView){var lt=this.getBoundsZoom(Me);this.setView(_e,Ye.maxZoom?Math.min(lt,Ye.maxZoom):lt)}var mt={latlng:_e,bounds:Me,timestamp:g.timestamp};for(var yt in g.coords)typeof g.coords[yt]=="number"&&(mt[yt]=g.coords[yt]);this.fire("locationfound",mt)}},addHandler:function(g,S){if(!S)return this;var B=this[g]=new S(this);return this._handlers.push(B),this.options[g]&&B.enable(),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch{this._container._leaflet_id=void 0,this._containerId=void 0}this._locationWatchId!==void 0&&this.stopLocate(),this._stop(),ir(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(he(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload");var g;for(g in this._layers)this._layers[g].remove();for(g in this._panes)ir(this._panes[g]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(g,S){var B="leaflet-pane"+(g?" leaflet-"+g.replace("Pane","")+"-pane":""),_e=Wt("div",B,S||this._mapPane);return g&&(this._panes[g]=_e),_e},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var g=this.getPixelBounds(),S=this.unproject(g.getBottomLeft()),B=this.unproject(g.getTopRight());return new fe(S,B)},getMinZoom:function(){return this.options.minZoom===void 0?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===void 0?this._layersMaxZoom===void 0?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(g,S,B){g=ye(g),B=Pe(B||[0,0]);var _e=this.getZoom()||0,Me=this.getMinZoom(),Ye=this.getMaxZoom(),lt=g.getNorthWest(),mt=g.getSouthEast(),yt=this.getSize().subtract(B),_t=Be(this.project(mt,_e),this.project(lt,_e)).getSize(),Tt=$t.any3d?this.options.zoomSnap:1,Mt=yt.x/_t.x,Dt=yt.y/_t.y,br=S?Math.max(Mt,Dt):Math.min(Mt,Dt);return _e=this.getScaleZoom(br,_e),Tt&&(_e=Math.round(_e/(Tt/100))*(Tt/100),_e=S?Math.ceil(_e/Tt)*Tt:Math.floor(_e/Tt)*Tt),Math.max(Me,Math.min(Ye,_e))},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new se(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(g,S){var B=this._getTopLeftPoint(g,S);return new Ue(B,B.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(g){return this.options.crs.getProjectedBounds(g===void 0?this.getZoom():g)},getPane:function(g){return typeof g=="string"?this._panes[g]:g},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(g,S){var B=this.options.crs;return S=S===void 0?this._zoom:S,B.scale(g)/B.scale(S)},getScaleZoom:function(g,S){var B=this.options.crs;S=S===void 0?this._zoom:S;var _e=B.zoom(g*B.scale(S));return isNaN(_e)?1/0:_e},project:function(g,S){return S=S===void 0?this._zoom:S,this.options.crs.latLngToPoint(Le(g),S)},unproject:function(g,S){return S=S===void 0?this._zoom:S,this.options.crs.pointToLatLng(Pe(g),S)},layerPointToLatLng:function(g){var S=Pe(g).add(this.getPixelOrigin());return this.unproject(S)},latLngToLayerPoint:function(g){var S=this.project(Le(g))._round();return S._subtract(this.getPixelOrigin())},wrapLatLng:function(g){return this.options.crs.wrapLatLng(Le(g))},wrapLatLngBounds:function(g){return this.options.crs.wrapLatLngBounds(ye(g))},distance:function(g,S){return this.options.crs.distance(Le(g),Le(S))},containerPointToLayerPoint:function(g){return Pe(g).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(g){return Pe(g).add(this._getMapPanePos())},containerPointToLatLng:function(g){var S=this.containerPointToLayerPoint(Pe(g));return this.layerPointToLatLng(S)},latLngToContainerPoint:function(g){return this.layerPointToContainerPoint(this.latLngToLayerPoint(Le(g)))},mouseEventToContainerPoint:function(g){return ri(g,this._container)},mouseEventToLayerPoint:function(g){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(g))},mouseEventToLatLng:function(g){return this.layerPointToLatLng(this.mouseEventToLayerPoint(g))},_initContainer:function(g){var S=this._container=Gn(g);if(S){if(S._leaflet_id)throw new Error("Map container is already initialized.")}else throw new Error("Map container not found.");Ot(S,"scroll",this._onScroll,this),this._containerId=u(S)},_initLayout:function(){var g=this._container;this._fadeAnimated=this.options.fadeAnimation&&$t.any3d,Nt(g,"leaflet-container"+($t.touch?" leaflet-touch":"")+($t.retina?" leaflet-retina":"")+($t.ielt9?" leaflet-oldie":"")+($t.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":""));var S=Ar(g,"position");S!=="absolute"&&S!=="relative"&&S!=="fixed"&&(g.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var g=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),lr(this._mapPane,new se(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(Nt(g.markerPane,"leaflet-zoom-hide"),Nt(g.shadowPane,"leaflet-zoom-hide"))},_resetView:function(g,S,B){lr(this._mapPane,new se(0,0));var _e=!this._loaded;this._loaded=!0,S=this._limitZoom(S),this.fire("viewprereset");var Me=this._zoom!==S;this._moveStart(Me,B)._move(g,S)._moveEnd(Me),this.fire("viewreset"),_e&&this.fire("load")},_moveStart:function(g,S){return g&&this.fire("zoomstart"),S||this.fire("movestart"),this},_move:function(g,S,B,_e){S===void 0&&(S=this._zoom);var Me=this._zoom!==S;return this._zoom=S,this._lastCenter=g,this._pixelOrigin=this._getNewPixelOrigin(g),_e?B&&B.pinch&&this.fire("zoom",B):((Me||B&&B.pinch)&&this.fire("zoom",B),this.fire("move",B)),this},_moveEnd:function(g){return g&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return he(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(g){lr(this._mapPane,this._getMapPanePos().subtract(g))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(g){this._targets={},this._targets[u(this._container)]=this;var S=g?Qt:Ot;S(this._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&S(window,"resize",this._onResize,this),$t.any3d&&this.options.transform3DLimit&&(g?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){he(this._resizeRequest),this._resizeRequest=ee(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var g=this._getMapPanePos();Math.max(Math.abs(g.x),Math.abs(g.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(g,S){for(var B=[],_e,Me=S==="mouseout"||S==="mouseover",Ye=g.target||g.srcElement,lt=!1;Ye;){if(_e=this._targets[u(Ye)],_e&&(S==="click"||S==="preclick")&&this._draggableMoved(_e)){lt=!0;break}if(_e&&_e.listens(S,!0)&&(Me&&!Bi(Ye,g)||(B.push(_e),Me))||Ye===this._container)break;Ye=Ye.parentNode}return!B.length&&!lt&&!Me&&this.listens(S,!0)&&(B=[this]),B},_isClickDisabled:function(g){for(;g&&g!==this._container;){if(g._leaflet_disable_click)return!0;g=g.parentNode}},_handleDOMEvent:function(g){var S=g.target||g.srcElement;if(!(!this._loaded||S._leaflet_disable_events||g.type==="click"&&this._isClickDisabled(S))){var B=g.type;B==="mousedown"&&Li(S),this._fireDOMEvent(g,B)}},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(g,S,B){if(g.type==="click"){var _e=o({},g);_e.type="preclick",this._fireDOMEvent(_e,_e.type,B)}var Me=this._findEventTargets(g,S);if(B){for(var Ye=[],lt=0;lt0?Math.round(g-S)/2:Math.max(0,Math.ceil(g))-Math.max(0,Math.floor(S))},_limitZoom:function(g){var S=this.getMinZoom(),B=this.getMaxZoom(),_e=$t.any3d?this.options.zoomSnap:1;return _e&&(g=Math.round(g/_e)*_e),Math.max(S,Math.min(B,g))},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){ar(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(g,S){var B=this._getCenterOffset(g)._trunc();return(S&&S.animate)!==!0&&!this.getSize().contains(B)?!1:(this.panBy(B,S),!0)},_createAnimProxy:function(){var g=this._proxy=Wt("div","leaflet-proxy leaflet-zoom-animated");this._panes.mapPane.appendChild(g),this.on("zoomanim",function(S){var B=ki,_e=this._proxy.style[B];Gr(this._proxy,this.project(S.center,S.zoom),this.getZoomScale(S.zoom,1)),_e===this._proxy.style[B]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on("load moveend",this._animMoveEnd,this),this._on("unload",this._destroyAnimProxy,this)},_destroyAnimProxy:function(){ir(this._proxy),this.off("load moveend",this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var g=this.getCenter(),S=this.getZoom();Gr(this._proxy,this.project(g,S),this.getZoomScale(S,1))},_catchTransitionEnd:function(g){this._animatingZoom&&g.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(g,S,B){if(this._animatingZoom)return!0;if(B=B||{},!this._zoomAnimated||B.animate===!1||this._nothingToAnimate()||Math.abs(S-this._zoom)>this.options.zoomAnimationThreshold)return!1;var _e=this.getZoomScale(S),Me=this._getCenterOffset(g)._divideBy(1-1/_e);return B.animate!==!0&&!this.getSize().contains(Me)?!1:(ee(function(){this._moveStart(!0,!1)._animateZoom(g,S,!0)},this),!0)},_animateZoom:function(g,S,B,_e){!this._mapPane||(B&&(this._animatingZoom=!0,this._animateToCenter=g,this._animateToZoom=S,Nt(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:g,zoom:S,noUpdate:_e}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(l(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){!this._animatingZoom||(this._mapPane&&ar(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function gs(g,S){return new Vt(g,S)}var Cr=xe.extend({options:{position:"topright"},initialize:function(g){T(this,g)},getPosition:function(){return this.options.position},setPosition:function(g){var S=this._map;return S&&S.removeControl(this),this.options.position=g,S&&S.addControl(this),this},getContainer:function(){return this._container},addTo:function(g){this.remove(),this._map=g;var S=this._container=this.onAdd(g),B=this.getPosition(),_e=g._controlCorners[B];return Nt(S,"leaflet-control"),B.indexOf("bottom")!==-1?_e.insertBefore(S,_e.firstChild):_e.appendChild(S),this._map.on("unload",this.remove,this),this},remove:function(){return this._map?(ir(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null,this):this},_refocusOnMap:function(g){this._map&&g&&g.screenX>0&&g.screenY>0&&this._map.getContainer().focus()}}),$n=function(g){return new Cr(g)};Vt.include({addControl:function(g){return g.addTo(this),this},removeControl:function(g){return g.remove(),this},_initControlPos:function(){var g=this._controlCorners={},S="leaflet-",B=this._controlContainer=Wt("div",S+"control-container",this._container);function _e(Me,Ye){var lt=S+Me+" "+S+Ye;g[Me+Ye]=Wt("div",lt,B)}_e("top","left"),_e("top","right"),_e("bottom","left"),_e("bottom","right")},_clearControlPos:function(){for(var g in this._controlCorners)ir(this._controlCorners[g]);ir(this._controlContainer),delete this._controlCorners,delete this._controlContainer}});var ys=Cr.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(g,S,B,_e){return B<_e?-1:_e1,this._baseLayersList.style.display=g?"":"none"),this._separator.style.display=S&&g?"":"none",this},_onLayerChange:function(g){this._handlingClick||this._update();var S=this._getLayer(u(g.target)),B=S.overlay?g.type==="add"?"overlayadd":"overlayremove":g.type==="add"?"baselayerchange":null;B&&this._map.fire(B,S)},_createRadioElement:function(g,S){var B='",_e=document.createElement("div");return _e.innerHTML=B,_e.firstChild},_addItem:function(g){var S=document.createElement("label"),B=this._map.hasLayer(g.layer),_e;g.overlay?(_e=document.createElement("input"),_e.type="checkbox",_e.className="leaflet-control-layers-selector",_e.defaultChecked=B):_e=this._createRadioElement("leaflet-base-layers_"+u(this),B),this._layerControlInputs.push(_e),_e.layerId=u(g.layer),Ot(_e,"click",this._onInputClick,this);var Me=document.createElement("span");Me.innerHTML=" "+g.name;var Ye=document.createElement("span");S.appendChild(Ye),Ye.appendChild(_e),Ye.appendChild(Me);var lt=g.overlay?this._overlaysList:this._baseLayersList;return lt.appendChild(S),this._checkDisabledLayers(),S},_onInputClick:function(){var g=this._layerControlInputs,S,B,_e=[],Me=[];this._handlingClick=!0;for(var Ye=g.length-1;Ye>=0;Ye--)S=g[Ye],B=this._getLayer(S.layerId).layer,S.checked?_e.push(B):S.checked||Me.push(B);for(Ye=0;Ye=0;Me--)S=g[Me],B=this._getLayer(S.layerId).layer,S.disabled=B.options.minZoom!==void 0&&_eB.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this}}),$o=function(g,S,B){return new ys(g,S,B)},Fi=Cr.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(g){var S="leaflet-control-zoom",B=Wt("div",S+" leaflet-bar"),_e=this.options;return this._zoomInButton=this._createButton(_e.zoomInText,_e.zoomInTitle,S+"-in",B,this._zoomIn),this._zoomOutButton=this._createButton(_e.zoomOutText,_e.zoomOutTitle,S+"-out",B,this._zoomOut),this._updateDisabled(),g.on("zoomend zoomlevelschange",this._updateDisabled,this),B},onRemove:function(g){g.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(g){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(g.shiftKey?3:1))},_createButton:function(g,S,B,_e,Me){var Ye=Wt("a",B,_e);return Ye.innerHTML=g,Ye.href="#",Ye.title=S,Ye.setAttribute("role","button"),Ye.setAttribute("aria-label",S),Pr(Ye),Ot(Ye,"click",Zr),Ot(Ye,"click",Me,this),Ot(Ye,"click",this._refocusOnMap,this),Ye},_updateDisabled:function(){var g=this._map,S="leaflet-disabled";ar(this._zoomInButton,S),ar(this._zoomOutButton,S),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),(this._disabled||g._zoom===g.getMinZoom())&&(Nt(this._zoomOutButton,S),this._zoomOutButton.setAttribute("aria-disabled","true")),(this._disabled||g._zoom===g.getMaxZoom())&&(Nt(this._zoomInButton,S),this._zoomInButton.setAttribute("aria-disabled","true"))}});Vt.mergeOptions({zoomControl:!0}),Vt.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new Fi,this.addControl(this.zoomControl))});var Lo=function(g){return new Fi(g)},vs=Cr.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(g){var S="leaflet-control-scale",B=Wt("div",S),_e=this.options;return this._addScales(_e,S+"-line",B),g.on(_e.updateWhenIdle?"moveend":"move",this._update,this),g.whenReady(this._update,this),B},onRemove:function(g){g.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(g,S,B){g.metric&&(this._mScale=Wt("div",S,B)),g.imperial&&(this._iScale=Wt("div",S,B))},_update:function(){var g=this._map,S=g.getSize().y/2,B=g.distance(g.containerPointToLatLng([0,S]),g.containerPointToLatLng([this.options.maxWidth,S]));this._updateScales(B)},_updateScales:function(g){this.options.metric&&g&&this._updateMetric(g),this.options.imperial&&g&&this._updateImperial(g)},_updateMetric:function(g){var S=this._getRoundNum(g),B=S<1e3?S+" m":S/1e3+" km";this._updateScale(this._mScale,B,S/g)},_updateImperial:function(g){var S=g*3.2808399,B,_e,Me;S>5280?(B=S/5280,_e=this._getRoundNum(B),this._updateScale(this._iScale,_e+" mi",_e/B)):(Me=this._getRoundNum(S),this._updateScale(this._iScale,Me+" ft",Me/S))},_updateScale:function(g,S,B){g.style.width=Math.round(this.options.maxWidth*B)+"px",g.innerHTML=S},_getRoundNum:function(g){var S=Math.pow(10,(Math.floor(g)+"").length-1),B=g/S;return B=B>=10?10:B>=5?5:B>=3?3:B>=2?2:1,S*B}}),_s=function(g){return new vs(g)},Ro='',Ui=Cr.extend({options:{position:"bottomright",prefix:''+($t.inlineSvg?Ro+" ":"")+"Leaflet"},initialize:function(g){T(this,g),this._attributions={}},onAdd:function(g){g.attributionControl=this,this._container=Wt("div","leaflet-control-attribution"),Pr(this._container);for(var S in g._layers)g._layers[S].getAttribution&&this.addAttribution(g._layers[S].getAttribution());return this._update(),g.on("layeradd",this._addAttribution,this),this._container},onRemove:function(g){g.off("layeradd",this._addAttribution,this)},_addAttribution:function(g){g.layer.getAttribution&&(this.addAttribution(g.layer.getAttribution()),g.layer.once("remove",function(){this.removeAttribution(g.layer.getAttribution())},this))},setPrefix:function(g){return this.options.prefix=g,this._update(),this},addAttribution:function(g){return g?(this._attributions[g]||(this._attributions[g]=0),this._attributions[g]++,this._update(),this):this},removeAttribution:function(g){return g?(this._attributions[g]&&(this._attributions[g]--,this._update()),this):this},_update:function(){if(!!this._map){var g=[];for(var S in this._attributions)this._attributions[S]&&g.push(S);var B=[];this.options.prefix&&B.push(this.options.prefix),g.length&&B.push(g.join(", ")),this._container.innerHTML=B.join(' ')}}});Vt.mergeOptions({attributionControl:!0}),Vt.addInitHook(function(){this.options.attributionControl&&new Ui().addTo(this)});var Mo=function(g){return new Ui(g)};Cr.Layers=ys,Cr.Zoom=Fi,Cr.Scale=vs,Cr.Attribution=Ui,$n.layers=$o,$n.zoom=Lo,$n.scale=_s,$n.attribution=Mo;var Ir=xe.extend({initialize:function(g){this._map=g},enable:function(){return this._enabled?this:(this._enabled=!0,this.addHooks(),this)},disable:function(){return this._enabled?(this._enabled=!1,this.removeHooks(),this):this},enabled:function(){return!!this._enabled}});Ir.addTo=function(g,S){return g.addHandler(S,this),this};var Oo={Events:ae},bs=$t.touch?"touchstart mousedown":"mousedown",Vr=ge.extend({options:{clickTolerance:3},initialize:function(g,S,B,_e){T(this,_e),this._element=g,this._dragStartTarget=S||g,this._preventOutline=B},enable:function(){this._enabled||(Ot(this._dragStartTarget,bs,this._onDown,this),this._enabled=!0)},disable:function(){!this._enabled||(Vr._dragging===this&&this.finishDrag(!0),Qt(this._dragStartTarget,bs,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(g){if(!!this._enabled&&(this._moved=!1,!Xn(this._element,"leaflet-zoom-anim"))){if(g.touches&&g.touches.length!==1){Vr._dragging===this&&this.finishDrag();return}if(!(Vr._dragging||g.shiftKey||g.which!==1&&g.button!==1&&!g.touches)&&(Vr._dragging=this,this._preventOutline&&Li(this._element),Pi(),kn(),!this._moving)){this.fire("down");var S=g.touches?g.touches[0]:g,B=Ri(this._element);this._startPoint=new se(S.clientX,S.clientY),this._startPos=qr(this._element),this._parentScale=ei(B);var _e=g.type==="mousedown";Ot(document,_e?"mousemove":"touchmove",this._onMove,this),Ot(document,_e?"mouseup":"touchend touchcancel",this._onUp,this)}}},_onMove:function(g){if(!!this._enabled){if(g.touches&&g.touches.length>1){this._moved=!0;return}var S=g.touches&&g.touches.length===1?g.touches[0]:g,B=new se(S.clientX,S.clientY)._subtract(this._startPoint);!B.x&&!B.y||Math.abs(B.x)+Math.abs(B.y)Ye&&(lt=mt,Ye=yt);Ye>B&&(S[lt]=1,Vi(g,S,B,_e,lt),Vi(g,S,B,lt,Me))}function No(g,S){for(var B=[g[0]],_e=1,Me=0,Ye=g.length;_eS&&(B.push(g[_e]),Me=_e);return MeS.max.x&&(B|=2),g.yS.max.y&&(B|=8),B}function Bo(g,S){var B=S.x-g.x,_e=S.y-g.y;return B*B+_e*_e}function Rn(g,S,B,_e){var Me=S.x,Ye=S.y,lt=B.x-Me,mt=B.y-Ye,yt=lt*lt+mt*mt,_t;return yt>0&&(_t=((g.x-Me)*lt+(g.y-Ye)*mt)/yt,_t>1?(Me=B.x,Ye=B.y):_t>0&&(Me+=lt*_t,Ye+=mt*_t)),lt=g.x-Me,mt=g.y-Ye,_e?lt*lt+mt*mt:new se(Me,Ye)}function Er(g){return!N(g[0])||typeof g[0][0]!="object"&&typeof g[0][0]<"u"}function ks(g){return console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead."),Er(g)}function Ts(g,S){var B,_e,Me,Ye,lt,mt,yt,_t;if(!g||g.length===0)throw new Error("latlngs not passed");Er(g)||(console.warn("latlngs are not flat! Only the first ring will be used"),g=g[0]);var Tt=[];for(var Mt in g)Tt.push(S.project(Le(g[Mt])));var Dt=Tt.length;for(B=0,_e=0;B_e){yt=(Ye-_e)/Me,_t=[mt.x-yt*(mt.x-lt.x),mt.y-yt*(mt.y-lt.y)];break}return S.unproject(Pe(_t))}var As={__proto__:null,simplify:ws,pointToSegmentDistance:xs,closestPointOnSegment:Do,clipSegment:Cs,_getEdgeIntersection:Ln,_getBitCode:Qr,_sqClosestPointOnSegment:Rn,isFlat:Er,_flat:ks,polylineCenter:Ts};function Mn(g,S,B){var _e,Me=[1,4,2,8],Ye,lt,mt,yt,_t,Tt,Mt,Dt;for(Ye=0,Tt=g.length;Ye1e-7;mt++)_t=Me*Math.sin(lt),_t=Math.pow((1-_t)/(1+_t),Me/2),yt=Math.PI/2-2*Math.atan(Ye*_t)-lt,lt+=yt;return new Ce(lt*S,g.x*S/B)}},Fo={__proto__:null,LonLat:Hi,Mercator:ii,SphericalMercator:Re},Is=o({},Oe,{code:"EPSG:3395",projection:ii,transformation:function(){var g=.5/(Math.PI*ii.R);return we(g,.5,-g,.5)}()}),$s=o({},Oe,{code:"EPSG:4326",projection:Hi,transformation:we(1/180,1,-1/180,.5)}),On=o({},Fe,{projection:Hi,transformation:we(1,0,-1,0),scale:function(g){return Math.pow(2,g)},zoom:function(g){return Math.log(g)/Math.LN2},distance:function(g,S){var B=S.lng-g.lng,_e=S.lat-g.lat;return Math.sqrt(B*B+_e*_e)},infinite:!0});Fe.Earth=Oe,Fe.EPSG3395=Is,Fe.EPSG3857=oe,Fe.EPSG900913=pe,Fe.EPSG4326=$s,Fe.Simple=On;var kr=ge.extend({options:{pane:"overlayPane",attribution:null,bubblingMouseEvents:!0},addTo:function(g){return g.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(g){return g&&g.removeLayer(this),this},getPane:function(g){return this._map.getPane(g?this.options[g]||g:this.options.pane)},addInteractiveTarget:function(g){return this._map._targets[u(g)]=this,this},removeInteractiveTarget:function(g){return delete this._map._targets[u(g)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(g){var S=g.target;if(!!S.hasLayer(this)){if(this._map=S,this._zoomAnimated=S._zoomAnimated,this.getEvents){var B=this.getEvents();S.on(B,this),this.once("remove",function(){S.off(B,this)},this)}this.onAdd(S),this.fire("add"),S.fire("layeradd",{layer:this})}}});Vt.include({addLayer:function(g){if(!g._layerAdd)throw new Error("The provided object is not a Layer.");var S=u(g);return this._layers[S]?this:(this._layers[S]=g,g._mapToAdd=this,g.beforeAdd&&g.beforeAdd(this),this.whenReady(g._layerAdd,g),this)},removeLayer:function(g){var S=u(g);return this._layers[S]?(this._loaded&&g.onRemove(this),delete this._layers[S],this._loaded&&(this.fire("layerremove",{layer:g}),g.fire("remove")),g._map=g._mapToAdd=null,this):this},hasLayer:function(g){return u(g)in this._layers},eachLayer:function(g,S){for(var B in this._layers)g.call(S,this._layers[B]);return this},_addLayers:function(g){g=g?N(g)?g:[g]:[];for(var S=0,B=g.length;Sthis._layersMaxZoom&&this.setZoom(this._layersMaxZoom),this.options.minZoom===void 0&&this._layersMinZoom&&this.getZoom()=2&&S[0]instanceof Ce&&S[0].equals(S[B-1])&&S.pop(),S},_setLatLngs:function(g){$r.prototype._setLatLngs.call(this,g),Er(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return Er(this._latlngs[0])?this._latlngs[0]:this._latlngs[0][0]},_clipPoints:function(){var g=this._renderer._bounds,S=this.options.weight,B=new se(S,S);if(g=new Ue(g.min.subtract(B),g.max.add(B)),this._parts=[],!(!this._pxBounds||!this._pxBounds.intersects(g))){if(this.options.noClip){this._parts=this._rings;return}for(var _e=0,Me=this._rings.length,Ye;_eg.y!=Me.y>g.y&&g.x<(Me.x-_e.x)*(g.y-_e.y)/(Me.y-_e.y)+_e.x&&(S=!S);return S||$r.prototype._containsPoint.call(this,g,!0)}});function oi(g,S){return new en(g,S)}var Rr=Jr.extend({initialize:function(g,S){T(this,S),this._layers={},g&&this.addData(g)},addData:function(g){var S=N(g)?g:g.features,B,_e,Me;if(S){for(B=0,_e=S.length;B<_e;B++)Me=S[B],(Me.geometries||Me.geometry||Me.features||Me.coordinates)&&this.addData(Me);return this}var Ye=this.options;if(Ye.filter&&!Ye.filter(g))return this;var lt=Fn(g,Ye);return lt?(lt.feature=tn(g),lt.defaultOptions=lt.options,this.resetStyle(lt),Ye.onEachFeature&&Ye.onEachFeature(g,lt),this.addLayer(lt)):this},resetStyle:function(g){return g===void 0?this.eachLayer(this.resetStyle,this):(g.options=o({},g.defaultOptions),this._setLayerStyle(g,this.options.style),this)},setStyle:function(g){return this.eachLayer(function(S){this._setLayerStyle(S,g)},this)},_setLayerStyle:function(g,S){g.setStyle&&(typeof S=="function"&&(S=S(g.feature)),g.setStyle(S))}});function Fn(g,S){var B=g.type==="Feature"?g.geometry:g,_e=B?B.coordinates:null,Me=[],Ye=S&&S.pointToLayer,lt=S&&S.coordsToLatLng||zi,mt,yt,_t,Tt;if(!_e&&!B)return null;switch(B.type){case"Point":return mt=lt(_e),Ds(Ye,g,mt,S);case"MultiPoint":for(_t=0,Tt=_e.length;_t0?_e:[S.src];return}N(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(S.style,"objectFit")&&(S.style.objectFit="fill"),S.autoplay=!!this.options.autoplay,S.loop=!!this.options.loop,S.muted=!!this.options.muted,S.playsInline=!!this.options.playsInline;for(var Ye=0;YeMe?(S.height=Me+"px",Nt(g,Ye)):ar(g,Ye),this._containerWidth=this._container.offsetWidth},_animateZoom:function(g){var S=this._map._latLngToNewLayerPoint(this._latlng,g.zoom,g.center),B=this._getAnchor();lr(this._container,S.add(B))},_adjustPan:function(g){if(!!this.options.autoPan){this._map._panAnim&&this._map._panAnim.stop();var S=this._map,B=parseInt(Ar(this._container,"marginBottom"),10)||0,_e=this._container.offsetHeight+B,Me=this._containerWidth,Ye=new se(this._containerLeft,-_e-this._containerBottom);Ye._add(qr(this._container));var lt=S.layerPointToContainerPoint(Ye),mt=Pe(this.options.autoPanPadding),yt=Pe(this.options.autoPanPaddingTopLeft||mt),_t=Pe(this.options.autoPanPaddingBottomRight||mt),Tt=S.getSize(),Mt=0,Dt=0;lt.x+Me+_t.x>Tt.x&&(Mt=lt.x+Me-Tt.x+_t.x),lt.x-Mt-yt.x<0&&(Mt=lt.x-yt.x),lt.y+_e+_t.y>Tt.y&&(Dt=lt.y+_e-Tt.y+_t.y),lt.y-Dt-yt.y<0&&(Dt=lt.y-yt.y),(Mt||Dt)&&S.fire("autopanstart").panBy([Mt,Dt],{animate:g&&g.type==="moveend"})}},_getAnchor:function(){return Pe(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}}),Yo=function(g,S){return new rn(g,S)};Vt.mergeOptions({closePopupOnClick:!0}),Vt.include({openPopup:function(g,S,B){return this._initOverlay(rn,g,S,B).openOn(this),this},closePopup:function(g){return g=arguments.length?g:this._popup,g&&g.close(),this}}),kr.include({bindPopup:function(g,S){return this._popup=this._initOverlay(rn,this._popup,g,S),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(g){return this._popup&&this._popup._prepareOpen(g||this._latlng)&&this._popup.openOn(this._map),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return this._popup?this._popup.isOpen():!1},setPopupContent:function(g){return this._popup&&this._popup.setContent(g),this},getPopup:function(){return this._popup},_openPopup:function(g){if(!(!this._popup||!this._map)){Zr(g);var S=g.layer||g.target;if(this._popup._source===S&&!(S instanceof Hr)){this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(g.latlng);return}this._popup._source=S,this.openPopup(g.latlng)}},_movePopup:function(g){this._popup.setLatLng(g.latlng)},_onKeyPress:function(g){g.originalEvent.keyCode===13&&this._openPopup(g)}});var ci=Lr.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(g){Lr.prototype.onAdd.call(this,g),this.setOpacity(this.options.opacity),g.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(g){Lr.prototype.onRemove.call(this,g),g.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var g=Lr.prototype.getEvents.call(this);return this.options.permanent||(g.preclick=this.close),g},_initLayout:function(){var g="leaflet-tooltip",S=g+" "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=Wt("div",S),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+u(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(g){var S,B,_e=this._map,Me=this._container,Ye=_e.latLngToContainerPoint(_e.getCenter()),lt=_e.layerPointToContainerPoint(g),mt=this.options.direction,yt=Me.offsetWidth,_t=Me.offsetHeight,Tt=Pe(this.options.offset),Mt=this._getAnchor();mt==="top"?(S=yt/2,B=_t):mt==="bottom"?(S=yt/2,B=0):mt==="center"?(S=yt/2,B=_t/2):mt==="right"?(S=0,B=_t/2):mt==="left"?(S=yt,B=_t/2):lt.xthis.options.maxZoom||B_e?this._retainParent(Me,Ye,lt,_e):!1)},_retainChildren:function(g,S,B,_e){for(var Me=2*g;Me<2*g+2;Me++)for(var Ye=2*S;Ye<2*S+2;Ye++){var lt=new se(Me,Ye);lt.z=B+1;var mt=this._tileCoordsToKey(lt),yt=this._tiles[mt];if(yt&&yt.active){yt.retain=!0;continue}else yt&&yt.loaded&&(yt.retain=!0);B+1<_e&&this._retainChildren(Me,Ye,B+1,_e)}},_resetView:function(g){var S=g&&(g.pinch||g.flyTo);this._setView(this._map.getCenter(),this._map.getZoom(),S,S)},_animateZoom:function(g){this._setView(g.center,g.zoom,!0,g.noUpdate)},_clampZoom:function(g){var S=this.options;return S.minNativeZoom!==void 0&&gthis.options.maxZoom||this.options.minZoom!==void 0&&Me1){this._setView(g,B);return}for(var Mt=Me.min.y;Mt<=Me.max.y;Mt++)for(var Dt=Me.min.x;Dt<=Me.max.x;Dt++){var br=new se(Dt,Mt);if(br.z=this._tileZoom,!!this._isValidTile(br)){var Wr=this._tiles[this._tileCoordsToKey(br)];Wr?Wr.current=!0:lt.push(br)}}if(lt.sort(function(Or,Wn){return Or.distanceTo(Ye)-Wn.distanceTo(Ye)}),lt.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var fi=document.createDocumentFragment();for(Dt=0;DtB.max.x)||!S.wrapLat&&(g.yB.max.y))return!1}if(!this.options.bounds)return!0;var _e=this._tileCoordsToBounds(g);return ye(this.options.bounds).overlaps(_e)},_keyToBounds:function(g){return this._tileCoordsToBounds(this._keyToTileCoords(g))},_tileCoordsToNwSe:function(g){var S=this._map,B=this.getTileSize(),_e=g.scaleBy(B),Me=_e.add(B),Ye=S.unproject(_e,g.z),lt=S.unproject(Me,g.z);return[Ye,lt]},_tileCoordsToBounds:function(g){var S=this._tileCoordsToNwSe(g),B=new fe(S[0],S[1]);return this.options.noWrap||(B=this._map.wrapLatLngBounds(B)),B},_tileCoordsToKey:function(g){return g.x+":"+g.y+":"+g.z},_keyToTileCoords:function(g){var S=g.split(":"),B=new se(+S[0],+S[1]);return B.z=+S[2],B},_removeTile:function(g){var S=this._tiles[g];!S||(ir(S.el),delete this._tiles[g],this.fire("tileunload",{tile:S.el,coords:this._keyToTileCoords(g)}))},_initTile:function(g){Nt(g,"leaflet-tile");var S=this.getTileSize();g.style.width=S.x+"px",g.style.height=S.y+"px",g.onselectstart=x,g.onmousemove=x,$t.ielt9&&this.options.opacity<1&&xr(g,this.options.opacity)},_addTile:function(g,S){var B=this._getTilePos(g),_e=this._tileCoordsToKey(g),Me=this.createTile(this._wrapCoords(g),l(this._tileReady,this,g));this._initTile(Me),this.createTile.length<2&&ee(l(this._tileReady,this,g,null,Me)),lr(Me,B),this._tiles[_e]={el:Me,coords:g,current:!0},S.appendChild(Me),this.fire("tileloadstart",{tile:Me,coords:g})},_tileReady:function(g,S,B){S&&this.fire("tileerror",{error:S,tile:B,coords:g});var _e=this._tileCoordsToKey(g);B=this._tiles[_e],B&&(B.loaded=+new Date,this._map._fadeAnimated?(xr(B.el,0),he(this._fadeFrame),this._fadeFrame=ee(this._updateOpacity,this)):(B.active=!0,this._pruneTiles()),S||(Nt(B.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:B.el,coords:g})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),$t.ielt9||!this._map._fadeAnimated?ee(this._pruneTiles,this):setTimeout(l(this._pruneTiles,this),250)))},_getTilePos:function(g){return g.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(g){var S=new se(this._wrapX?b(g.x,this._wrapX):g.x,this._wrapY?b(g.y,this._wrapY):g.y);return S.z=g.z,S},_pxBoundsToTileRange:function(g){var S=this.getTileSize();return new Ue(g.min.unscaleBy(S).floor(),g.max.unscaleBy(S).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var g in this._tiles)if(!this._tiles[g].loaded)return!1;return!0}});function qo(g){return new Vn(g)}var nn=Vn.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(g,S){this._url=g,S=T(this,S),S.detectRetina&&$t.retina&&S.maxZoom>0?(S.tileSize=Math.floor(S.tileSize/2),S.zoomReverse?(S.zoomOffset--,S.minZoom=Math.min(S.maxZoom,S.minZoom+1)):(S.zoomOffset++,S.maxZoom=Math.max(S.minZoom,S.maxZoom-1)),S.minZoom=Math.max(0,S.minZoom)):S.zoomReverse?S.minZoom=Math.min(S.maxZoom,S.minZoom):S.maxZoom=Math.max(S.minZoom,S.maxZoom),typeof S.subdomains=="string"&&(S.subdomains=S.subdomains.split("")),this.on("tileunload",this._onTileRemove)},setUrl:function(g,S){return this._url===g&&S===void 0&&(S=!0),this._url=g,S||this.redraw(),this},createTile:function(g,S){var B=document.createElement("img");return Ot(B,"load",l(this._tileOnLoad,this,S,B)),Ot(B,"error",l(this._tileOnError,this,S,B)),(this.options.crossOrigin||this.options.crossOrigin==="")&&(B.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),typeof this.options.referrerPolicy=="string"&&(B.referrerPolicy=this.options.referrerPolicy),B.alt="",B.src=this.getTileUrl(g),B},getTileUrl:function(g){var S={r:$t.retina?"@2x":"",s:this._getSubdomain(g),x:g.x,y:g.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var B=this._globalTileRange.max.y-g.y;this.options.tms&&(S.y=B),S["-y"]=B}return D(this._url,o(S,this.options))},_tileOnLoad:function(g,S){$t.ielt9?setTimeout(l(g,this,null,S),0):g(null,S)},_tileOnError:function(g,S,B){var _e=this.options.errorTileUrl;_e&&S.getAttribute("src")!==_e&&(S.src=_e),g(B,S)},_onTileRemove:function(g){g.tile.onload=null},_getZoomForUrl:function(){var g=this._tileZoom,S=this.options.maxZoom,B=this.options.zoomReverse,_e=this.options.zoomOffset;return B&&(g=S-g),g+_e},_getSubdomain:function(g){var S=Math.abs(g.x+g.y)%this.options.subdomains.length;return this.options.subdomains[S]},_abortLoading:function(){var g,S;for(g in this._tiles)if(this._tiles[g].coords.z!==this._tileZoom&&(S=this._tiles[g].el,S.onload=x,S.onerror=x,!S.complete)){S.src=ie;var B=this._tiles[g].coords;ir(S),delete this._tiles[g],this.fire("tileabort",{tile:S,coords:B})}},_removeTile:function(g){var S=this._tiles[g];if(!!S)return S.el.setAttribute("src",ie),Vn.prototype._removeTile.call(this,g)},_tileReady:function(g,S,B){if(!(!this._map||B&&B.getAttribute("src")===ie))return Vn.prototype._tileReady.call(this,g,S,B)}});function Yi(g,S){return new nn(g,S)}var Us=nn.extend({defaultWmsParams:{service:"WMS",request:"GetMap",layers:"",styles:"",format:"image/jpeg",transparent:!1,version:"1.1.1"},options:{crs:null,uppercase:!1},initialize:function(g,S){this._url=g;var B=o({},this.defaultWmsParams);for(var _e in S)_e in this.options||(B[_e]=S[_e]);S=T(this,S);var Me=S.detectRetina&&$t.retina?2:1,Ye=this.getTileSize();B.width=Ye.x*Me,B.height=Ye.y*Me,this.wmsParams=B},onAdd:function(g){this._crs=this.options.crs||g.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var S=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[S]=this._crs.code,nn.prototype.onAdd.call(this,g)},getTileUrl:function(g){var S=this._tileCoordsToNwSe(g),B=this._crs,_e=Be(B.project(S[0]),B.project(S[1])),Me=_e.min,Ye=_e.max,lt=(this._wmsVersion>=1.3&&this._crs===$s?[Me.y,Me.x,Ye.y,Ye.x]:[Me.x,Me.y,Ye.x,Ye.y]).join(","),mt=nn.prototype.getTileUrl.call(this,g);return mt+O(this.wmsParams,mt,this.options.uppercase)+(this.options.uppercase?"&BBOX=":"&bbox=")+lt},setParams:function(g,S){return o(this.wmsParams,g),S||this.redraw(),this}});function Xo(g,S){return new Us(g,S)}nn.WMS=Us,Yi.wms=Xo;var Mr=kr.extend({options:{padding:.1},initialize:function(g){T(this,g),u(this),this._layers=this._layers||{}},onAdd:function(){this._container||(this._initContainer(),this._zoomAnimated&&Nt(this._container,"leaflet-zoom-animated")),this.getPane().appendChild(this._container),this._update(),this.on("update",this._updatePaths,this)},onRemove:function(){this.off("update",this._updatePaths,this),this._destroyContainer()},getEvents:function(){var g={viewreset:this._reset,zoom:this._onZoom,moveend:this._update,zoomend:this._onZoomEnd};return this._zoomAnimated&&(g.zoomanim=this._onAnimZoom),g},_onAnimZoom:function(g){this._updateTransform(g.center,g.zoom)},_onZoom:function(){this._updateTransform(this._map.getCenter(),this._map.getZoom())},_updateTransform:function(g,S){var B=this._map.getZoomScale(S,this._zoom),_e=this._map.getSize().multiplyBy(.5+this.options.padding),Me=this._map.project(this._center,S),Ye=_e.multiplyBy(-B).add(Me).subtract(this._map._getNewPixelOrigin(g,S));$t.any3d?Gr(this._container,Ye,B):lr(this._container,Ye)},_reset:function(){this._update(),this._updateTransform(this._center,this._zoom);for(var g in this._layers)this._layers[g]._reset()},_onZoomEnd:function(){for(var g in this._layers)this._layers[g]._project()},_updatePaths:function(){for(var g in this._layers)this._layers[g]._update()},_update:function(){var g=this.options.padding,S=this._map.getSize(),B=this._map.containerPointToLayerPoint(S.multiplyBy(-g)).round();this._bounds=new Ue(B,B.add(S.multiplyBy(1+g*2)).round()),this._center=this._map.getCenter(),this._zoom=this._map.getZoom()}}),Vs=Mr.extend({options:{tolerance:0},getEvents:function(){var g=Mr.prototype.getEvents.call(this);return g.viewprereset=this._onViewPreReset,g},_onViewPreReset:function(){this._postponeUpdatePaths=!0},onAdd:function(){Mr.prototype.onAdd.call(this),this._draw()},_initContainer:function(){var g=this._container=document.createElement("canvas");Ot(g,"mousemove",this._onMouseMove,this),Ot(g,"click dblclick mousedown mouseup contextmenu",this._onClick,this),Ot(g,"mouseout",this._handleMouseOut,this),g._leaflet_disable_events=!0,this._ctx=g.getContext("2d")},_destroyContainer:function(){he(this._redrawRequest),delete this._ctx,ir(this._container),Qt(this._container),delete this._container},_updatePaths:function(){if(!this._postponeUpdatePaths){var g;this._redrawBounds=null;for(var S in this._layers)g=this._layers[S],g._update();this._redraw()}},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Mr.prototype._update.call(this);var g=this._bounds,S=this._container,B=g.getSize(),_e=$t.retina?2:1;lr(S,g.min),S.width=_e*B.x,S.height=_e*B.y,S.style.width=B.x+"px",S.style.height=B.y+"px",$t.retina&&this._ctx.scale(2,2),this._ctx.translate(-g.min.x,-g.min.y),this.fire("update")}},_reset:function(){Mr.prototype._reset.call(this),this._postponeUpdatePaths&&(this._postponeUpdatePaths=!1,this._updatePaths())},_initPath:function(g){this._updateDashArray(g),this._layers[u(g)]=g;var S=g._order={layer:g,prev:this._drawLast,next:null};this._drawLast&&(this._drawLast.next=S),this._drawLast=S,this._drawFirst=this._drawFirst||this._drawLast},_addPath:function(g){this._requestRedraw(g)},_removePath:function(g){var S=g._order,B=S.next,_e=S.prev;B?B.prev=_e:this._drawLast=_e,_e?_e.next=B:this._drawFirst=B,delete g._order,delete this._layers[u(g)],this._requestRedraw(g)},_updatePath:function(g){this._extendRedrawBounds(g),g._project(),g._update(),this._requestRedraw(g)},_updateStyle:function(g){this._updateDashArray(g),this._requestRedraw(g)},_updateDashArray:function(g){if(typeof g.options.dashArray=="string"){var S=g.options.dashArray.split(/[, ]+/),B=[],_e,Me;for(Me=0;Me')}}catch{}return function(g){return document.createElement("<"+g+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),Zo={_initContainer:function(){this._container=Wt("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Mr.prototype._update.call(this),this.fire("update"))},_initPath:function(g){var S=g._container=Hn("shape");Nt(S,"leaflet-vml-shape "+(this.options.className||"")),S.coordsize="1 1",g._path=Hn("path"),S.appendChild(g._path),this._updateStyle(g),this._layers[u(g)]=g},_addPath:function(g){var S=g._container;this._container.appendChild(S),g.options.interactive&&g.addInteractiveTarget(S)},_removePath:function(g){var S=g._container;ir(S),g.removeInteractiveTarget(S),delete this._layers[u(g)]},_updateStyle:function(g){var S=g._stroke,B=g._fill,_e=g.options,Me=g._container;Me.stroked=!!_e.stroke,Me.filled=!!_e.fill,_e.stroke?(S||(S=g._stroke=Hn("stroke")),Me.appendChild(S),S.weight=_e.weight+"px",S.color=_e.color,S.opacity=_e.opacity,_e.dashArray?S.dashStyle=N(_e.dashArray)?_e.dashArray.join(" "):_e.dashArray.replace(/( *, *)/g," "):S.dashStyle="",S.endcap=_e.lineCap.replace("butt","flat"),S.joinstyle=_e.lineJoin):S&&(Me.removeChild(S),g._stroke=null),_e.fill?(B||(B=g._fill=Hn("fill")),Me.appendChild(B),B.color=_e.fillColor||_e.color,B.opacity=_e.fillOpacity):B&&(Me.removeChild(B),g._fill=null)},_updateCircle:function(g){var S=g._point.round(),B=Math.round(g._radius),_e=Math.round(g._radiusY||B);this._setPath(g,g._empty()?"M0 0":"AL "+S.x+","+S.y+" "+B+","+_e+" 0,"+65535*360)},_setPath:function(g,S){g._path.v=S},_bringToFront:function(g){fn(g._container)},_bringToBack:function(g){dn(g._container)}},hi=$t.vml?Hn:ke,zn=Mr.extend({_initContainer:function(){this._container=hi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=hi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){ir(this._container),Qt(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Mr.prototype._update.call(this);var g=this._bounds,S=g.getSize(),B=this._container;(!this._svgSize||!this._svgSize.equals(S))&&(this._svgSize=S,B.setAttribute("width",S.x),B.setAttribute("height",S.y)),lr(B,g.min),B.setAttribute("viewBox",[g.min.x,g.min.y,S.x,S.y].join(" ")),this.fire("update")}},_initPath:function(g){var S=g._path=hi("path");g.options.className&&Nt(S,g.options.className),g.options.interactive&&Nt(S,"leaflet-interactive"),this._updateStyle(g),this._layers[u(g)]=g},_addPath:function(g){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(g._path),g.addInteractiveTarget(g._path)},_removePath:function(g){ir(g._path),g.removeInteractiveTarget(g._path),delete this._layers[u(g)]},_updatePath:function(g){g._project(),g._update()},_updateStyle:function(g){var S=g._path,B=g.options;!S||(B.stroke?(S.setAttribute("stroke",B.color),S.setAttribute("stroke-opacity",B.opacity),S.setAttribute("stroke-width",B.weight),S.setAttribute("stroke-linecap",B.lineCap),S.setAttribute("stroke-linejoin",B.lineJoin),B.dashArray?S.setAttribute("stroke-dasharray",B.dashArray):S.removeAttribute("stroke-dasharray"),B.dashOffset?S.setAttribute("stroke-dashoffset",B.dashOffset):S.removeAttribute("stroke-dashoffset")):S.setAttribute("stroke","none"),B.fill?(S.setAttribute("fill",B.fillColor||B.color),S.setAttribute("fill-opacity",B.fillOpacity),S.setAttribute("fill-rule",B.fillRule||"evenodd")):S.setAttribute("fill","none"))},_updatePoly:function(g,S){this._setPath(g,Ne(g._parts,S))},_updateCircle:function(g){var S=g._point,B=Math.max(Math.round(g._radius),1),_e=Math.max(Math.round(g._radiusY),1)||B,Me="a"+B+","+_e+" 0 1,0 ",Ye=g._empty()?"M0 0":"M"+(S.x-B)+","+S.y+Me+B*2+",0 "+Me+-B*2+",0 ";this._setPath(g,Ye)},_setPath:function(g,S){g._path.setAttribute("d",S)},_bringToFront:function(g){fn(g._path)},_bringToBack:function(g){dn(g._path)}});$t.vml&&zn.include(Zo);function zs(g){return $t.svg||$t.vml?new zn(g):null}Vt.include({getRenderer:function(g){var S=g.options.renderer||this._getPaneRenderer(g.options.pane)||this.options.renderer||this._renderer;return S||(S=this._renderer=this._createRenderer()),this.hasLayer(S)||this.addLayer(S),S},_getPaneRenderer:function(g){if(g==="overlayPane"||g===void 0)return!1;var S=this._paneRenderers[g];return S===void 0&&(S=this._createRenderer({pane:g}),this._paneRenderers[g]=S),S},_createRenderer:function(g){return this.options.preferCanvas&&Hs(g)||zs(g)}});var Ws=en.extend({initialize:function(g,S){en.prototype.initialize.call(this,this._boundsToLatLngs(g),S)},setBounds:function(g){return this.setLatLngs(this._boundsToLatLngs(g))},_boundsToLatLngs:function(g){return g=ye(g),[g.getSouthWest(),g.getNorthWest(),g.getNorthEast(),g.getSouthEast()]}});function Qo(g,S){return new Ws(g,S)}zn.create=hi,zn.pointsToPath=Ne,Rr.geometryToLayer=Fn,Rr.coordsToLatLng=zi,Rr.coordsToLatLngs=ai,Rr.latLngToCoords=Wi,Rr.latLngsToCoords=li,Rr.getFeature=zr,Rr.asFeature=tn,Vt.mergeOptions({boxZoom:!0});var js=Ir.extend({initialize:function(g){this._map=g,this._container=g._container,this._pane=g._panes.overlayPane,this._resetStateTimeout=0,g.on("unload",this._destroy,this)},addHooks:function(){Ot(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){Qt(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){ir(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){this._resetStateTimeout!==0&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(g){if(!g.shiftKey||g.which!==1&&g.button!==1)return!1;this._clearDeferredResetState(),this._resetState(),kn(),Pi(),this._startPoint=this._map.mouseEventToContainerPoint(g),Ot(document,{contextmenu:Zr,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(g){this._moved||(this._moved=!0,this._box=Wt("div","leaflet-zoom-box",this._container),Nt(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(g);var S=new Ue(this._point,this._startPoint),B=S.getSize();lr(this._box,S.min),this._box.style.width=B.x+"px",this._box.style.height=B.y+"px"},_finish:function(){this._moved&&(ir(this._box),ar(this._container,"leaflet-crosshair")),Tn(),Ii(),Qt(document,{contextmenu:Zr,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(g){if(!(g.which!==1&&g.button!==1)&&(this._finish(),!!this._moved)){this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(l(this._resetState,this),0);var S=new fe(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point));this._map.fitBounds(S).fire("boxzoomend",{boxZoomBounds:S})}},_onKeyDown:function(g){g.keyCode===27&&(this._finish(),this._clearDeferredResetState(),this._resetState())}});Vt.addInitHook("addHandler","boxZoom",js),Vt.mergeOptions({doubleClickZoom:!0});var Ks=Ir.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(g){var S=this._map,B=S.getZoom(),_e=S.options.zoomDelta,Me=g.originalEvent.shiftKey?B-_e:B+_e;S.options.doubleClickZoom==="center"?S.setZoom(Me):S.setZoomAround(g.containerPoint,Me)}});Vt.addInitHook("addHandler","doubleClickZoom",Ks),Vt.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0});var Gi=Ir.extend({addHooks:function(){if(!this._draggable){var g=this._map;this._draggable=new Vr(g._mapPane,g._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),g.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),g.on("zoomend",this._onZoomEnd,this),g.whenReady(this._onZoomEnd,this))}Nt(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){ar(this._map._container,"leaflet-grab"),ar(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var g=this._map;if(g._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity){var S=ye(this._map.options.maxBounds);this._offsetLimit=Be(this._map.latLngToContainerPoint(S.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(S.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))}else this._offsetLimit=null;g.fire("movestart").fire("dragstart"),g.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(g){if(this._map.options.inertia){var S=this._lastTime=+new Date,B=this._lastPos=this._draggable._absPos||this._draggable._newPos;this._positions.push(B),this._times.push(S),this._prunePositions(S)}this._map.fire("move",g).fire("drag",g)},_prunePositions:function(g){for(;this._positions.length>1&&g-this._times[0]>50;)this._positions.shift(),this._times.shift()},_onZoomEnd:function(){var g=this._map.getSize().divideBy(2),S=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=S.subtract(g).x,this._worldWidth=this._map.getPixelWorldBounds().getSize().x},_viscousLimit:function(g,S){return g-(g-S)*this._viscosity},_onPreDragLimit:function(){if(!(!this._viscosity||!this._offsetLimit)){var g=this._draggable._newPos.subtract(this._draggable._startPos),S=this._offsetLimit;g.xS.max.x&&(g.x=this._viscousLimit(g.x,S.max.x)),g.y>S.max.y&&(g.y=this._viscousLimit(g.y,S.max.y)),this._draggable._newPos=this._draggable._startPos.add(g)}},_onPreDragWrap:function(){var g=this._worldWidth,S=Math.round(g/2),B=this._initialWorldOffset,_e=this._draggable._newPos.x,Me=(_e-S+B)%g+S-B,Ye=(_e+S+B)%g-S-B,lt=Math.abs(Me+B)0?Ye:-Ye))-S;this._delta=0,this._startTime=null,lt&&(g.options.scrollWheelZoom==="center"?g.setZoom(S+lt):g.setZoomAround(this._lastMousePos,S+lt))}});Vt.addInitHook("addHandler","scrollWheelZoom",Ys);var Gs=600;Vt.mergeOptions({tapHold:$t.touchNative&&$t.safari&&$t.mobile,tapTolerance:15});var qs=Ir.extend({addHooks:function(){Ot(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){Qt(this._map._container,"touchstart",this._onDown,this)},_onDown:function(g){if(clearTimeout(this._holdTimeout),g.touches.length===1){var S=g.touches[0];this._startPos=this._newPos=new se(S.clientX,S.clientY),this._holdTimeout=setTimeout(l(function(){this._cancel(),this._isTapValid()&&(Ot(document,"touchend",ur),Ot(document,"touchend touchcancel",this._cancelClickPrevent),this._simulateEvent("contextmenu",S))},this),Gs),Ot(document,"touchend touchcancel contextmenu",this._cancel,this),Ot(document,"touchmove",this._onMove,this)}},_cancelClickPrevent:function g(){Qt(document,"touchend",ur),Qt(document,"touchend touchcancel",g)},_cancel:function(){clearTimeout(this._holdTimeout),Qt(document,"touchend touchcancel contextmenu",this._cancel,this),Qt(document,"touchmove",this._onMove,this)},_onMove:function(g){var S=g.touches[0];this._newPos=new se(S.clientX,S.clientY)},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_simulateEvent:function(g,S){var B=new MouseEvent(g,{bubbles:!0,cancelable:!0,view:window,screenX:S.screenX,screenY:S.screenY,clientX:S.clientX,clientY:S.clientY});B._simulated=!0,S.target.dispatchEvent(B)}});Vt.addInitHook("addHandler","tapHold",qs),Vt.mergeOptions({touchZoom:$t.touch,bounceAtZoomLimits:!0});var Xs=Ir.extend({addHooks:function(){Nt(this._map._container,"leaflet-touch-zoom"),Ot(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){ar(this._map._container,"leaflet-touch-zoom"),Qt(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(g){var S=this._map;if(!(!g.touches||g.touches.length!==2||S._animatingZoom||this._zooming)){var B=S.mouseEventToContainerPoint(g.touches[0]),_e=S.mouseEventToContainerPoint(g.touches[1]);this._centerPoint=S.getSize()._divideBy(2),this._startLatLng=S.containerPointToLatLng(this._centerPoint),S.options.touchZoom!=="center"&&(this._pinchStartLatLng=S.containerPointToLatLng(B.add(_e)._divideBy(2))),this._startDist=B.distanceTo(_e),this._startZoom=S.getZoom(),this._moved=!1,this._zooming=!0,S._stop(),Ot(document,"touchmove",this._onTouchMove,this),Ot(document,"touchend touchcancel",this._onTouchEnd,this),ur(g)}},_onTouchMove:function(g){if(!(!g.touches||g.touches.length!==2||!this._zooming)){var S=this._map,B=S.mouseEventToContainerPoint(g.touches[0]),_e=S.mouseEventToContainerPoint(g.touches[1]),Me=B.distanceTo(_e)/this._startDist;if(this._zoom=S.getScaleZoom(Me,this._startZoom),!S.options.bounceAtZoomLimits&&(this._zoomS.getMaxZoom()&&Me>1)&&(this._zoom=S._limitZoom(this._zoom)),S.options.touchZoom==="center"){if(this._center=this._startLatLng,Me===1)return}else{var Ye=B._add(_e)._divideBy(2)._subtract(this._centerPoint);if(Me===1&&Ye.x===0&&Ye.y===0)return;this._center=S.unproject(S.project(this._pinchStartLatLng,this._zoom).subtract(Ye),this._zoom)}this._moved||(S._moveStart(!0,!1),this._moved=!0),he(this._animRequest);var lt=l(S._move,S,this._center,this._zoom,{pinch:!0,round:!1},void 0);this._animRequest=ee(lt,this,!0),ur(g)}},_onTouchEnd:function(){if(!this._moved||!this._zooming){this._zooming=!1;return}this._zooming=!1,he(this._animRequest),Qt(document,"touchmove",this._onTouchMove,this),Qt(document,"touchend touchcancel",this._onTouchEnd,this),this._map.options.zoomAnimation?this._map._animateZoom(this._center,this._map._limitZoom(this._zoom),!0,this._map.options.zoomSnap):this._map._resetView(this._center,this._map._limitZoom(this._zoom))}});Vt.addInitHook("addHandler","touchZoom",Xs),Vt.BoxZoom=js,Vt.DoubleClickZoom=Ks,Vt.Drag=Gi,Vt.Keyboard=qi,Vt.ScrollWheelZoom=Ys,Vt.TapHold=qs,Vt.TouchZoom=Xs,r.Bounds=Ue,r.Browser=$t,r.CRS=Fe,r.Canvas=Vs,r.Circle=Bn,r.CircleMarker=si,r.Class=xe,r.Control=Cr,r.DivIcon=ui,r.DivOverlay=Lr,r.DomEvent=Io,r.DomUtil=Po,r.Draggable=Vr,r.Evented=ge,r.FeatureGroup=Jr,r.GeoJSON=Rr,r.GridLayer=Vn,r.Handler=Ir,r.Icon=mn,r.ImageOverlay=gn,r.LatLng=Ce,r.LatLngBounds=fe,r.Layer=kr,r.LayerGroup=pn,r.LineUtil=As,r.Map=Vt,r.Marker=Nn,r.Mixin=Oo,r.Path=Hr,r.Point=se,r.PolyUtil=Ps,r.Polygon=en,r.Polyline=$r,r.Popup=rn,r.PosAnimation=ps,r.Projection=Fo,r.Rectangle=Ws,r.Renderer=Mr,r.SVG=zn,r.SVGOverlay=ji,r.TileLayer=nn,r.Tooltip=ci,r.Transformation=Ie,r.Util=ne,r.VideoOverlay=Bs,r.bind=l,r.bounds=Be,r.canvas=Hs,r.circle=Ms,r.circleMarker=zo,r.control=$n,r.divIcon=Go,r.extend=o,r.featureGroup=Vo,r.geoJSON=Ns,r.geoJson=Wo,r.gridLayer=qo,r.icon=Ho,r.imageOverlay=jo,r.latLng=Le,r.latLngBounds=ye,r.layerGroup=Uo,r.map=gs,r.marker=Rs,r.point=Pe,r.polygon=oi,r.polyline=Os,r.popup=Yo,r.rectangle=Qo,r.setOptions=T,r.stamp=u,r.svg=zs,r.svgOverlay=Ki,r.tileLayer=Yi,r.tooltip=Fs,r.transformation=we,r.version=n,r.videoOverlay=Ko;var sn=window.L;r.noConflict=function(){return window.L=sn,this},window.L=r})})(leafletSrc,leafletSrc.exports);const L$2=leafletSrc.exports;(function(e){typeof e>"u"&&(e={getCenter:L.Map.prototype.getCenter,setView:L.Map.prototype.setView,flyTo:L.Map.prototype.flyTo,setZoomAround:L.Map.prototype.setZoomAround,getBoundsZoom:L.Map.prototype.getBoundsZoom,PopupAdjustPan:L.Popup.prototype._adjustPan,RendererUpdate:L.Renderer.prototype._update}),L.Map.include({getBounds:function(){if(this._viewport)return this.getViewportLatLngBounds();var t=this.getPixelBounds(),r=this.unproject(t.getBottomLeft()),n=this.unproject(t.getTopRight());return new L.LatLngBounds(r,n)},getViewport:function(){return this._viewport},getViewportBounds:function(){var t=this._viewport,r=L.point(t.offsetLeft,t.offsetTop),n=L.point(t.clientWidth,t.clientHeight);return(n.x===0||n.y===0)&&(t=this.getContainer(),t&&(r=L.point(0,0),n=L.point(t.clientWidth,t.clientHeight))),L.bounds(r,r.add(n))},getViewportLatLngBounds:function(){var t=this.getViewportBounds();return L.latLngBounds(this.containerPointToLatLng(t.min),this.containerPointToLatLng(t.max))},getOffset:function(){var t=this.getSize().divideBy(2),r=this.getViewportBounds().getCenter();return t.subtract(r)},getCenter:function(t){var r=e.getCenter.call(this);if(this.getViewport()&&!t){var n=this.getZoom(),o=this.project(r,n);o=o.subtract(this.getOffset()),r=this.unproject(o,n)}return r},setView:function(t,r,n){if(t=L.latLng(t),r=r===void 0?this._zoom:this._limitZoom(r),this.getViewport()){var o=this.project(t,this._limitZoom(r));o=o.add(this.getOffset()),t=this.unproject(o,this._limitZoom(r))}return e.setView.call(this,t,r,n)},flyTo:function(t,r,n){if(t=L.latLng(t),r=r===void 0?u:r,this.getViewport()){var o=this.project(t,this._limitZoom(r));o=o.add(this.getOffset()),t=this.unproject(o,this._limitZoom(r))}if(n=n||{},n.animate===!1||!L.Browser.any3d)return this.setView(t,r,n);this._stop();var a=this.project(e.getCenter.call(this)),l=this.project(t),c=this.getSize(),u=this._zoom,_=Math.max(c.x,c.y),b=_*this.getZoomScale(u,r),x=l.distanceTo(a)||1,E=1.42,I=E*E;function k(ve){var ee=ve?-1:1,he=ve?b:_,ne=b*b-_*_+ee*I*I*x*x,xe=2*he*I*x,te=ne/xe,ae=Math.sqrt(te*te+1)-te,ge=ae<1e-9?-18:Math.log(ae);return ge}function T(ve){return(Math.exp(ve)-Math.exp(-ve))/2}function O(ve){return(Math.exp(ve)+Math.exp(-ve))/2}function $(ve){return T(ve)/O(ve)}var D=k(0);function N(ve){return _*(O(D)/O(D+E*ve))}function H(ve){return _*(O(D)*$(D+E*ve)-T(D))/I}function ie(ve){return 1-Math.pow(1-ve,1.5)}var ue=Date.now(),de=(k(1)-D)/E,le=n.duration?1e3*n.duration:1e3*de*.8;function ce(){var ve=(Date.now()-ue)/le,ee=ie(ve)*de;ve<=1?(this._flyToFrame=L.Util.requestAnimFrame(ce,this),this._move(this.unproject(a.add(l.subtract(a).multiplyBy(H(ee)/x)),u),this.getScaleZoom(_/N(ee),u),{flyTo:!0})):this._move(t,r)._moveEnd(!0)}return this._moveStart(!0,n.noMoveStart),ce.call(this),this},setZoomAround:function(t,r,n){var o=this.getViewport();if(o){var a=this.getZoomScale(r),l=this.getViewportBounds().getCenter(),c=t instanceof L.Point?t:this.latLngToContainerPoint(t),u=c.subtract(l).multiplyBy(1-1/a),_=this.containerPointToLatLng(l.add(u));return this.setView(_,r,{zoom:n})}else return e.setZoomAround.call(this,t,r,n)},getBoundsZoom:function(t,r,n){t=L.latLngBounds(t),n=L.point(n||[0,0]);var o=this.getZoom()||0,a=this.getMinZoom(),l=this.getMaxZoom(),c=t.getNorthWest(),u=t.getSouthEast(),_=this.getViewport(),b=(_?L.point(_.clientWidth,_.clientHeight):this.getSize()).subtract(n),x=this.project(u,o).subtract(this.project(c,o)),E=L.Browser.any3d?this.options.zoomSnap:1,I=b.x/x.x,k=b.y/x.y,T=r?Math.max(I,k):Math.min(I,k);return o=this.getScaleZoom(T,o),E&&(o=Math.round(o/(E/100))*(E/100),o=r?Math.ceil(o/E)*E:Math.floor(o/E)*E),Math.max(a,Math.min(l,o))},setActiveArea:function(t,r,n){var o;if(r&&this._zoom&&(o=this.getCenter()),!this._viewport){var a=this.getContainer();this._viewport=L.DomUtil.create("div",""),a.insertBefore(this._viewport,a.firstChild)}return typeof t=="string"?this._viewport.className=t:L.extend(this._viewport.style,t),o&&this.setView(o,this.getZoom(),{animate:!!n}),this}}),L.Renderer.include({_onZoom:function(){this._updateTransform(this._map.getCenter(!0),this._map.getZoom())},_update:function(){e.RendererUpdate.call(this),this._center=this._map.getCenter(!0)}}),L.GridLayer.include({_updateLevels:function(){var t=this._tileZoom,r=this.options.maxZoom;if(t!==void 0){for(var n in this._levels)n=Number(n),this._levels[n].el.children.length||n===t?(this._levels[n].el.style.zIndex=r-Math.abs(t-n),this._onUpdateLevel(n)):(L.DomUtil.remove(this._levels[n].el),this._removeTilesAtZoom(n),this._onRemoveLevel(n),delete this._levels[n]);var o=this._levels[t],a=this._map;return o||(o=this._levels[t]={},o.el=L.DomUtil.create("div","leaflet-tile-container leaflet-zoom-animated",this._container),o.el.style.zIndex=r,o.origin=a.project(a.unproject(a.getPixelOrigin()),t).round(),o.zoom=t,this._setZoomTransform(o,a.getCenter(!0),a.getZoom()),L.Util.falseFn(o.el.offsetWidth),this._onCreateLevel(o)),this._level=o,o}},_resetView:function(t){var r=t&&(t.pinch||t.flyTo);this._setView(this._map.getCenter(!0),this._map.getZoom(),r,r)},_update:function(t){var r=this._map;if(!!r){var n=this._clampZoom(r.getZoom());if(t===void 0&&(t=r.getCenter(!0)),this._tileZoom!==void 0){var o=this._getTiledPixelBounds(t),a=this._pxBoundsToTileRange(o),l=a.getCenter(),c=[],u=this.options.keepBuffer,_=new L.Bounds(a.getBottomLeft().subtract([u,-u]),a.getTopRight().add([u,-u]));if(!(isFinite(a.min.x)&&isFinite(a.min.y)&&isFinite(a.max.x)&&isFinite(a.max.y)))throw new Error("Attempted to load an infinite number of tiles");for(var b in this._tiles){var x=this._tiles[b].coords;(x.z!==this._tileZoom||!_.contains(new L.Point(x.x,x.y)))&&(this._tiles[b].current=!1)}if(Math.abs(n-this._tileZoom)>1){this._setView(t,n);return}for(var E=a.min.y;E<=a.max.y;E++)for(var I=a.min.x;I<=a.max.x;I++){var k=new L.Point(I,E);if(k.z=this._tileZoom,!!this._isValidTile(k)){var T=this._tiles[this._tileCoordsToKey(k)];T?T.current=!0:c.push(k)}}if(c.sort(function($,D){return $.distanceTo(l)-D.distanceTo(l)}),c.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var O=document.createDocumentFragment();for(I=0;Ix.x&&(E=c.x+o-x.x+b.x),c.x-E-_.x<0&&(E=c.x-_.x),c.y+n+b.y>x.y&&(I=c.y+n-x.y+b.y),c.y-I-_.y<0&&(I=c.y-_.y),(E||I)&&t.fire("autopanstart").panBy([E,I])}}})})(window.leafletActiveAreaPreviousMethods);L.TileLayer.ColorFilter=L.TileLayer.extend({intialize:function(e,t){L.TileLayer.prototype.initialize.call(this,e,t)},colorFilter:function(){var e=["blur:px","brightness:%","bright:brightness:%","bri:brightness:%","contrast:%","con:contrast:%","grayscale:%","gray:grayscale:%","hue-rotate:deg","hue:hue-rotate:deg","hue-rotation:hue-rotate:deg","invert:%","inv:invert:%","opacity:%","op:opacity:%","saturate:%","saturation:saturate:%","sat:saturate:%","sepia:%","sep:sepia:%"];return(this.options.filter?this.options.filter:[]).map(function(t){var r=t.toLowerCase().split(":");if(r.length===2){var n=e.find(function(o){return o.split(":")[0]===r[0]});if(n)return n=n.split(":"),r[1]+=/^\d+$/.test(r[1])?n[n.length-1]:"","".concat(n[n.length-2],"(").concat(r[1],")")}return""}).join(" ")},_initContainer:function(){L.TileLayer.prototype._initContainer.call(this),this._container.style.filter=this.colorFilter()},updateFilter:function(e){this.options.filter=e,this._container&&(this._container.style.filter=this.colorFilter())}}),L.tileLayer.colorFilter=function(e,t){return new L.TileLayer.ColorFilter(e,t)};const leaflet="";let map$3,usermarker;const attrs$1={attribution:'© OpenStreetMap contributors'},layerMapLight=L$2.tileLayer.colorFilter("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{...attrs$1,filter:["grayscale:50%","saturate:70%"]}),layerMapDark=L$2.tileLayer.colorFilter("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{...attrs$1,filter:["invert:100%","grayscale:100%","bright:100%","saturate:0%","sepia:10%"]});function instanceMap(){if(map$3)return map$3;throw new Error("Must be initialized before using the mapd.")}function removeMap(){map$3.remove(),map$3=void 0}function init$3(e,t,r="light"){return map$3=L$2.map("map",{minZoom:3}),setTheme(r),map$3.attributionControl.setPrefix(""),map$3.setView(e,t),map$3.zoomControl.remove(),map$3}function setTheme(e){const t=instanceMap();e==="light"?(t.removeLayer(layerMapDark),t.addLayer(layerMapLight)):(t.removeLayer(layerMapLight),t.addLayer(layerMapDark))}function setview(e,t){const r=instanceMap();r&&r.setView(e,t)}function drawuser(e,t){const r=instanceMap();let n=100;r&&(usermarker&&r.removeLayer(usermarker),t>0&&(n=10*t),t>4&&(n=5*t),t>7&&(n=2*t),usermarker=new L$2.circleMarker(e,{radius:n,opacity:.2}),usermarker.addTo(r))}const scriptRel="modulepreload",assetsURL=function(e){return"/"+e},seen={},__vitePreload=function(t,r,n){if(!r||r.length===0)return t();const o=document.getElementsByTagName("link");return Promise.all(r.map(a=>{if(a=assetsURL(a),a in seen)return;seen[a]=!0;const l=a.endsWith(".css"),c=l?'[rel="stylesheet"]':"";if(!!n)for(let b=o.length-1;b>=0;b--){const x=o[b];if(x.href===a&&(!l||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${c}`))return;const _=document.createElement("link");if(_.rel=l?"stylesheet":scriptRel,l||(_.as="script",_.crossOrigin=""),_.href=a,document.head.appendChild(_),l)return new Promise((b,x)=>{_.addEventListener("load",b),_.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${a}`)))})})).then(()=>t())},__variableDynamicImportRuntimeHelper=(e,t)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t)))})};function Queue(e){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:l},next:{enumerable:!0,writable:!1,value:c},clear:{enumerable:!0,writable:!1,value:n},contents:{enumerable:!1,get:o,set:a},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var t=[],r=!1;function n(){return t=[],t}function o(){return t}function a(u){return t=u,t}function l(){for(var u in arguments)t.push(arguments[u]);!r&&!this.stop&&this.autoRun&&this.next()}function c(){if(r=!0,t.length<1||this.stop){r=!1;return}t.shift().bind(this)()}}var queue$1=Queue,leaflet_geometryutil={exports:{}};(function(e){(function(t){var r;r=leafletSrc.exports,e.exports=t(r)})(function(t){return t.Polyline._flat=t.LineUtil.isFlat||t.Polyline._flat||function(r){return!t.Util.isArray(r[0])||typeof r[0][0]!="object"&&typeof r[0][0]<"u"},t.GeometryUtil=t.extend(t.GeometryUtil||{},{distance:function(r,n,o){return r.latLngToLayerPoint(n).distanceTo(r.latLngToLayerPoint(o))},distanceSegment:function(r,n,o,a){var l=r.latLngToLayerPoint(n),c=r.latLngToLayerPoint(o),u=r.latLngToLayerPoint(a);return t.LineUtil.pointToSegmentDistance(l,c,u)},readableDistance:function(r,n){var o=n!=="imperial",a;return o?r>1e3?a=(r/1e3).toFixed(2)+" km":a=r.toFixed(1)+" m":(r*=1.09361,r>1760?a=(r/1760).toFixed(2)+" miles":a=r.toFixed(1)+" yd"),a},belongsSegment:function(r,n,o,a){a=a===void 0?.2:a;var l=n.distanceTo(o),c=n.distanceTo(r)+r.distanceTo(o)-l;return c/l0?n[n.length-1]:0},accumulatedLengths:function(r){if(typeof r.getLatLngs=="function"&&(r=r.getLatLngs()),r.length===0)return[];for(var n=0,o=[0],a=0,l=r.length-1;aa?l.slice(0,a):l},layersWithin:function(r,n,o,a){a=typeof a=="number"?a:1/0;for(var l=[],c=null,u=0,_=0,b=n.length;_a)return null;if(l&&typeof c.layer.getLatLngs=="function"){var u=t.GeometryUtil.closest(r,c.layer,c.latlng,!0);u.distance0&&(u+=c[_-1].distanceTo(c[_]));for(var b=u*o,x=0,E=0,_=0;Ea)return t.GeometryUtil.extract(r,t.GeometryUtil.reverse(n),1-o,1-a);o=Math.max(Math.min(o,1),0),a=Math.max(Math.min(a,1),0);var l=n.getLatLngs(),c=t.GeometryUtil.interpolateOnLine(r,n,o),u=t.GeometryUtil.interpolateOnLine(r,n,a);if(o==a){var _=t.GeometryUtil.interpolateOnLine(r,n,a);return[_.latLng]}c.predecessor==-1&&(c.predecessor=0),u.predecessor==-1&&(u.predecessor=0);var b=l.slice(c.predecessor+1,u.predecessor+1);return b.unshift(c.latLng),b.push(u.latLng),b},isBefore:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs();return o[o.length-1].equals(a[0])},isAfter:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs();return o[0].equals(a[a.length-1])},startsAtExtremity:function(r,n){if(!n)return!1;var o=r.getLatLngs(),a=n.getLatLngs(),l=o[0];return l.equals(a[0])||l.equals(a[a.length-1])},computeAngle:function(r,n){return Math.atan2(n.y-r.y,n.x-r.x)*180/Math.PI},computeSlope:function(r,n){var o=(n.y-r.y)/(n.x-r.x),a=r.y-o*r.x;return{a:o,b:a}},rotatePoint:function(r,n,o,a){var l=r.getMaxZoom();l===1/0&&(l=r.getZoom());var c=o*Math.PI/180,u=r.project(n,l),_=r.project(a,l),b=Math.cos(c)*(u.x-_.x)-Math.sin(c)*(u.y-_.y)+_.x,x=Math.sin(c)*(u.x-_.x)+Math.cos(c)*(u.y-_.y)+_.y;return r.unproject(new t.Point(b,x),l)},bearing:function(r,n){var o=Math.PI/180,a=r.lat*o,l=n.lat*o,c=r.lng*o,u=n.lng*o,_=Math.sin(u-c)*Math.cos(l),b=Math.cos(a)*Math.sin(l)-Math.sin(a)*Math.cos(l)*Math.cos(u-c),x=(Math.atan2(_,b)*180/Math.PI+360)%360;return x>=180?x-360:x},destination:function(r,n,o){n=(n+360)%360;var a=Math.PI/180,l=180/Math.PI,c=6378137,u=r.lng*a,_=r.lat*a,b=n*a,x=Math.sin(_),E=Math.cos(_),I=Math.cos(o/c),k=Math.sin(o/c),T=Math.asin(x*I+E*k*Math.cos(b)),O=u+Math.atan2(Math.sin(b)*k*E,I-x*Math.sin(T));return O=O*l,O=O>180?O-360:O<-180?O+360:O,t.latLng([T*l,O])},angle:function(r,n,o){var a=r.latLngToContainerPoint(n),l=r.latLngToContainerPoint(o),c=Math.atan2(l.y-a.y,l.x-a.x)*180/Math.PI+90;return c+=c<0?360:0,c},destinationOnSegment:function(r,n,o,a){var l=t.GeometryUtil.angle(r,n,o),c=t.GeometryUtil.destination(n,l,a);return t.GeometryUtil.closestOnSegment(r,c,n,o)}}),t.GeometryUtil})})(leaflet_geometryutil);function modulus(e,t){return(e%t+t)%t}function definedProps(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r!==void 0))}function isInMeters(e){return e.toString().trim().slice(e.toString().length-1,e.toString().length)==="m"}function isInPercent(e){return e.toString().trim().slice(e.toString().length-1,e.toString().length)==="%"}function isInPixels(e){return e.toString().trim().slice(e.toString().length-2,e.toString().length)==="px"}function pixelsToMeters(e,t){let r=t.getCenter(),n=t.latLngToLayerPoint(r),o={x:n.x+Number(e),y:n.y},a=t.layerPointToLatLng(o);return t.distance(r,a)}L.Polyline.include({arrowheads:function(e={}){const t={yawn:60,size:"15%",frequency:"allvertices",proportionalToTotal:!1};this.options.noClip=!0;let r=Object.assign({},t,e);return this._arrowheadOptions=r,this._hatsApplied=!0,this},buildVectorHats:function(e){this._arrowheads&&this._arrowheads.remove(),this._ghosts&&this._ghosts.remove();let t=Object.getPrototypeOf(Object.getPrototypeOf(this.options)),r=Object.assign({},t,this.options),n=Object.assign({},r,e);n.smoothFactor=1,n.fillOpacity=1,n.fill=!!e.fill,n.interactive=!1;let o=e.size.toString(),a=[];const{frequency:l,offsets:c}=e;(c?.start||c?.end)&&this._buildGhosts({start:c.start,end:c.end}),(this._ghosts||this)._parts.forEach((b,x)=>{const E=b.map(ue=>this._map.layerPointToLatLng(ue)),I=(()=>{let ue=0;for(var de=0;de{let ue=l.slice(0,l.length-2);return pixelsToMeters(ue,this._map)/I})(),$=1/O,$=Math.floor($),O=1/$):(O=1/l,$=l),e.frequency==="allvertices")T=(()=>{let ue=[];for(var de=1;de=2)k=[E[E.length-1]],T=[L.GeometryUtil.angle(this._map,E[E.length-2],E[E.length-1])+180];else{k=[];let ue=[];for(var D=0;D<$;D++){let de=L.GeometryUtil.interpolateOnLine(this._map,E,O*(D+1));de&&(ue.push(de),k.push(de.latLng))}T=(()=>{let de=[];for(var le=0;le{let le=de.yawn??e.yawn,ce=L.GeometryUtil.destination(k[D],T[D]-le/2,ue),ve=L.GeometryUtil.destination(k[D],T[D]+le/2,ue),ee=[[ce.lat,ce.lng],[k[D].lat,k[D].lng],[ve.lat,ve.lng]],he=e.fill?L.polygon(ee,{...n,...de}):L.polyline(ee,{...n,...de});N.push(he)},ie=(ue,de={})=>{let le=ue.slice(0,ue.length-2),ce=de.yawn??e.yawn,ve=this._map.latLngToLayerPoint(k[D]),ee=T[D],he=(180-ee-ce/2)*(Math.PI/180),ne=(180-ee+ce/2)*(Math.PI/180),xe=le*Math.sin(he),te=le*Math.cos(he),ae=le*Math.sin(ne),ge=le*Math.cos(ne),se={x:ve.x+xe,y:ve.y+te},Se={x:ve.x+ae,y:ve.y+ge},Pe=this._map.layerPointToLatLng(se),Ue=this._map.layerPointToLatLng(Se),Be=[[Pe.lat,Pe.lng],[k[D].lat,k[D].lng],[Ue.lat,Ue.lng]],fe=e.fill?L.polygon(Be,{...n,...de}):L.polyline(Be,{...n,...de});N.push(fe)};for(var D=0;De.frequency==="endonly"&&e.proportionalToTotal?I*ce/100:I/(b.length-1)*ce/100)();H(ve,de)}else isInPixels(o)?ie(e.size,de):console.error("Error: Arrowhead size unit not defined. Check your arrowhead options.")}a.push(...N)});let _=L.layerGroup(a);return this._arrowheads=_,this},getArrowheads:function(){return this._arrowheads?this._arrowheads:console.error("Error: You tried to call '.getArrowheads() on a shape that does not have a arrowhead. Use '.arrowheads()' to add a arrowheads before trying to call '.getArrowheads()'")},_buildGhosts:function({start:e,end:t}){if(e||t){let r=this.getLatLngs();r=Array.isArray(r[0])?r:[r];const n=r.map(o=>{const a=(()=>{let l=0;for(var c=0;c{if(isInMeters(e))return Number(e.slice(0,e.length-1));if(isInPixels(e)){let u=Number(e.slice(0,e.length-2));return pixelsToMeters(u,this._map)}})(),c=L.GeometryUtil.interpolateOnLine(this._map,o,l/a);o=o.slice(c.predecessor===-1?1:c.predecessor+1,o.length),o.unshift(c.latLng)}if(t){let l=(()=>{if(isInMeters(t))return Number(t.slice(0,t.length-1));if(isInPixels(t)){let u=Number(t.slice(0,t.length-2));return pixelsToMeters(u,this._map)}})(),c=L.GeometryUtil.interpolateOnLine(this._map,o,(a-l)/a);o=o.slice(0,c.predecessor+1),o.push(c.latLng)}return o});this._ghosts=L.polyline(n,{...this.options,color:"rgba(0,0,0,0)",stroke:0,smoothFactor:0,interactive:!1}),this._ghosts.addTo(this._map)}},deleteArrowheads:function(){this._arrowheads&&(this._arrowheads.remove(),delete this._arrowheads,delete this._arrowheadOptions,this._hatsApplied=!1),this._ghosts&&this._ghosts.remove()},_update:function(){!this._map||(this._clipPoints(),this._simplifyPoints(),this._updatePath(),this._hatsApplied&&(this.buildVectorHats(this._arrowheadOptions),this._map.addLayer(this._arrowheads)))},remove:function(){return this._arrowheads&&this._arrowheads.remove(),this._ghosts&&this._ghosts.remove(),this.removeFrom(this._map||this._mapToAdd)}});L.LayerGroup.include({removeLayer:function(e){var t=e in this._layers?e:this.getLayerId(e);return this._map&&this._layers[t]&&(this._layers[t]._arrowheads&&this._layers[t]._arrowheads.remove(),this._map.removeLayer(this._layers[t])),delete this._layers[t],this},onRemove:function(e,t){for(var t in this._layers)this._layers[t]&&this._layers[t].remove();this.eachLayer(e.removeLayer,e)}});L.Map.include({removeLayer:function(e){var t=L.Util.stamp(e);return e._arrowheads&&e._arrowheads.remove(),e._ghosts&&e._ghosts.remove(),this._layers[t]?(this._loaded&&e.onRemove(this),e.getAttribution&&this.attributionControl&&this.attributionControl.removeAttribution(e.getAttribution()),delete this._layers[t],this._loaded&&(this.fire("layerremove",{layer:e}),e.fire("remove")),e._map=e._mapToAdd=null,this):this}});L.GeoJSON.include({geometryToLayer:function(e,t){var r=e.type==="Feature"?e.geometry:e,n=r?r.coordinates:null,o=[],a=t&&t.pointToLayer,l=t&&t.coordsToLatLng||L.GeoJSON.coordsToLatLng,c,u,_,b;if(!n&&!r)return null;switch(r.type){case"Point":return c=l(n),this._pointToLayer(a,e,c,t);case"MultiPoint":for(_=0,b=n.length;_=c;)l=l.__parent;return this._currentShownBounds.contains(l.getLatLng())&&(this.options.animateAddingMarkers?this._animationAddLayer(a,l):this._animationAddLayerNonAnimated(a,l)),this},removeLayer:function(a){return a instanceof L.LayerGroup?this.removeLayers([a]):a.getLatLng?this._map?a.__parent?(this._unspiderfy&&(this._unspiderfy(),this._unspiderfyLayer(a)),this._removeLayer(a,!0),this.fire("layerremove",{layer:a}),this._topClusterLevel._recalculateBounds(),this._refreshClustersIcons(),a.off(this._childMarkerEventHandlers,this),this._featureGroup.hasLayer(a)&&(this._featureGroup.removeLayer(a),a.clusterShow&&a.clusterShow()),this):this:(!this._arraySplice(this._needsClustering,a)&&this.hasLayer(a)&&this._needsRemoving.push({layer:a,latlng:a._latlng}),this.fire("layerremove",{layer:a}),this):(this._nonPointGroup.removeLayer(a),this.fire("layerremove",{layer:a}),this)},addLayers:function(a,l){if(!L.Util.isArray(a))return this.addLayer(a);var c=this._featureGroup,u=this._nonPointGroup,_=this.options.chunkedLoading,b=this.options.chunkInterval,x=this.options.chunkProgress,E=a.length,I=0,k=!0,T;if(this._map){var O=new Date().getTime(),$=L.bind(function(){var N=new Date().getTime();for(this._map&&this._unspiderfy&&this._unspiderfy();Ib)break}if(T=a[I],T instanceof L.LayerGroup){k&&(a=a.slice(),k=!1),this._extractNonGroupLayers(T,a),E=a.length;continue}if(!T.getLatLng){u.addLayer(T),l||this.fire("layeradd",{layer:T});continue}if(!this.hasLayer(T)&&(this._addLayer(T,this._maxZoom),l||this.fire("layeradd",{layer:T}),T.__parent&&T.__parent.getChildCount()===2)){var ie=T.__parent.getAllChildMarkers(),ue=ie[0]===T?ie[1]:ie[0];c.removeLayer(ue)}}x&&x(I,E,new Date().getTime()-O),I===E?(this._topClusterLevel._recalculateBounds(),this._refreshClustersIcons(),this._topClusterLevel._recursivelyAddChildrenToMap(null,this._zoom,this._currentShownBounds)):setTimeout($,this.options.chunkDelay)},this);$()}else for(var D=this._needsClustering;I=0;l--)a.extend(this._needsClustering[l].getLatLng());return a.extend(this._nonPointGroup.getBounds()),a},eachLayer:function(a,l){var c=this._needsClustering.slice(),u=this._needsRemoving,_,b,x;for(this._topClusterLevel&&this._topClusterLevel.getAllChildMarkers(c),b=c.length-1;b>=0;b--){for(_=!0,x=u.length-1;x>=0;x--)if(u[x].layer===c[b]){_=!1;break}_&&a.call(l,c[b])}this._nonPointGroup.eachLayer(a,l)},getLayers:function(){var a=[];return this.eachLayer(function(l){a.push(l)}),a},getLayer:function(a){var l=null;return a=parseInt(a,10),this.eachLayer(function(c){L.stamp(c)===a&&(l=c)}),l},hasLayer:function(a){if(!a)return!1;var l,c=this._needsClustering;for(l=c.length-1;l>=0;l--)if(c[l]===a)return!0;for(c=this._needsRemoving,l=c.length-1;l>=0;l--)if(c[l].layer===a)return!1;return!!(a.__parent&&a.__parent._group===this)||this._nonPointGroup.hasLayer(a)},zoomToShowLayer:function(a,l){var c=this._map;typeof l!="function"&&(l=function(){});var u=function(){(c.hasLayer(a)||c.hasLayer(a.__parent))&&!this._inZoomAnimation&&(this._map.off("moveend",u,this),this.off("animationend",u,this),c.hasLayer(a)?l():a.__parent._icon&&(this.once("spiderfied",l,this),a.__parent.spiderfy()))};a._icon&&this._map.getBounds().contains(a.getLatLng())?l():a.__parent._zoom=0;c--)if(a[c]===l)return a.splice(c,1),!0},_removeFromGridUnclustered:function(a,l){for(var c=this._map,u=this._gridUnclustered,_=Math.floor(this._map.getMinZoom());l>=_&&u[l].removeObject(a,c.project(a.getLatLng(),l));l--);},_childMarkerDragStart:function(a){a.target.__dragStart=a.target._latlng},_childMarkerMoved:function(a){if(!this._ignoreMove&&!a.target.__dragStart){var l=a.target._popup&&a.target._popup.isOpen();this._moveChild(a.target,a.oldLatLng,a.latlng),l&&a.target.openPopup()}},_moveChild:function(a,l,c){a._latlng=l,this.removeLayer(a),a._latlng=c,this.addLayer(a)},_childMarkerDragEnd:function(a){var l=a.target.__dragStart;delete a.target.__dragStart,l&&this._moveChild(a.target,l,a.target._latlng)},_removeLayer:function(a,l,c){var u=this._gridClusters,_=this._gridUnclustered,b=this._featureGroup,x=this._map,E=Math.floor(this._map.getMinZoom());l&&this._removeFromGridUnclustered(a,this._maxZoom);var I=a.__parent,k=I._markers,T;for(this._arraySplice(k,a);I&&(I._childCount--,I._boundsNeedUpdate=!0,!(I._zoom"+l+"",className:"marker-cluster"+c,iconSize:new L.Point(40,40)})},_bindEvents:function(){var a=this._map,l=this.options.spiderfyOnMaxZoom,c=this.options.showCoverageOnHover,u=this.options.zoomToBoundsOnClick,_=this.options.spiderfyOnEveryZoom;(l||u||_)&&this.on("clusterclick clusterkeypress",this._zoomOrSpiderfy,this),c&&(this.on("clustermouseover",this._showCoverage,this),this.on("clustermouseout",this._hideCoverage,this),a.on("zoomend",this._hideCoverage,this))},_zoomOrSpiderfy:function(a){var l=a.layer,c=l;if(!(a.type==="clusterkeypress"&&a.originalEvent&&a.originalEvent.keyCode!==13)){for(;c._childClusters.length===1;)c=c._childClusters[0];c._zoom===this._maxZoom&&c._childCount===l._childCount&&this.options.spiderfyOnMaxZoom?l.spiderfy():this.options.zoomToBoundsOnClick&&l.zoomToBounds(),this.options.spiderfyOnEveryZoom&&l.spiderfy(),a.originalEvent&&a.originalEvent.keyCode===13&&this._map._container.focus()}},_showCoverage:function(a){var l=this._map;this._inZoomAnimation||(this._shownPolygon&&l.removeLayer(this._shownPolygon),a.layer.getChildCount()>2&&a.layer!==this._spiderfied&&(this._shownPolygon=new L.Polygon(a.layer.getConvexHull(),this.options.polygonOptions),l.addLayer(this._shownPolygon)))},_hideCoverage:function(){this._shownPolygon&&(this._map.removeLayer(this._shownPolygon),this._shownPolygon=null)},_unbindEvents:function(){var a=this.options.spiderfyOnMaxZoom,l=this.options.showCoverageOnHover,c=this.options.zoomToBoundsOnClick,u=this.options.spiderfyOnEveryZoom,_=this._map;(a||c||u)&&this.off("clusterclick clusterkeypress",this._zoomOrSpiderfy,this),l&&(this.off("clustermouseover",this._showCoverage,this),this.off("clustermouseout",this._hideCoverage,this),_.off("zoomend",this._hideCoverage,this))},_zoomEnd:function(){!this._map||(this._mergeSplitClusters(),this._zoom=Math.round(this._map._zoom),this._currentShownBounds=this._getExpandedVisibleBounds())},_moveEnd:function(){if(!this._inZoomAnimation){var a=this._getExpandedVisibleBounds();this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,Math.floor(this._map.getMinZoom()),this._zoom,a),this._topClusterLevel._recursivelyAddChildrenToMap(null,Math.round(this._map._zoom),a),this._currentShownBounds=a}},_generateInitialClusters:function(){var a=Math.ceil(this._map.getMaxZoom()),l=Math.floor(this._map.getMinZoom()),c=this.options.maxClusterRadius,u=c;typeof c!="function"&&(u=function(){return c}),this.options.disableClusteringAtZoom!==null&&(a=this.options.disableClusteringAtZoom-1),this._maxZoom=a,this._gridClusters={},this._gridUnclustered={};for(var _=a;_>=l;_--)this._gridClusters[_]=new L.DistanceGrid(u(_)),this._gridUnclustered[_]=new L.DistanceGrid(u(_));this._topClusterLevel=new this._markerCluster(this,l-1)},_addLayer:function(a,l){var c=this._gridClusters,u=this._gridUnclustered,_=Math.floor(this._map.getMinZoom()),b,x;for(this.options.singleMarkerMode&&this._overrideMarkerIcon(a),a.on(this._childMarkerEventHandlers,this);l>=_;l--){b=this._map.project(a.getLatLng(),l);var E=c[l].getNearObject(b);if(E){E._addChild(a),a.__parent=E;return}if(E=u[l].getNearObject(b),E){var I=E.__parent;I&&this._removeLayer(E,!1);var k=new this._markerCluster(this,l,E,a);c[l].addObject(k,this._map.project(k._cLatLng,l)),E.__parent=k,a.__parent=k;var T=k;for(x=l-1;x>I._zoom;x--)T=new this._markerCluster(this,x,T),c[x].addObject(T,this._map.project(E.getLatLng(),x));I._addChild(T),this._removeFromGridUnclustered(E,l);return}u[l].addObject(a,b)}this._topClusterLevel._addChild(a),a.__parent=this._topClusterLevel},_refreshClustersIcons:function(){this._featureGroup.eachLayer(function(a){a instanceof L.MarkerCluster&&a._iconNeedsUpdate&&a._updateIcon()})},_enqueue:function(a){this._queue.push(a),this._queueTimeout||(this._queueTimeout=setTimeout(L.bind(this._processQueue,this),300))},_processQueue:function(){for(var a=0;aa?(this._animationStart(),this._animationZoomOut(this._zoom,a)):this._moveEnd()},_getExpandedVisibleBounds:function(){if(this.options.removeOutsideVisibleBounds){if(L.Browser.mobile)return this._checkBoundsMaxLat(this._map.getBounds())}else return this._mapBoundsInfinite;return this._checkBoundsMaxLat(this._map.getBounds().pad(1))},_checkBoundsMaxLat:function(a){var l=this._maxLat;return l!==void 0&&(a.getNorth()>=l&&(a._northEast.lat=1/0),a.getSouth()<=-l&&(a._southWest.lat=-1/0)),a},_animationAddLayerNonAnimated:function(a,l){if(l===a)this._featureGroup.addLayer(a);else if(l._childCount===2){l._addToMap();var c=l.getAllChildMarkers();this._featureGroup.removeLayer(c[0]),this._featureGroup.removeLayer(c[1])}else l._updateIcon()},_extractNonGroupLayers:function(a,l){var c=a.getLayers(),u=0,_;for(l=l||[];u=0;b--)k=I[b],c.contains(k._latlng)||u.removeLayer(k)}),this._forceLayout(),this._topClusterLevel._recursivelyBecomeVisible(c,l),u.eachLayer(function(x){!(x instanceof L.MarkerCluster)&&x._icon&&x.clusterShow()}),this._topClusterLevel._recursively(c,a,l,function(x){x._recursivelyRestoreChildPositions(l)}),this._ignoreMove=!1,this._enqueue(function(){this._topClusterLevel._recursively(c,a,_,function(x){u.removeLayer(x),x.clusterShow()}),this._animationEnd()})},_animationZoomOut:function(a,l){this._animationZoomOutSingle(this._topClusterLevel,a-1,l),this._topClusterLevel._recursivelyAddChildrenToMap(null,l,this._getExpandedVisibleBounds()),this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,Math.floor(this._map.getMinZoom()),a,this._getExpandedVisibleBounds())},_animationAddLayer:function(a,l){var c=this,u=this._featureGroup;u.addLayer(a),l!==a&&(l._childCount>2?(l._updateIcon(),this._forceLayout(),this._animationStart(),a._setPos(this._map.latLngToLayerPoint(l.getLatLng())),a.clusterHide(),this._enqueue(function(){u.removeLayer(a),a.clusterShow(),c._animationEnd()})):(this._forceLayout(),c._animationStart(),c._animationZoomOutSingle(l,this._map.getMaxZoom(),this._zoom)))}},_animationZoomOutSingle:function(a,l,c){var u=this._getExpandedVisibleBounds(),_=Math.floor(this._map.getMinZoom());a._recursivelyAnimateChildrenInAndAddSelfToMap(u,_,l+1,c);var b=this;this._forceLayout(),a._recursivelyBecomeVisible(u,c),this._enqueue(function(){if(a._childCount===1){var x=a._markers[0];this._ignoreMove=!0,x.setLatLng(x.getLatLng()),this._ignoreMove=!1,x.clusterShow&&x.clusterShow()}else a._recursively(u,c,_,function(E){E._recursivelyRemoveChildrenFromMap(u,_,l+1)});b._animationEnd()})},_animationEnd:function(){this._map&&(this._map._mapPane.className=this._map._mapPane.className.replace(" leaflet-cluster-anim","")),this._inZoomAnimation--,this.fire("animationend")},_forceLayout:function(){L.Util.falseFn(document.body.offsetWidth)}}),L.markerClusterGroup=function(a){return new L.MarkerClusterGroup(a)};var o=L.MarkerCluster=L.Marker.extend({options:L.Icon.prototype.options,initialize:function(a,l,c,u){L.Marker.prototype.initialize.call(this,c?c._cLatLng||c.getLatLng():new L.LatLng(0,0),{icon:this,pane:a.options.clusterPane}),this._group=a,this._zoom=l,this._markers=[],this._childClusters=[],this._childCount=0,this._iconNeedsUpdate=!0,this._boundsNeedUpdate=!0,this._bounds=new L.LatLngBounds,c&&this._addChild(c),u&&this._addChild(u)},getAllChildMarkers:function(a,l){a=a||[];for(var c=this._childClusters.length-1;c>=0;c--)this._childClusters[c].getAllChildMarkers(a,l);for(var u=this._markers.length-1;u>=0;u--)l&&this._markers[u].__dragStart||a.push(this._markers[u]);return a},getChildCount:function(){return this._childCount},zoomToBounds:function(a){for(var l=this._childClusters.slice(),c=this._group._map,u=c.getBoundsZoom(this._bounds),_=this._zoom+1,b=c.getZoom(),x;l.length>0&&u>_;){_++;var E=[];for(x=0;x_?this._group._map.setView(this._latlng,_):u<=b?this._group._map.setView(this._latlng,b+1):this._group._map.fitBounds(this._bounds,a)},getBounds:function(){var a=new L.LatLngBounds;return a.extend(this._bounds),a},_updateIcon:function(){this._iconNeedsUpdate=!0,this._icon&&this.setIcon(this)},createIcon:function(){return this._iconNeedsUpdate&&(this._iconObj=this._group.options.iconCreateFunction(this),this._iconNeedsUpdate=!1),this._iconObj.createIcon()},createShadow:function(){return this._iconObj.createShadow()},_addChild:function(a,l){this._iconNeedsUpdate=!0,this._boundsNeedUpdate=!0,this._setClusterCenter(a),a instanceof L.MarkerCluster?(l||(this._childClusters.push(a),a.__parent=this),this._childCount+=a._childCount):(l||this._markers.push(a),this._childCount++),this.__parent&&this.__parent._addChild(a,!0)},_setClusterCenter:function(a){this._cLatLng||(this._cLatLng=a._cLatLng||a._latlng)},_resetBounds:function(){var a=this._bounds;a._southWest&&(a._southWest.lat=1/0,a._southWest.lng=1/0),a._northEast&&(a._northEast.lat=-1/0,a._northEast.lng=-1/0)},_recalculateBounds:function(){var a=this._markers,l=this._childClusters,c=0,u=0,_=this._childCount,b,x,E,I;if(_!==0){for(this._resetBounds(),b=0;b=0;b--)x=_[b],x._icon&&(x._setPos(l),x.clusterHide())},function(u){var _=u._childClusters,b,x;for(b=_.length-1;b>=0;b--)x=_[b],x._icon&&(x._setPos(l),x.clusterHide())})},_recursivelyAnimateChildrenInAndAddSelfToMap:function(a,l,c,u){this._recursively(a,u,l,function(_){_._recursivelyAnimateChildrenIn(a,_._group._map.latLngToLayerPoint(_.getLatLng()).round(),c),_._isSingleParent()&&c-1===u?(_.clusterShow(),_._recursivelyRemoveChildrenFromMap(a,l,c)):_.clusterHide(),_._addToMap()})},_recursivelyBecomeVisible:function(a,l){this._recursively(a,this._group._map.getMinZoom(),l,null,function(c){c.clusterShow()})},_recursivelyAddChildrenToMap:function(a,l,c){this._recursively(c,this._group._map.getMinZoom()-1,l,function(u){if(l!==u._zoom)for(var _=u._markers.length-1;_>=0;_--){var b=u._markers[_];!c.contains(b._latlng)||(a&&(b._backupLatlng=b.getLatLng(),b.setLatLng(a),b.clusterHide&&b.clusterHide()),u._group._featureGroup.addLayer(b))}},function(u){u._addToMap(a)})},_recursivelyRestoreChildPositions:function(a){for(var l=this._markers.length-1;l>=0;l--){var c=this._markers[l];c._backupLatlng&&(c.setLatLng(c._backupLatlng),delete c._backupLatlng)}if(a-1===this._zoom)for(var u=this._childClusters.length-1;u>=0;u--)this._childClusters[u]._restorePosition();else for(var _=this._childClusters.length-1;_>=0;_--)this._childClusters[_]._recursivelyRestoreChildPositions(a)},_restorePosition:function(){this._backupLatlng&&(this.setLatLng(this._backupLatlng),delete this._backupLatlng)},_recursivelyRemoveChildrenFromMap:function(a,l,c,u){var _,b;this._recursively(a,l-1,c-1,function(x){for(b=x._markers.length-1;b>=0;b--)_=x._markers[b],(!u||!u.contains(_._latlng))&&(x._group._featureGroup.removeLayer(_),_.clusterShow&&_.clusterShow())},function(x){for(b=x._childClusters.length-1;b>=0;b--)_=x._childClusters[b],(!u||!u.contains(_._latlng))&&(x._group._featureGroup.removeLayer(_),_.clusterShow&&_.clusterShow())})},_recursively:function(a,l,c,u,_){var b=this._childClusters,x=this._zoom,E,I;if(l<=x&&(u&&u(this),_&&x===c&&_(this)),x=0;E--)I=b[E],I._boundsNeedUpdate&&I._recalculateBounds(),a.intersects(I._bounds)&&I._recursively(a,l,c,u,_)},_isSingleParent:function(){return this._childClusters.length>0&&this._childClusters[0]._childCount===this._childCount}});L.Marker.include({clusterHide:function(){var a=this.options.opacity;return this.setOpacity(0),this.options.opacity=a,this},clusterShow:function(){return this.setOpacity(this.options.opacity)}}),L.DistanceGrid=function(a){this._cellSize=a,this._sqCellSize=a*a,this._grid={},this._objectPoint={}},L.DistanceGrid.prototype={addObject:function(a,l){var c=this._getCoord(l.x),u=this._getCoord(l.y),_=this._grid,b=_[u]=_[u]||{},x=b[c]=b[c]||[],E=L.Util.stamp(a);this._objectPoint[E]=l,x.push(a)},updateObject:function(a,l){this.removeObject(a),this.addObject(a,l)},removeObject:function(a,l){var c=this._getCoord(l.x),u=this._getCoord(l.y),_=this._grid,b=_[u]=_[u]||{},x=b[c]=b[c]||[],E,I;for(delete this._objectPoint[L.Util.stamp(a)],E=0,I=x.length;E=0;b--){if(x=l[b],E=this.getDistant(x,a),E>0)_.push(x);else continue;E>c&&(c=E,u=x)}return{maxPoint:u,newPoints:_}},buildConvexHull:function(a,l){var c=[],u=this.findMostDistantPointFromBaseLine(a,l);return u.maxPoint?(c=c.concat(this.buildConvexHull([a[0],u.maxPoint],u.newPoints)),c=c.concat(this.buildConvexHull([u.maxPoint,a[1]],u.newPoints)),c):[a[0]]},getConvexHull:function(a){var l=!1,c=!1,u=!1,_=!1,b=null,x=null,E=null,I=null,k=null,T=null,O;for(O=a.length-1;O>=0;O--){var $=a[O];(l===!1||$.lat>l)&&(b=$,l=$.lat),(c===!1||$.latu)&&(E=$,u=$.lng),(_===!1||$.lng<_)&&(I=$,_=$.lng)}c!==l?(T=x,k=b):(T=I,k=E);var D=[].concat(this.buildConvexHull([T,k],a),this.buildConvexHull([k,T],a));return D}}}(),L.MarkerCluster.include({getConvexHull:function(){var a=this.getAllChildMarkers(),l=[],c,u;for(u=a.length-1;u>=0;u--)c=a[u].getLatLng(),l.push(c);return L.QuickHull.getConvexHull(l)}}),L.MarkerCluster.include({_2PI:Math.PI*2,_circleFootSeparation:25,_circleStartAngle:0,_spiralFootSeparation:28,_spiralLengthStart:11,_spiralLengthFactor:5,_circleSpiralSwitchover:9,spiderfy:function(){if(!(this._group._spiderfied===this||this._group._inZoomAnimation)){var a=this.getAllChildMarkers(null,!0),l=this._group,c=l._map,u=c.latLngToLayerPoint(this._latlng),_;this._group._unspiderfy(),this._group._spiderfied=this,this._group.options.spiderfyShapePositions?_=this._group.options.spiderfyShapePositions(a.length,u):a.length>=this._circleSpiralSwitchover?_=this._generatePointsSpiral(a.length,u):(u.y+=10,_=this._generatePointsCircle(a.length,u)),this._animationSpiderfy(a,_)}},unspiderfy:function(a){this._group._inZoomAnimation||(this._animationUnspiderfy(a),this._group._spiderfied=null)},_generatePointsCircle:function(a,l){var c=this._group.options.spiderfyDistanceMultiplier*this._circleFootSeparation*(2+a),u=c/this._2PI,_=this._2PI/a,b=[],x,E;for(u=Math.max(u,35),b.length=a,x=0;x=0;I--)I=0;b--)_=u[b],c.removeLayer(_),_._preSpiderfyLatlng&&(_.setLatLng(_._preSpiderfyLatlng),delete _._preSpiderfyLatlng),_.setZIndexOffset&&_.setZIndexOffset(0),_._spiderLeg&&(l.removeLayer(_._spiderLeg),delete _._spiderLeg);a.fire("unspiderfied",{cluster:this,markers:u}),a._ignoreMove=!1,a._spiderfied=null}}),L.MarkerClusterNonAnimated=L.MarkerCluster.extend({_animationSpiderfy:function(a,l){var c=this._group,u=c._map,_=c._featureGroup,b=this._group.options.spiderLegPolylineOptions,x,E,I,k;for(c._ignoreMove=!0,x=0;x=0;O--)ie=_.layerPointToLatLng(l[O]),$=a[O],$._preSpiderfyLatlng=$._latlng,$.setLatLng(ie),$.clusterShow&&$.clusterShow(),I&&(D=$._spiderLeg,N=D._path,N.style.strokeDashoffset=0,D.setStyle({opacity:T}));this.setOpacity(.3),u._ignoreMove=!1,setTimeout(function(){u._animationEnd(),u.fire("spiderfied",{cluster:c,markers:a})},200)},_animationUnspiderfy:function(a){var l=this,c=this._group,u=c._map,_=c._featureGroup,b=a?u._latLngToNewLayerPoint(this._latlng,a.zoom,a.center):u.latLngToLayerPoint(this._latlng),x=this.getAllChildMarkers(null,!0),E=L.Path.SVG,I,k,T,O,$,D;for(c._ignoreMove=!0,c._animationStart(),this.setOpacity(1),k=x.length-1;k>=0;k--)I=x[k],I._preSpiderfyLatlng&&(I.closePopup(),I.setLatLng(I._preSpiderfyLatlng),delete I._preSpiderfyLatlng,D=!0,I._setPos&&(I._setPos(b),D=!1),I.clusterHide&&(I.clusterHide(),D=!1),D&&_.removeLayer(I),E&&(T=I._spiderLeg,O=T._path,$=O.getTotalLength()+.1,O.style.strokeDashoffset=$,T.setStyle({opacity:0})));c._ignoreMove=!1,setTimeout(function(){var N=0;for(k=x.length-1;k>=0;k--)I=x[k],I._spiderLeg&&N++;for(k=x.length-1;k>=0;k--)I=x[k],I._spiderLeg&&(I.clusterShow&&I.clusterShow(),I.setZIndexOffset&&I.setZIndexOffset(0),N>1&&_.removeLayer(I),u.removeLayer(I._spiderLeg),delete I._spiderLeg);c._animationEnd(),c.fire("unspiderfied",{cluster:l,markers:x})},200)}}),L.MarkerClusterGroup.include({_spiderfied:null,unspiderfy:function(){this._unspiderfy.apply(this,arguments)},_spiderfierOnAdd:function(){this._map.on("click",this._unspiderfyWrapper,this),this._map.options.zoomAnimation&&this._map.on("zoomstart",this._unspiderfyZoomStart,this),this._map.on("zoomend",this._noanimationUnspiderfy,this),L.Browser.touch||this._map.getRenderer(this)},_spiderfierOnRemove:function(){this._map.off("click",this._unspiderfyWrapper,this),this._map.off("zoomstart",this._unspiderfyZoomStart,this),this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._map.off("zoomend",this._noanimationUnspiderfy,this),this._noanimationUnspiderfy()},_unspiderfyZoomStart:function(){!this._map||this._map.on("zoomanim",this._unspiderfyZoomAnim,this)},_unspiderfyZoomAnim:function(a){L.DomUtil.hasClass(this._map._mapPane,"leaflet-touching")||(this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._unspiderfy(a))},_unspiderfyWrapper:function(){this._unspiderfy()},_unspiderfy:function(a){this._spiderfied&&this._spiderfied.unspiderfy(a)},_noanimationUnspiderfy:function(){this._spiderfied&&this._spiderfied._noanimationUnspiderfy()},_unspiderfyLayer:function(a){a._spiderLeg&&(this._featureGroup.removeLayer(a),a.clusterShow&&a.clusterShow(),a.setZIndexOffset&&a.setZIndexOffset(0),this._map.removeLayer(a._spiderLeg),delete a._spiderLeg)}}),L.MarkerClusterGroup.include({refreshClusters:function(a){return a?a instanceof L.MarkerClusterGroup?a=a._topClusterLevel.getAllChildMarkers():a instanceof L.LayerGroup?a=a._layers:a instanceof L.MarkerCluster?a=a.getAllChildMarkers():a instanceof L.Marker&&(a=[a]):a=this._topClusterLevel.getAllChildMarkers(),this._flagParentsIconsNeedUpdate(a),this._refreshClustersIcons(),this.options.singleMarkerMode&&this._refreshSingleMarkerModeMarkers(a),this},_flagParentsIconsNeedUpdate:function(a){var l,c;for(l in a)for(c=a[l].__parent;c;)c._iconNeedsUpdate=!0,c=c.__parent},_refreshSingleMarkerModeMarkers:function(a){var l,c;for(l in a)c=a[l],this.hasLayer(c)&&c.setIcon(this._overrideMarkerIcon(c))}}),L.Marker.include({refreshIconOptions:function(a,l){var c=this.options.icon;return L.setOptions(c,a),this.setIcon(c),l&&this.__parent&&this.__parent._group.refreshClusters(this),this}}),r.MarkerClusterGroup=n,r.MarkerCluster=o,Object.defineProperty(r,"__esModule",{value:!0})})})(leaflet_markerclusterSrc,leaflet_markerclusterSrc.exports);const MarkerCluster_Default="",MarkerCluster="",airtemp={label:"Airtemp",unit:"\u2103"},airtempavg={label:"AvgAirtemp",unit:"\u2103"},airtempmax={label:"MaxAirtemp",unit:"\u2103"},airtempmin={label:"MinAirtemp",unit:"\u2103"},co={label:"CO",name:{en:"Carbon monoxide",ru:"\u0423\u0433\u0430\u0440\u043D\u044B\u0439 \u0433\u0430\u0437"},unit:"mg/m3",chartColor:"#c1c1c1",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,2,4,14],zones:[{value:0,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:2,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:4,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,28.01)},info:"\u0421arbon monoxide. It is formed during the incomplete decomposition of organic compounds and during the combustion of biomass during forest fires."},gc={label:"GC",name:{en:"Radiation",ru:"\u0420\u0430\u0434\u0438\u0430\u0446\u0438\u044F"},unit:"\u03BCR/h",chartColor:"#e99152",range:[2,10,100,1e3],zones:[{value:2,color:"#60bc2a",label:{en:"Background",ru:"\u0424\u043E\u043D\u043E\u0432\u0430\u044F"}},{value:10,color:"#03a5ed",label:{en:"Moderate",ru:"\u041D\u0435\u0432\u044B\u0441\u043E\u043A\u0430\u044F"}},{value:100,color:"#ff9d00",label:{en:"Elevated",ru:"\u041F\u043E\u0432\u044B\u0448\u0435\u043D\u043D\u0430\u044F"}},{color:"#ff4d00",label:{en:"High",ru:"\u0412\u044B\u0441\u043E\u043A\u0430\u044F"}}]},humidity={label:"Hm",name:{en:"Humidity",ru:"\u0412\u043B\u0430\u0436\u043D\u043E\u0441\u0442\u044C"},unit:"%",chartColor:"#6fd3ff",range:[30,40,60,70],zones:[{value:30,color:"#ff4d00",label:{en:"Very dry",ru:"\u041E\u0447\u0435\u043D\u044C \u0441\u0443\u0445\u043E"}},{value:40,color:"#ff9d00",label:{en:"Dry",ru:"\u0421\u0443\u0445\u043E"}},{value:60,color:"#03a5ed",label:{en:"Comfortable",ru:"\u041A\u043E\u043C\u0444\u043E\u0440\u0442\u043D\u043E"}},{value:70,color:"#2a5cbc",label:{en:"Humid",ru:"\u0412\u043B\u0430\u0436\u043D\u043E"}},{color:"#7a00da",label:{en:"Very humid",ru:"\u041E\u0447\u0435\u043D\u044C \u0432\u043B\u0430\u0436\u043D\u043E"}}]},nh3={label:"NH3",name:{en:"Ammonia",ru:"\u0410\u043C\u043C\u0438\u0430\u043A"},unit:"mg/m3",icon:"vial-virus",chartColor:"#a1e37a",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,15,40],zones:[{value:15,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:40,color:"#ff9d00",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{color:"#fc0202",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,17.03)}},no2={label:"NO2",name:{en:"Nitrogen Dioxide",ru:"\u0414\u0438\u043E\u043A\u0441\u0438\u0434 \u0430\u0437\u043E\u0442\u0430"},unit:"mg/m3",chartColor:"#d4dd53",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,1,5],zones:[{value:1,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:5,color:"#ff9d00",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{color:"#fc0202",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}}],calculate:function(e){return converterPpmToMgm3(e,46.01)}},pm1={label:"PM1",unit:"\u03BCg/m3",chartColor:"#ff99e9"},pm10={label:"PM10",unit:"\u03BCg/m3",chartColor:"#e8b738",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,51,101,251,350],zones:[{value:50,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:100,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:250,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{value:350,color:"#ff4d00",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Unacceptable",ru:"\u041D\u0435\u043F\u0440\u0438\u0435\u043C\u043B\u0435\u043C\u043E"}}],calculate:function(e){return toFixed(e)},info:"PM10 - suspended particles (PM - particulate matter) of a substance with a diameter of less than 10 micrometers (\u03BCm). Pollen and other allergens."},pm25={label:"PM2.5",unit:"\u03BCg/m3",chartColor:"#89b268",colors:["#60bc2a","#ff9d00","#fc0202"],range:[0,36,70,151,251],zones:[{value:36,color:"#60bc2a",label:{en:"Good",ru:"\u0425\u043E\u0440\u043E\u0448\u043E"}},{value:70,color:"#12bfcc",label:{en:"Satisfyingly",ru:"\u0423\u0434\u043E\u0432\u043B\u0435\u0442\u0432\u043E\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E"}},{value:150,color:"#ff9d00",label:{en:"Poor",ru:"\u041F\u043B\u043E\u0445\u043E"}},{value:250,color:"#ff4d00",label:{en:"Very poor",ru:"\u041E\u0447\u0435\u043D\u044C \u043F\u043B\u043E\u0445\u043E"}},{color:"#7a00da",label:{en:"Unacceptable",ru:"\u041D\u0435\u043F\u0440\u0438\u0435\u043C\u043B\u0435\u043C\u043E"}}],calculate:function(e){return toFixed(e)},info:"Suspended, solid and liquid particles with a diameter of 2.5 microns are an air pollutant."},pressure={label:"Pr",name:{en:"Atmospheric pressure",ru:"\u0410\u0442\u043C\u043E\u0441\u0444\u0435\u0440\u043D\u043E\u0435 \u0434\u0430\u0432\u043B\u0435\u043D\u0438\u0435"},unit:"mmHg"},rainfall={label:"Rainfall",unit:"mm"},sat10={label:"Sat10",unit:""},sat5={label:"Sat5",unit:""},soiltemp={label:"Soiltemp",unit:"\u2103"},temperature={label:"Tmp",name:{en:"Temperature",ru:"\u0422\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u0430"},unit:"\u2103",chartColor:"#2d7ac7",colors:["#fc0202","#ff9d00","#60bc2a","#ff9d00","#fc0202"],range:[-10,0,10,25],zones:[{value:-9,color:"#7a00da",label:{en:"Very cold",ru:"\u041E\u0447\u0435\u043D\u044C \u0445\u043E\u043B\u043E\u0434\u043D\u043E"}},{value:0,color:"#2a5cbc",label:{en:"Cold",ru:"\u0425\u043E\u043B\u043E\u0434\u043D\u043E"}},{value:10,color:"#03a5ed",label:{en:"Cool",ru:"\u041F\u0440\u043E\u0445\u043B\u0430\u0434\u043D\u043E"}},{value:25,color:"#60bc2a",label:{en:"Warm",ru:"\u0422\u0435\u043F\u043B\u043E"}},{color:"#ff9d00",label:{en:"Very warm",ru:"\u041E\u0447\u0435\u043D\u044C \u0442\u0435\u043F\u043B\u043E"}}],states:["danger","attention","good","attention","danger","neutral"],calculate:function(e){return toFixed(e)},info:"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C \u0442\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u044B \u0432\u043E\u0437\u0434\u0443\u0445\u0430"},windang={label:"Windang",unit:"\xB0",icon:"wind"},windspeed={label:"Windspeed",unit:"m/s",icon:"wind"},windspeedmax={label:"Windspeedmax",unit:"m/s"},measurements={airtemp,airtempavg,airtempmax,airtempmin,co,gc,humidity,nh3,no2,pm1,pm10,pm25,pressure,rainfall,sat10,sat5,soiltemp,temperature,windang,windspeed,windspeedmax};function toFixed(e,t=4){return+(+e||0).toFixed(t)}function converterPpmToMgm3(e,t){return toFixed(e*t/24.05526)}const states=["good","attention","danger","neutral"];function getMeasurementByName(e){return measurements[e]||measurements.pm10}const artesiantlt="/assets/artesiantlt.b6bada62.jpg",atc="/assets/atc.09cec0ab.png",dolinatlt="/assets/dolinatlt.9bfd5fdc.jpg",ekovoz="/assets/ekovoz.af7d8a74.png",panorama="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACGVBMVEUAAACz00SfykaQuUWZx0ZQnEyax0aBu0iBu0iBvElgmUhpsExosEtgm0irz0SawkWrz0aTxUiTxEd2rkeTw0d4uUp6uUp6uEp6uUl6uUpwoUZhrUxTnkuly0ZGnE1Jok6lzUaLwUiNwUiNwEdko0hztUp0tUpztkpcn0lam0qHtUZbqk1ooEebw0ZytUpytUlTmks7iktytkp0tUxAnVBBnk9Ank9Bn088lk8vf0wueUote0s/mk9AnU0sbEgobUl9q0Ztn0d6qUaYw0aeyUaCskeAskdzo0Ztnkeax0eaxkeKu0dknEdRkklYoUtRm0tWnUpPkUlknUeSwUebx0eCu0qCu0mBu0lkoklBhUpAhUpqp0qCvElUmEpiqEtpsExpr0tpsEtYn0pZn0tmrUtVlkl4qUZLjkpJmExQpE5GlkxHlkxIl0xQkkproUeiyEWTw0iTw0dSkkk1iU0ziU0zjE45iUtZmEl3rEeSw0d6uEp6t0pvrkpQkklMjUp0s0pgm0lPlkpirExhrExUnEtWnktdl0ily0aUwEZblkhHjUpClExBlE1JoU5Hnk1EjktgmUiFs0alzEaMwEhloElEjEovf0wvgk1FjEpemkiGukh0tUt0tEpXmUp0tUpvsUpcl0hNkEpUoExbqk1bqUxPm0xPmktbqU1RnEtJjklytUpBi0s8jUxCm048kk1CnE5AiktcoUv///8iSiW7AAAAQHRSTlMAf/7+f/7+f/7+f/7+f3/+f3/+/v5//v7+f3/+/n/+/n9//v5//v7+/n9//v5/f/7v/v5/YL+/v7+/3++/YEA/+66NsgAAAAFiS0dEsq1qz+gAAAEDSURBVBjTY2B0cHRydnFxdWNycXb3YGZkYPH08vbx9fNnDQgMCmYLYWFg5wgNC+eMiIyKDguLieFkZ+CKjYtP4E5MSuaJT0xISeVl4ONPS8/IzMzKzszMyc3LF2AQLCgUEi4qLiktK68QEqkUZBCtqharqqqprasXrxITk5BkkGpolG5qbm6RaZJukm5tk2KQbe/o7JKT7+7p7eufMHGSAoPi5MlKk6dMnTZ9xsxZk5WUFRlUZs9Rna2mrjF3tursebPnazJoLVi4SHvxkqXLli/XXrFSR5dBb5W+weo1a9etW2+4YaPRKmMGE1MzU3MLSytrSxtTILBlgAI7ewZUABcAAE5TTddsyTFjAAAAAElFTkSuQmCC",qvantorium="/assets/qvantorium.d5858788.jpg",sun="/assets/sun.d26ef6d1.png",sensors={"7e071fd9b023ed8f18458a73613a0834f6220bd5cc50357ba3493c6040a9ea8c":{icon:ekovoz,link:"http://ekovoz.ru/"},"162ebfac08a69bc96c0bd569c95026c6750cbecca7a61731dfe1a985a9391176":{icon:atc,link:"http://atcgaz.ru/"},"7c7ffabc786c46ff40d8ca922b1248e1261baefec702eea160001140063f8c53":{icon:atc,link:"http://atcgaz.ru/"},"7cdeafa03331cb330c3993ff0381457f0713a8fd6d0b3dbe93ea24affe5676ac":{icon:artesiantlt,link:"https://www.artesiantlt.ru/"},"217a9ae639e48a9b99de7895c496b224ad6a80f9b679d516557561aedd47c58b":{icon:qvantorium,link:"https://vk.com/kvantoriumtlt"},f5cf0ec44b696400af9b280cb5bedc9e10893f5f961159658a218286f8e97372:{icon:dolinatlt,link:"https://dolinatlt.ru/"},"5bd528a4d708304254d2417b83f8b5c997ed08ccf956fa4e538fc6cfa40f86c0":{icon:panorama,link:"https://panorama-park63.ru/"},e4871acd155431c63fbbc54b89d015bc17bc5fbe44d5846502f7e58566e24a8e:{link:"https://airalab.org/"},"62c86fb3712e2c8e3d8a7a79f62c1cb0dbd4ad2980606dbf8fcf96ce9ed46c8d":{icon:sun}};var chroma$1={exports:{}};/** * chroma.js - JavaScript library for color conversions * * Copyright (c) 2011-2019, Gregor Aisch @@ -84,13 +84,13 @@ hooks.version="2.29.4";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min * http://www.w3.org/TR/css3-color/#svg-color * * @preserve - */(function(e,t){(function(r,n){e.exports=n()})(commonjsGlobal$2,function(){for(var r=function(Te,De,We){return De===void 0&&(De=0),We===void 0&&(We=1),TeWe?We:Te},n=r,o=function(Te){Te._clipped=!1,Te._unclipped=Te.slice(0);for(var De=0;De<=3;De++)De<3?((Te[De]<0||Te[De]>255)&&(Te._clipped=!0),Te[De]=n(Te[De],0,255)):De===3&&(Te[De]=n(Te[De],0,1));return Te},a={},l=0,c=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"];l=3?Array.prototype.slice.call(Te):b(Te[0])=="object"&&De?De.split("").filter(function(We){return Te[0][We]!==void 0}).map(function(We){return Te[0][We]}):Te[0]},E=_,I=function(Te){if(Te.length<2)return null;var De=Te.length-1;return E(Te[De])=="string"?Te[De].toLowerCase():null},k=Math.PI,T={clip_rgb:o,limit:r,type:_,unpack:x,last:I,PI:k,TWOPI:k*2,PITHIRD:k/3,DEG2RAD:k/180,RAD2DEG:180/k},O={format:{},autodetect:[]},$=T.last,D=T.clip_rgb,N=T.type,H=O,ie=function(){for(var De=[],We=arguments.length;We--;)De[We]=arguments[We];var Qe=this;if(N(De[0])==="object"&&De[0].constructor&&De[0].constructor===this.constructor)return De[0];var ht=$(De),ft=!1;if(!ht){ft=!0,H.sorted||(H.autodetect=H.autodetect.sort(function(bt,At){return At.p-bt.p}),H.sorted=!0);for(var ct=0,pt=H.autodetect;ct4?Te[4]:1;return ft===1?[0,0,0,ct]:[We>=1?0:255*(1-We)*(1-ft),Qe>=1?0:255*(1-Qe)*(1-ft),ht>=1?0:255*(1-ht)*(1-ft),ct]},te=xe,ae=le,ge=ue,se=O,Se=T.unpack,Pe=T.type,Ue=he;ge.prototype.cmyk=function(){return Ue(this._rgb)},ae.cmyk=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(ge,[null].concat(Te,["cmyk"])))},se.format.cmyk=te,se.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Se(Te,"cmyk"),Pe(Te)==="array"&&Te.length===4)return"cmyk"}});var Be=T.unpack,fe=T.last,ye=function(Te){return Math.round(Te*100)/100},Ce=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Be(Te,"hsla"),Qe=fe(Te)||"lsa";return We[0]=ye(We[0]||0),We[1]=ye(We[1]*100)+"%",We[2]=ye(We[2]*100)+"%",Qe==="hsla"||We.length>3&&We[3]<1?(We[3]=We.length>3?We[3]:1,Qe="hsla"):We.length=3,Qe+"("+We.join(",")+")"},Le=Ce,Fe=T.unpack,Oe=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Fe(Te,"rgba");var We=Te[0],Qe=Te[1],ht=Te[2];We/=255,Qe/=255,ht/=255;var ft=Math.min(We,Qe,ht),ct=Math.max(We,Qe,ht),pt=(ct+ft)/2,gt,vt;return ct===ft?(gt=0,vt=Number.NaN):gt=pt<.5?(ct-ft)/(ct+ft):(ct-ft)/(2-ct-ft),We==ct?vt=(Qe-ht)/(ct-ft):Qe==ct?vt=2+(ht-We)/(ct-ft):ht==ct&&(vt=4+(We-Qe)/(ct-ft)),vt*=60,vt<0&&(vt+=360),Te.length>3&&Te[3]!==void 0?[vt,gt,pt,Te[3]]:[vt,gt,pt]},be=Oe,Re=T.unpack,Ie=T.last,we=Le,oe=be,pe=Math.round,ke=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Re(Te,"rgba"),Qe=Ie(Te)||"rgb";return Qe.substr(0,3)=="hsl"?we(oe(We),Qe):(We[0]=pe(We[0]),We[1]=pe(We[1]),We[2]=pe(We[2]),(Qe==="rgba"||We.length>3&&We[3]<1)&&(We[3]=We.length>3?We[3]:1,Qe="rgba"),Qe+"("+We.slice(0,Qe==="rgb"?3:4).join(",")+")")},Ne=ke,ze=T.unpack,Xe=Math.round,Je=function(){for(var Te,De=[],We=arguments.length;We--;)De[We]=arguments[We];De=ze(De,"hsl");var Qe=De[0],ht=De[1],ft=De[2],ct,pt,gt;if(ht===0)ct=pt=gt=ft*255;else{var vt=[0,0,0],bt=[0,0,0],At=ft<.5?ft*(1+ht):ft+ht-ft*ht,wt=2*ft-At,It=Qe/360;vt[0]=It+1/3,vt[1]=It,vt[2]=It-1/3;for(var Pt=0;Pt<3;Pt++)vt[Pt]<0&&(vt[Pt]+=1),vt[Pt]>1&&(vt[Pt]-=1),6*vt[Pt]<1?bt[Pt]=wt+(At-wt)*6*vt[Pt]:2*vt[Pt]<1?bt[Pt]=At:3*vt[Pt]<2?bt[Pt]=wt+(At-wt)*(2/3-vt[Pt])*6:bt[Pt]=wt;Te=[Xe(bt[0]*255),Xe(bt[1]*255),Xe(bt[2]*255)],ct=Te[0],pt=Te[1],gt=Te[2]}return De.length>3?[ct,pt,gt,De[3]]:[ct,pt,gt,1]},rt=Je,qe=rt,Ve=O,Ae=/^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/,He=/^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/,Ge=/^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,Ze=/^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,$e=/^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,me=/^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,Ee=Math.round,je=function(Te){Te=Te.toLowerCase().trim();var De;if(Ve.format.named)try{return Ve.format.named(Te)}catch{}if(De=Te.match(Ae)){for(var We=De.slice(1,4),Qe=0;Qe<3;Qe++)We[Qe]=+We[Qe];return We[3]=1,We}if(De=Te.match(He)){for(var ht=De.slice(1,5),ft=0;ft<4;ft++)ht[ft]=+ht[ft];return ht}if(De=Te.match(Ge)){for(var ct=De.slice(1,4),pt=0;pt<3;pt++)ct[pt]=Ee(ct[pt]*2.55);return ct[3]=1,ct}if(De=Te.match(Ze)){for(var gt=De.slice(1,5),vt=0;vt<3;vt++)gt[vt]=Ee(gt[vt]*2.55);return gt[3]=+gt[3],gt}if(De=Te.match($e)){var bt=De.slice(1,4);bt[1]*=.01,bt[2]*=.01;var At=qe(bt);return At[3]=1,At}if(De=Te.match(me)){var wt=De.slice(1,4);wt[1]*=.01,wt[2]*=.01;var It=qe(wt);return It[3]=+De[4],It}};je.test=function(Te){return Ae.test(Te)||He.test(Te)||Ge.test(Te)||Ze.test(Te)||$e.test(Te)||me.test(Te)};var nt=je,ot=le,dt=ue,Ct=O,St=T.type,kt=Ne,Et=nt;dt.prototype.css=function(Te){return kt(this._rgb,Te)},ot.css=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(dt,[null].concat(Te,["css"])))},Ct.format.css=Et,Ct.autodetect.push({p:5,test:function(Te){for(var De=[],We=arguments.length-1;We-- >0;)De[We]=arguments[We+1];if(!De.length&&St(Te)==="string"&&Et.test(Te))return"css"}});var Lt=ue,tr=le,Xt=O,wr=T.unpack;Xt.format.gl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=wr(Te,"rgba");return We[0]*=255,We[1]*=255,We[2]*=255,We},tr.gl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Lt,[null].concat(Te,["gl"])))},Lt.prototype.gl=function(){var Te=this._rgb;return[Te[0]/255,Te[1]/255,Te[2]/255,Te[3]]};var nr=T.unpack,dr=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=nr(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Math.min(Qe,ht,ft),pt=Math.max(Qe,ht,ft),gt=pt-ct,vt=gt*100/255,bt=ct/(255-gt)*100,At;return gt===0?At=Number.NaN:(Qe===pt&&(At=(ht-ft)/gt),ht===pt&&(At=2+(ft-Qe)/gt),ft===pt&&(At=4+(Qe-ht)/gt),At*=60,At<0&&(At+=360)),[At,vt,bt]},pr=dr,po=T.unpack,go=Math.floor,yo=function(){for(var Te,De,We,Qe,ht,ft,ct=[],pt=arguments.length;pt--;)ct[pt]=arguments[pt];ct=po(ct,"hcg");var gt=ct[0],vt=ct[1],bt=ct[2],At,wt,It;bt=bt*255;var Pt=vt*255;if(vt===0)At=wt=It=bt;else{gt===360&&(gt=0),gt>360&&(gt-=360),gt<0&&(gt+=360),gt/=60;var Bt=go(gt),Ht=gt-Bt,jt=bt*(1-vt),Kt=jt+Pt*(1-Ht),gr=jt+Pt*Ht,fr=jt+Pt;switch(Bt){case 0:Te=[fr,gr,jt],At=Te[0],wt=Te[1],It=Te[2];break;case 1:De=[Kt,fr,jt],At=De[0],wt=De[1],It=De[2];break;case 2:We=[jt,fr,gr],At=We[0],wt=We[1],It=We[2];break;case 3:Qe=[jt,Kt,fr],At=Qe[0],wt=Qe[1],It=Qe[2];break;case 4:ht=[gr,jt,fr],At=ht[0],wt=ht[1],It=ht[2];break;case 5:ft=[fr,jt,Kt],At=ft[0],wt=ft[1],It=ft[2];break}}return[At,wt,It,ct.length>3?ct[3]:1]},vo=yo,xi=T.unpack,_o=T.type,bo=le,ns=ue,is=O,Tr=pr;ns.prototype.hcg=function(){return Tr(this._rgb)},bo.hcg=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(ns,[null].concat(Te,["hcg"])))},is.format.hcg=vo,is.autodetect.push({p:1,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=xi(Te,"hcg"),_o(Te)==="array"&&Te.length===3)return"hcg"}});var $t=T.unpack,ss=T.last,En=Math.round,os=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$t(Te,"rgba"),Qe=We[0],ht=We[1],ft=We[2],ct=We[3],pt=ss(Te)||"auto";ct===void 0&&(ct=1),pt==="auto"&&(pt=ct<1?"rgba":"rgb"),Qe=En(Qe),ht=En(ht),ft=En(ft);var gt=Qe<<16|ht<<8|ft,vt="000000"+gt.toString(16);vt=vt.substr(vt.length-6);var bt="0"+En(ct*255).toString(16);switch(bt=bt.substr(bt.length-2),pt.toLowerCase()){case"rgba":return"#"+vt+bt;case"argb":return"#"+bt+vt;default:return"#"+vt}},Ei=os,Si=/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,ls=/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/,hn=function(Te){if(Te.match(Si)){(Te.length===4||Te.length===7)&&(Te=Te.substr(1)),Te.length===3&&(Te=Te.split(""),Te=Te[0]+Te[0]+Te[1]+Te[1]+Te[2]+Te[2]);var De=parseInt(Te,16),We=De>>16,Qe=De>>8&255,ht=De&255;return[We,Qe,ht,1]}if(Te.match(ls)){(Te.length===5||Te.length===9)&&(Te=Te.substr(1)),Te.length===4&&(Te=Te.split(""),Te=Te[0]+Te[0]+Te[1]+Te[1]+Te[2]+Te[2]+Te[3]+Te[3]);var ft=parseInt(Te,16),ct=ft>>24&255,pt=ft>>16&255,gt=ft>>8&255,vt=Math.round((ft&255)/255*100)/100;return[ct,pt,gt,vt]}throw new Error("unknown hex color: "+Te)},Ci=hn,wo=le,cs=ue,xo=T.type,us=O,hs=Ei;cs.prototype.hex=function(Te){return hs(this._rgb,Te)},wo.hex=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(cs,[null].concat(Te,["hex"])))},us.format.hex=Ci,us.autodetect.push({p:4,test:function(Te){for(var De=[],We=arguments.length-1;We-- >0;)De[We]=arguments[We+1];if(!De.length&&xo(Te)==="string"&&[3,4,5,6,7,8,9].indexOf(Te.length)>=0)return"hex"}});var Eo=T.unpack,Sn=T.TWOPI,So=Math.min,Co=Math.sqrt,ko=Math.acos,To=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Eo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2];Qe/=255,ht/=255,ft/=255;var ct,pt=So(Qe,ht,ft),gt=(Qe+ht+ft)/3,vt=gt>0?1-pt/gt:0;return vt===0?ct=NaN:(ct=(Qe-ht+(Qe-ft))/2,ct/=Co((Qe-ht)*(Qe-ht)+(Qe-ft)*(ht-ft)),ct=ko(ct),ft>ht&&(ct=Sn-ct),ct/=Sn),[ct*360,vt,gt]},Ao=To,ki=T.unpack,Yr=T.limit,Kr=T.TWOPI,Gn=T.PITHIRD,Ar=Math.cos,Wt=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=ki(Te,"hsi");var We=Te[0],Qe=Te[1],ht=Te[2],ft,ct,pt;return isNaN(We)&&(We=0),isNaN(Qe)&&(Qe=0),We>360&&(We-=360),We<0&&(We+=360),We/=360,We<1/3?(pt=(1-Qe)/3,ft=(1+Qe*Ar(Kr*We)/Ar(Gn-Kr*We))/3,ct=1-(pt+ft)):We<2/3?(We-=1/3,ft=(1-Qe)/3,ct=(1+Qe*Ar(Kr*We)/Ar(Gn-Kr*We))/3,pt=1-(ft+ct)):(We-=2/3,ct=(1-Qe)/3,pt=(1+Qe*Ar(Kr*We)/Ar(Gn-Kr*We))/3,ft=1-(ct+pt)),ft=Yr(ht*ft*3),ct=Yr(ht*ct*3),pt=Yr(ht*pt*3),[ft*255,ct*255,pt*255,Te.length>3?Te[3]:1]},ir=Wt,qn=T.unpack,fn=T.type,dn=le,Xn=ue,Nt=O,ar=Ao;Xn.prototype.hsi=function(){return ar(this._rgb)},dn.hsi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Xn,[null].concat(Te,["hsi"])))},Nt.format.hsi=ir,Nt.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=qn(Te,"hsi"),fn(Te)==="array"&&Te.length===3)return"hsi"}});var Ti=T.unpack,Zn=T.type,xr=le,fs=ue,Cn=O,Gr=be;fs.prototype.hsl=function(){return Gr(this._rgb)},xr.hsl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(fs,[null].concat(Te,["hsl"])))},Cn.format.hsl=rt,Cn.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Ti(Te,"hsl"),Zn(Te)==="array"&&Te.length===3)return"hsl"}});var lr=T.unpack,qr=Math.min,kn=Math.max,Tn=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=lr(Te,"rgb");var We=Te[0],Qe=Te[1],ht=Te[2],ft=qr(We,Qe,ht),ct=kn(We,Qe,ht),pt=ct-ft,gt,vt,bt;return bt=ct/255,ct===0?(gt=Number.NaN,vt=0):(vt=pt/ct,We===ct&&(gt=(Qe-ht)/pt),Qe===ct&&(gt=2+(ht-We)/pt),ht===ct&&(gt=4+(We-Qe)/pt),gt*=60,gt<0&&(gt+=360)),[gt,vt,bt]},Ai=Tn,An=T.unpack,Pi=Math.floor,Ii=function(){for(var Te,De,We,Qe,ht,ft,ct=[],pt=arguments.length;pt--;)ct[pt]=arguments[pt];ct=An(ct,"hsv");var gt=ct[0],vt=ct[1],bt=ct[2],At,wt,It;if(bt*=255,vt===0)At=wt=It=bt;else{gt===360&&(gt=0),gt>360&&(gt-=360),gt<0&&(gt+=360),gt/=60;var Pt=Pi(gt),Bt=gt-Pt,Ht=bt*(1-vt),jt=bt*(1-vt*Bt),Kt=bt*(1-vt*(1-Bt));switch(Pt){case 0:Te=[bt,Kt,Ht],At=Te[0],wt=Te[1],It=Te[2];break;case 1:De=[jt,bt,Ht],At=De[0],wt=De[1],It=De[2];break;case 2:We=[Ht,bt,Kt],At=We[0],wt=We[1],It=We[2];break;case 3:Qe=[Ht,jt,bt],At=Qe[0],wt=Qe[1],It=Qe[2];break;case 4:ht=[Kt,Ht,bt],At=ht[0],wt=ht[1],It=ht[2];break;case 5:ft=[bt,Ht,jt],At=ft[0],wt=ft[1],It=ft[2];break}}return[At,wt,It,ct.length>3?ct[3]:1]},Qn=Ii,$i=T.unpack,Li=T.type,Jn=le,Ri=ue,ei=O,Po=Ai;Ri.prototype.hsv=function(){return Po(this._rgb)},Jn.hsv=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Ri,[null].concat(Te,["hsv"])))},ei.format.hsv=Qn,ei.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=$i(Te,"hsv"),Li(Te)==="array"&&Te.length===3)return"hsv"}});var Ot={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},mr=Ot,Qt=T.unpack,Mi=Math.pow,Oi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Qt(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Xr(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2],bt=116*gt-16;return[bt<0?0:bt,500*(pt-gt),200*(gt-vt)]},Pn=function(Te){return(Te/=255)<=.04045?Te/12.92:Mi((Te+.055)/1.055,2.4)},In=function(Te){return Te>mr.t3?Mi(Te,1/3):Te/mr.t2+mr.t0},Xr=function(Te,De,We){Te=Pn(Te),De=Pn(De),We=Pn(We);var Qe=In((.4124564*Te+.3575761*De+.1804375*We)/mr.Xn),ht=In((.2126729*Te+.7151522*De+.072175*We)/mr.Yn),ft=In((.0193339*Te+.119192*De+.9503041*We)/mr.Zn);return[Qe,ht,ft]},ti=Oi,Pr=Ot,ur=T.unpack,Zr=Math.pow,ds=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=ur(Te,"lab");var We=Te[0],Qe=Te[1],ht=Te[2],ft,ct,pt,gt,vt,bt;return ct=(We+16)/116,ft=isNaN(Qe)?ct:ct+Qe/500,pt=isNaN(ht)?ct:ct-ht/200,ct=Pr.Yn*Di(ct),ft=Pr.Xn*Di(ft),pt=Pr.Zn*Di(pt),gt=ri(3.2404542*ft-1.5371385*ct-.4985314*pt),vt=ri(-.969266*ft+1.8760108*ct+.041556*pt),bt=ri(.0556434*ft-.2040259*ct+1.0572252*pt),[gt,vt,bt,Te.length>3?Te[3]:1]},ri=function(Te){return 255*(Te<=.00304?12.92*Te:1.055*Zr(Te,1/2.4)-.055)},Di=function(Te){return Te>Pr.t1?Te*Te*Te:Pr.t2*(Te-Pr.t0)},Ni=ds,Bi=T.unpack,Io=T.type,ps=le,Vt=ue,gs=O,Cr=ti;Vt.prototype.lab=function(){return Cr(this._rgb)},ps.lab=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Vt,[null].concat(Te,["lab"])))},gs.format.lab=Ni,gs.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Bi(Te,"lab"),Io(Te)==="array"&&Te.length===3)return"lab"}});var $n=T.unpack,ys=T.RAD2DEG,$o=Math.sqrt,Fi=Math.atan2,Lo=Math.round,vs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$n(Te,"lab"),Qe=We[0],ht=We[1],ft=We[2],ct=$o(ht*ht+ft*ft),pt=(Fi(ft,ht)*ys+360)%360;return Lo(ct*1e4)===0&&(pt=Number.NaN),[Qe,ct,pt]},_s=vs,Ro=T.unpack,Ui=ti,Mo=_s,Ir=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Ro(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Ui(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2];return Mo(pt,gt,vt)},Oo=Ir,bs=T.unpack,Vr=T.DEG2RAD,ws=Math.sin,xs=Math.cos,Do=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=bs(Te,"lch"),Qe=We[0],ht=We[1],ft=We[2];return isNaN(ft)&&(ft=0),ft=ft*Vr,[Qe,xs(ft)*ht,ws(ft)*ht]},Es=Do,Vi=T.unpack,No=Es,Ss=Ni,Cs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Vi(Te,"lch");var We=Te[0],Qe=Te[1],ht=Te[2],ft=No(We,Qe,ht),ct=ft[0],pt=ft[1],gt=ft[2],vt=Ss(ct,pt,gt),bt=vt[0],At=vt[1],wt=vt[2];return[bt,At,wt,Te.length>3?Te[3]:1]},Ln=Cs,Qr=T.unpack,Bo=Ln,Rn=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Qr(Te,"hcl").reverse();return Bo.apply(void 0,We)},Er=Rn,ks=T.unpack,Ts=T.type,As=le,Mn=ue,ni=O,Ps=Oo;Mn.prototype.lch=function(){return Ps(this._rgb)},Mn.prototype.hcl=function(){return Ps(this._rgb).reverse()},As.lch=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Mn,[null].concat(Te,["lch"])))},As.hcl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Mn,[null].concat(Te,["hcl"])))},ni.format.lch=Ln,ni.format.hcl=Er,["lch","hcl"].forEach(function(Te){return ni.autodetect.push({p:2,test:function(){for(var De=[],We=arguments.length;We--;)De[We]=arguments[We];if(De=ks(De,Te),Ts(De)==="array"&&De.length===3)return Te}})});var Hi={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflower:"#6495ed",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},ii=Hi,Fo=ue,Is=O,$s=T.type,On=ii,kr=Ci,pn=Ei;Fo.prototype.name=function(){for(var Te=pn(this._rgb,"rgb"),De=0,We=Object.keys(On);De0;)De[We]=arguments[We+1];if(!De.length&&$s(Te)==="string"&&On[Te.toLowerCase()])return"named"}});var Uo=T.unpack,Jr=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Uo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2];return(Qe<<16)+(ht<<8)+ft},Vo=Jr,mn=T.type,Ho=function(Te){if(mn(Te)=="number"&&Te>=0&&Te<=16777215){var De=Te>>16,We=Te>>8&255,Qe=Te&255;return[De,We,Qe,1]}throw new Error("unknown num color: "+Te)},Dn=Ho,Ls=le,Nn=ue,Rs=O,Hr=T.type,si=Vo;Nn.prototype.num=function(){return si(this._rgb)},Ls.num=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Nn,[null].concat(Te,["num"])))},Rs.format.num=Dn,Rs.autodetect.push({p:5,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te.length===1&&Hr(Te[0])==="number"&&Te[0]>=0&&Te[0]<=16777215)return"num"}});var zo=le,Bn=ue,Ms=O,$r=T.unpack,Os=T.type,en=Math.round;Bn.prototype.rgb=function(Te){return Te===void 0&&(Te=!0),Te===!1?this._rgb.slice(0,3):this._rgb.slice(0,3).map(en)},Bn.prototype.rgba=function(Te){return Te===void 0&&(Te=!0),this._rgb.slice(0,4).map(function(De,We){return We<3?Te===!1?De:en(De):De})},zo.rgb=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Bn,[null].concat(Te,["rgb"])))},Ms.format.rgb=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$r(Te,"rgba");return We[3]===void 0&&(We[3]=1),We},Ms.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=$r(Te,"rgba"),Os(Te)==="array"&&(Te.length===3||Te.length===4&&Os(Te[3])=="number"&&Te[3]>=0&&Te[3]<=1))return"rgb"}});var oi=Math.log,Rr=function(Te){var De=Te/100,We,Qe,ht;return De<66?(We=255,Qe=De<6?0:-155.25485562709179-.44596950469579133*(Qe=De-2)+104.49216199393888*oi(Qe),ht=De<20?0:-254.76935184120902+.8274096064007395*(ht=De-10)+115.67994401066147*oi(ht)):(We=351.97690566805693+.114206453784165*(We=De-55)-40.25366309332127*oi(We),Qe=325.4494125711974+.07943456536662342*(Qe=De-50)-28.0852963507957*oi(Qe),ht=255),[We,Qe,ht,1]},Fn=Rr,Ds=Fn,zi=T.unpack,ai=Math.round,Wi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];for(var We=zi(Te,"rgb"),Qe=We[0],ht=We[2],ft=1e3,ct=4e4,pt=.4,gt;ct-ft>pt;){gt=(ct+ft)*.5;var vt=Ds(gt);vt[2]/vt[0]>=ht/Qe?ct=gt:ft=gt}return ai(gt)},li=Wi,zr=le,tn=ue,Un=O,Ns=li;tn.prototype.temp=tn.prototype.kelvin=tn.prototype.temperature=function(){return Ns(this._rgb)},zr.temp=zr.kelvin=zr.temperature=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(tn,[null].concat(Te,["temp"])))},Un.format.temp=Un.format.kelvin=Un.format.temperature=Fn;var Wo=T.unpack,gn=Math.cbrt,jo=Math.pow,Bs=Math.sign,Yo=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Wo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=[Yi(Qe/255),Yi(ht/255),Yi(ft/255)],pt=ct[0],gt=ct[1],vt=ct[2],bt=gn(.4122214708*pt+.5363325363*gt+.0514459929*vt),At=gn(.2119034982*pt+.6806995451*gt+.1073969566*vt),wt=gn(.0883024619*pt+.2817188376*gt+.6299787005*vt);return[.2104542553*bt+.793617785*At-.0040720468*wt,1.9779984951*bt-2.428592205*At+.4505937099*wt,.0259040371*bt+.7827717662*At-.808675766*wt]},ji=Yo;function Yi(Te){var De=Math.abs(Te);return De<.04045?Te/12.92:(Bs(Te)||1)*jo((De+.055)/1.055,2.4)}var Lr=T.unpack,rn=Math.pow,Ko=Math.sign,ci=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Lr(Te,"lab");var We=Te[0],Qe=Te[1],ht=Te[2],ft=rn(We+.3963377774*Qe+.2158037573*ht,3),ct=rn(We-.1055613458*Qe-.0638541728*ht,3),pt=rn(We-.0894841775*Qe-1.291485548*ht,3);return[255*ui(4.0767416621*ft-3.3077115913*ct+.2309699292*pt),255*ui(-1.2684380046*ft+2.6097574011*ct-.3413193965*pt),255*ui(-.0041960863*ft-.7034186147*ct+1.707614701*pt),Te.length>3?Te[3]:1]},Fs=ci;function ui(Te){var De=Math.abs(Te);return De>.0031308?(Ko(Te)||1)*(1.055*rn(De,1/2.4)-.055):Te*12.92}var Go=T.unpack,Vn=T.type,qo=le,nn=ue,Ki=O,Us=ji;nn.prototype.oklab=function(){return Us(this._rgb)},qo.oklab=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(nn,[null].concat(Te,["oklab"])))},Ki.format.oklab=Fs,Ki.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Go(Te,"oklab"),Vn(Te)==="array"&&Te.length===3)return"oklab"}});var Xo=T.unpack,Mr=ji,Vs=_s,Hs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Xo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Mr(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2];return Vs(pt,gt,vt)},Hn=Hs,Zo=T.unpack,hi=Es,zn=Fs,zs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Zo(Te,"lch");var We=Te[0],Qe=Te[1],ht=Te[2],ft=hi(We,Qe,ht),ct=ft[0],pt=ft[1],gt=ft[2],vt=zn(ct,pt,gt),bt=vt[0],At=vt[1],wt=vt[2];return[bt,At,wt,Te.length>3?Te[3]:1]},Ws=zs,Qo=T.unpack,js=T.type,Ys=le,Gi=ue,qi=O,Ks=Hn;Gi.prototype.oklch=function(){return Ks(this._rgb)},Ys.oklch=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Gi,[null].concat(Te,["oklch"])))},qi.format.oklch=Ws,qi.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Qo(Te,"oklch"),js(Te)==="array"&&Te.length===3)return"oklch"}});var Gs=ue,qs=T.type;Gs.prototype.alpha=function(Te,De){return De===void 0&&(De=!1),Te!==void 0&&qs(Te)==="number"?De?(this._rgb[3]=Te,this):new Gs([this._rgb[0],this._rgb[1],this._rgb[2],Te],"rgb"):this._rgb[3]};var Xs=ue;Xs.prototype.clipped=function(){return this._rgb._clipped||!1};var sn=ue,g=Ot;sn.prototype.darken=function(Te){Te===void 0&&(Te=1);var De=this,We=De.lab();return We[0]-=g.Kn*Te,new sn(We,"lab").alpha(De.alpha(),!0)},sn.prototype.brighten=function(Te){return Te===void 0&&(Te=1),this.darken(-Te)},sn.prototype.darker=sn.prototype.darken,sn.prototype.brighter=sn.prototype.brighten;var S=ue;S.prototype.get=function(Te){var De=Te.split("."),We=De[0],Qe=De[1],ht=this[We]();if(Qe){var ft=We.indexOf(Qe)-(We.substr(0,2)==="ok"?2:0);if(ft>-1)return ht[ft];throw new Error("unknown channel "+Qe+" in mode "+We)}else return ht};var B=ue,_e=T.type,Me=Math.pow,Ke=1e-7,lt=20;B.prototype.luminance=function(Te){if(Te!==void 0&&_e(Te)==="number"){if(Te===0)return new B([0,0,0,this._rgb[3]],"rgb");if(Te===1)return new B([255,255,255,this._rgb[3]],"rgb");var De=this.luminance(),We="rgb",Qe=lt,ht=function(ct,pt){var gt=ct.interpolate(pt,.5,We),vt=gt.luminance();return Math.abs(Te-vt)Te?ht(ct,gt):ht(gt,pt)},ft=(De>Te?ht(new B([0,0,0]),this):ht(this,new B([255,255,255]))).rgb();return new B(ft.concat([this._rgb[3]]))}return mt.apply(void 0,this._rgb.slice(0,3))};var mt=function(Te,De,We){return Te=yt(Te),De=yt(De),We=yt(We),.2126*Te+.7152*De+.0722*We},yt=function(Te){return Te/=255,Te<=.03928?Te/12.92:Me((Te+.055)/1.055,2.4)},_t={},Tt=ue,Mt=T.type,Dt=_t,br=function(Te,De,We){We===void 0&&(We=.5);for(var Qe=[],ht=arguments.length-3;ht-- >0;)Qe[ht]=arguments[ht+3];var ft=Qe[0]||"lrgb";if(!Dt[ft]&&!Qe.length&&(ft=Object.keys(Dt)[0]),!Dt[ft])throw new Error("interpolation mode "+ft+" is not defined");return Mt(Te)!=="object"&&(Te=new Tt(Te)),Mt(De)!=="object"&&(De=new Tt(De)),Dt[ft](Te,De,We).alpha(Te.alpha()+We*(De.alpha()-Te.alpha()))},Wr=ue,fi=br;Wr.prototype.mix=Wr.prototype.interpolate=function(Te,De){De===void 0&&(De=.5);for(var We=[],Qe=arguments.length-2;Qe-- >0;)We[Qe]=arguments[Qe+2];return fi.apply(void 0,[this,Te,De].concat(We))};var Or=ue;Or.prototype.premultiply=function(Te){Te===void 0&&(Te=!1);var De=this._rgb,We=De[3];return Te?(this._rgb=[De[0]*We,De[1]*We,De[2]*We,We],this):new Or([De[0]*We,De[1]*We,De[2]*We,We],"rgb")};var Wn=ue,Jo=Ot;Wn.prototype.saturate=function(Te){Te===void 0&&(Te=1);var De=this,We=De.lch();return We[1]+=Jo.Kn*Te,We[1]<0&&(We[1]=0),new Wn(We,"lch").alpha(De.alpha(),!0)},Wn.prototype.desaturate=function(Te){return Te===void 0&&(Te=1),this.saturate(-Te)};var Zs=ue,Qs=T.type;Zs.prototype.set=function(Te,De,We){We===void 0&&(We=!1);var Qe=Te.split("."),ht=Qe[0],ft=Qe[1],ct=this[ht]();if(ft){var pt=ht.indexOf(ft)-(ht.substr(0,2)==="ok"?2:0);if(pt>-1){if(Qs(De)=="string")switch(De.charAt(0)){case"+":ct[pt]+=+De;break;case"-":ct[pt]+=+De;break;case"*":ct[pt]*=+De.substr(1);break;case"/":ct[pt]/=+De.substr(1);break;default:ct[pt]=+De}else if(Qs(De)==="number")ct[pt]=De;else throw new Error("unsupported value for Color.set");var gt=new Zs(ct,ht);return We?(this._rgb=gt._rgb,this):gt}throw new Error("unknown channel "+ft+" in mode "+ht)}else return ct};var Js=ue,ea=function(Te,De,We){var Qe=Te._rgb,ht=De._rgb;return new Js(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"rgb")};_t.rgb=ea;var eo=ue,sr=Math.sqrt,Dr=Math.pow,ta=function(Te,De,We){var Qe=Te._rgb,ht=Qe[0],ft=Qe[1],ct=Qe[2],pt=De._rgb,gt=pt[0],vt=pt[1],bt=pt[2];return new eo(sr(Dr(ht,2)*(1-We)+Dr(gt,2)*We),sr(Dr(ft,2)*(1-We)+Dr(vt,2)*We),sr(Dr(ct,2)*(1-We)+Dr(bt,2)*We),"rgb")};_t.lrgb=ta;var ra=ue,na=function(Te,De,We){var Qe=Te.lab(),ht=De.lab();return new ra(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"lab")};_t.lab=na;var di=ue,an=function(Te,De,We,Qe){var ht,ft,ct,pt;Qe==="hsl"?(ct=Te.hsl(),pt=De.hsl()):Qe==="hsv"?(ct=Te.hsv(),pt=De.hsv()):Qe==="hcg"?(ct=Te.hcg(),pt=De.hcg()):Qe==="hsi"?(ct=Te.hsi(),pt=De.hsi()):Qe==="lch"||Qe==="hcl"?(Qe="hcl",ct=Te.hcl(),pt=De.hcl()):Qe==="oklch"&&(ct=Te.oklch().reverse(),pt=De.oklch().reverse());var gt,vt,bt,At,wt,It;(Qe.substr(0,1)==="h"||Qe==="oklch")&&(ht=ct,gt=ht[0],bt=ht[1],wt=ht[2],ft=pt,vt=ft[0],At=ft[1],It=ft[2]);var Pt,Bt,Ht,jt;return!isNaN(gt)&&!isNaN(vt)?(vt>gt&&vt-gt>180?jt=vt-(gt+360):vt180?jt=vt+360-gt:jt=vt-gt,Bt=gt+We*jt):isNaN(gt)?isNaN(vt)?Bt=Number.NaN:(Bt=vt,(wt==1||wt==0)&&Qe!="hsv"&&(Pt=At)):(Bt=gt,(It==1||It==0)&&Qe!="hsv"&&(Pt=bt)),Pt===void 0&&(Pt=bt+We*(At-bt)),Ht=wt+We*(It-wt),Qe==="oklch"?new di([Ht,Pt,Bt],Qe):new di([Bt,Pt,Ht],Qe)},ia=an,xa=function(Te,De,We){return ia(Te,De,We,"lch")};_t.lch=xa,_t.hcl=xa;var Wa=ue,ja=function(Te,De,We){var Qe=Te.num(),ht=De.num();return new Wa(Qe+We*(ht-Qe),"num")};_t.num=ja;var Ya=an,Ka=function(Te,De,We){return Ya(Te,De,We,"hcg")};_t.hcg=Ka;var Ga=an,qa=function(Te,De,We){return Ga(Te,De,We,"hsi")};_t.hsi=qa;var Xa=an,Za=function(Te,De,We){return Xa(Te,De,We,"hsl")};_t.hsl=Za;var Qa=an,Ja=function(Te,De,We){return Qa(Te,De,We,"hsv")};_t.hsv=Ja;var el=ue,tl=function(Te,De,We){var Qe=Te.oklab(),ht=De.oklab();return new el(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"oklab")};_t.oklab=tl;var rl=an,nl=function(Te,De,We){return rl(Te,De,We,"oklch")};_t.oklch=nl;var sa=ue,il=T.clip_rgb,oa=Math.pow,aa=Math.sqrt,la=Math.PI,Ea=Math.cos,Sa=Math.sin,sl=Math.atan2,ol=function(Te,De,We){De===void 0&&(De="lrgb"),We===void 0&&(We=null);var Qe=Te.length;We||(We=Array.from(new Array(Qe)).map(function(){return 1}));var ht=Qe/We.reduce(function(Bt,Ht){return Bt+Ht});if(We.forEach(function(Bt,Ht){We[Ht]*=ht}),Te=Te.map(function(Bt){return new sa(Bt)}),De==="lrgb")return al(Te,We);for(var ft=Te.shift(),ct=ft.get(De),pt=[],gt=0,vt=0,bt=0;bt=360;)Pt-=360;ct[It]=Pt}else ct[It]=ct[It]/pt[It];return wt/=Qe,new sa(ct,De).alpha(wt>.99999?1:wt,!0)},al=function(Te,De){for(var We=Te.length,Qe=[0,0,0,0],ht=0;ht.9999999&&(Qe[3]=1),new sa(il(Qe))},Nr=le,pi=T.type,ll=Math.pow,ca=function(Te){var De="rgb",We=Nr("#ccc"),Qe=0,ht=[0,1],ft=[],ct=[0,0],pt=!1,gt=[],vt=!1,bt=0,At=1,wt=!1,It={},Pt=!0,Bt=1,Ht=function(xt){if(xt=xt||["#fff","#000"],xt&&pi(xt)==="string"&&Nr.brewer&&Nr.brewer[xt.toLowerCase()]&&(xt=Nr.brewer[xt.toLowerCase()]),pi(xt)==="array"){xt.length===1&&(xt=[xt[0],xt[0]]),xt=xt.slice(0);for(var Rt=0;Rt=pt[Ut];)Ut++;return Ut-1}return 0},Kt=function(xt){return xt},gr=function(xt){return xt},fr=function(xt,Rt){var Ut,Ft;if(Rt==null&&(Rt=!1),isNaN(xt)||xt===null)return We;if(Rt)Ft=xt;else if(pt&&pt.length>2){var yr=jt(xt);Ft=yr/(pt.length-2)}else At!==bt?Ft=(xt-bt)/(At-bt):Ft=1;Ft=gr(Ft),Rt||(Ft=Kt(Ft)),Bt!==1&&(Ft=ll(Ft,Bt)),Ft=ct[0]+Ft*(1-ct[0]-ct[1]),Ft=Math.min(1,Math.max(0,Ft));var er=Math.floor(Ft*1e4);if(Pt&&It[er])Ut=It[er];else{if(pi(gt)==="array")for(var Yt=0;Yt=Gt&&Yt===ft.length-1){Ut=gt[Yt];break}if(Ft>Gt&&Ft2){var Yt=xt.map(function(qt,Zt){return Zt/(xt.length-1)}),Gt=xt.map(function(qt){return(qt-bt)/(At-bt)});Gt.every(function(qt,Zt){return Yt[Zt]===qt})||(gr=function(qt){if(qt<=0||qt>=1)return qt;for(var Zt=0;qt>=Gt[Zt+1];)Zt++;var Fr=(qt-Gt[Zt])/(Gt[Zt+1]-Gt[Zt]),_n=Yt[Zt]+Fr*(Yt[Zt+1]-Yt[Zt]);return _n})}}return ht=[bt,At],zt},zt.mode=function(xt){return arguments.length?(De=xt,Sr(),zt):De},zt.range=function(xt,Rt){return Ht(xt),zt},zt.out=function(xt){return vt=xt,zt},zt.spread=function(xt){return arguments.length?(Qe=xt,zt):Qe},zt.correctLightness=function(xt){return xt==null&&(xt=!0),wt=xt,Sr(),wt?Kt=function(Rt){for(var Ut=fr(0,!0).lab()[0],Ft=fr(1,!0).lab()[0],yr=Ut>Ft,er=fr(Rt,!0).lab()[0],Yt=Ut+(Ft-Ut)*Rt,Gt=er-Yt,qt=0,Zt=1,Fr=20;Math.abs(Gt)>.01&&Fr-- >0;)(function(){return yr&&(Gt*=-1),Gt<0?(qt=Rt,Rt+=(Zt-Rt)*.5):(Zt=Rt,Rt+=(qt-Rt)*.5),er=fr(Rt,!0).lab()[0],Gt=er-Yt})();return Rt}:Kt=function(Rt){return Rt},zt},zt.padding=function(xt){return xt!=null?(pi(xt)==="number"&&(xt=[xt,xt]),ct=xt,zt):ct},zt.colors=function(xt,Rt){arguments.length<2&&(Rt="hex");var Ut=[];if(arguments.length===0)Ut=gt.slice(0);else if(xt===1)Ut=[zt(.5)];else if(xt>1){var Ft=ht[0],yr=ht[1]-Ft;Ut=cl(0,xt,!1).map(function(Zt){return zt(Ft+Zt/(xt-1)*yr)})}else{Te=[];var er=[];if(pt&&pt.length>2)for(var Yt=1,Gt=pt.length,qt=1<=Gt;qt?YtGt;qt?Yt++:Yt--)er.push((pt[Yt-1]+pt[Yt])*.5);else er=ht;Ut=er.map(function(Zt){return zt(Zt)})}return Nr[Rt]&&(Ut=Ut.map(function(Zt){return Zt[Rt]()})),Ut},zt.cache=function(xt){return xt!=null?(Pt=xt,zt):Pt},zt.gamma=function(xt){return xt!=null?(Bt=xt,zt):Bt},zt.nodata=function(xt){return xt!=null?(We=Nr(xt),zt):We},zt};function cl(Te,De,We){for(var Qe=[],ht=Teft;ht?ct++:ct--)Qe.push(ct);return Qe}var Xi=ue,ul=ca,hl=function(Te){for(var De=[1,1],We=1;We=5){var vt,bt,At;vt=Te.map(function(wt){return wt.lab()}),At=Te.length-1,bt=hl(At),ht=function(wt){var It=1-wt,Pt=[0,1,2].map(function(Bt){return vt.reduce(function(Ht,jt,Kt){return Ht+bt[Kt]*Math.pow(It,At-Kt)*Math.pow(wt,Kt)*jt[Bt]},0)});return new Xi(Pt,"lab")}}else throw new RangeError("No point in running bezier with only one color.");return ht},dl=function(Te){var De=fl(Te);return De.scale=function(){return ul(De)},De},ua=le,Br=function(Te,De,We){if(!Br[We])throw new Error("unknown blend mode "+We);return Br[We](Te,De)},yn=function(Te){return function(De,We){var Qe=ua(We).rgb(),ht=ua(De).rgb();return ua.rgb(Te(Qe,ht))}},vn=function(Te){return function(De,We){var Qe=[];return Qe[0]=Te(De[0],We[0]),Qe[1]=Te(De[1],We[1]),Qe[2]=Te(De[2],We[2]),Qe}},pl=function(Te){return Te},ml=function(Te,De){return Te*De/255},gl=function(Te,De){return Te>De?De:Te},yl=function(Te,De){return Te>De?Te:De},vl=function(Te,De){return 255*(1-(1-Te/255)*(1-De/255))},_l=function(Te,De){return De<128?2*Te*De/255:255*(1-2*(1-Te/255)*(1-De/255))},bl=function(Te,De){return 255*(1-(1-De/255)/(Te/255))},wl=function(Te,De){return Te===255?255:(Te=255*(De/255)/(1-Te/255),Te>255?255:Te)};Br.normal=yn(vn(pl)),Br.multiply=yn(vn(ml)),Br.screen=yn(vn(vl)),Br.overlay=yn(vn(_l)),Br.darken=yn(vn(gl)),Br.lighten=yn(vn(yl)),Br.dodge=yn(vn(wl)),Br.burn=yn(vn(bl));for(var xl=Br,ha=T.type,El=T.clip_rgb,Sl=T.TWOPI,Cl=Math.pow,kl=Math.sin,Tl=Math.cos,Ca=le,Al=function(Te,De,We,Qe,ht){Te===void 0&&(Te=300),De===void 0&&(De=-1.5),We===void 0&&(We=1),Qe===void 0&&(Qe=1),ht===void 0&&(ht=[0,1]);var ft=0,ct;ha(ht)==="array"?ct=ht[1]-ht[0]:(ct=0,ht=[ht,ht]);var pt=function(gt){var vt=Sl*((Te+120)/360+De*gt),bt=Cl(ht[0]+ct*gt,Qe),At=ft!==0?We[0]+gt*ft:We,wt=At*bt*(1-bt)/2,It=Tl(vt),Pt=kl(vt),Bt=bt+wt*(-.14861*It+1.78277*Pt),Ht=bt+wt*(-.29227*It-.90649*Pt),jt=bt+wt*(1.97294*It);return Ca(El([Bt*255,Ht*255,jt*255,1]))};return pt.start=function(gt){return gt==null?Te:(Te=gt,pt)},pt.rotations=function(gt){return gt==null?De:(De=gt,pt)},pt.gamma=function(gt){return gt==null?Qe:(Qe=gt,pt)},pt.hue=function(gt){return gt==null?We:(We=gt,ha(We)==="array"?(ft=We[1]-We[0],ft===0&&(We=We[1])):ft=0,pt)},pt.lightness=function(gt){return gt==null?ht:(ha(gt)==="array"?(ht=gt,ct=gt[1]-gt[0]):(ht=[gt,gt],ct=0),pt)},pt.scale=function(){return Ca.scale(pt)},pt.hue(We),pt},Pl=ue,Il="0123456789abcdef",$l=Math.floor,Ll=Math.random,Rl=function(){for(var Te="#",De=0;De<6;De++)Te+=Il.charAt($l(Ll()*16));return new Pl(Te,"hex")},fa=_,ka=Math.log,Ml=Math.pow,Ol=Math.floor,Dl=Math.abs,Ta=function(Te,De){De===void 0&&(De=null);var We={min:Number.MAX_VALUE,max:Number.MAX_VALUE*-1,sum:0,values:[],count:0};return fa(Te)==="object"&&(Te=Object.values(Te)),Te.forEach(function(Qe){De&&fa(Qe)==="object"&&(Qe=Qe[De]),Qe!=null&&!isNaN(Qe)&&(We.values.push(Qe),We.sum+=Qe,QeWe.max&&(We.max=Qe),We.count+=1)}),We.domain=[We.min,We.max],We.limits=function(Qe,ht){return Aa(We,Qe,ht)},We},Aa=function(Te,De,We){De===void 0&&(De="equal"),We===void 0&&(We=7),fa(Te)=="array"&&(Te=Ta(Te));var Qe=Te.min,ht=Te.max,ft=Te.values.sort(function(pa,ma){return pa-ma});if(We===1)return[Qe,ht];var ct=[];if(De.substr(0,1)==="c"&&(ct.push(Qe),ct.push(ht)),De.substr(0,1)==="e"){ct.push(Qe);for(var pt=1;pt 0");var gt=Math.LOG10E*ka(Qe),vt=Math.LOG10E*ka(ht);ct.push(Qe);for(var bt=1;bt200&&(gr=!1)}for(var bn={},mi=0;miQe?(We+.05)/(Qe+.05):(Qe+.05)/(We+.05)},$a=ue,ln=Math.sqrt,cr=Math.pow,Bl=Math.min,Fl=Math.max,La=Math.atan2,Ra=Math.abs,ro=Math.cos,Ma=Math.sin,Ul=Math.exp,Oa=Math.PI,Vl=function(Te,De,We,Qe,ht){We===void 0&&(We=1),Qe===void 0&&(Qe=1),ht===void 0&&(ht=1);var ft=function(Yn){return 360*Yn/(2*Oa)},ct=function(Yn){return 2*Oa*Yn/360};Te=new $a(Te),De=new $a(De);var pt=Array.from(Te.lab()),gt=pt[0],vt=pt[1],bt=pt[2],At=Array.from(De.lab()),wt=At[0],It=At[1],Pt=At[2],Bt=(gt+wt)/2,Ht=ln(cr(vt,2)+cr(bt,2)),jt=ln(cr(It,2)+cr(Pt,2)),Kt=(Ht+jt)/2,gr=.5*(1-ln(cr(Kt,7)/(cr(Kt,7)+cr(25,7)))),fr=vt*(1+gr),Sr=It*(1+gr),zt=ln(cr(fr,2)+cr(bt,2)),xt=ln(cr(Sr,2)+cr(Pt,2)),Rt=(zt+xt)/2,Ut=ft(La(bt,fr)),Ft=ft(La(Pt,Sr)),yr=Ut>=0?Ut:Ut+360,er=Ft>=0?Ft:Ft+360,Yt=Ra(yr-er)>180?(yr+er+360)/2:(yr+er)/2,Gt=1-.17*ro(ct(Yt-30))+.24*ro(ct(2*Yt))+.32*ro(ct(3*Yt+6))-.2*ro(ct(4*Yt-63)),qt=er-yr;qt=Ra(qt)<=180?qt:er<=yr?qt+360:qt-360,qt=2*ln(zt*xt)*Ma(ct(qt)/2);var Zt=wt-gt,Fr=xt-zt,_n=1+.015*cr(Bt-50,2)/ln(20+cr(Bt-50,2)),bn=1+.045*Rt,mi=1+.015*Rt*Gt,gi=30*Ul(-cr((Yt-275)/25,2)),cn=2*ln(cr(Rt,7)/(cr(Rt,7)+cr(25,7))),jn=-cn*Ma(2*ct(gi)),Zi=ln(cr(Zt/(We*_n),2)+cr(Fr/(Qe*bn),2)+cr(qt/(ht*mi),2)+jn*(Fr/(Qe*bn))*(qt/(ht*mi)));return Fl(0,Bl(100,Zi))},Da=ue,Hl=function(Te,De,We){We===void 0&&(We="lab"),Te=new Da(Te),De=new Da(De);var Qe=Te.get(We),ht=De.get(We),ft=0;for(var ct in Qe){var pt=(Qe[ct]||0)-(ht[ct]||0);ft+=pt*pt}return Math.sqrt(ft)},zl=ue,Wl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];try{return new(Function.prototype.bind.apply(zl,[null].concat(Te))),!0}catch{return!1}},Na=le,Ba=ca,jl={cool:function(){return Ba([Na.hsl(180,1,.9),Na.hsl(250,.7,.4)])},hot:function(){return Ba(["#000","#f00","#ff0","#fff"]).mode("rgb")}},no={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},da=0,Fa=Object.keys(no);dal===o);if(r[a])return r[a]}return r[r.length-1]}const markerIcon2x="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAMAAAAhFXfZAAAC91BMVEVMaXEzeak2f7I4g7g3g7cua5gzeKg8hJo3grY4g7c3grU0gLI2frE0daAubJc2gbQwd6QzeKk2gLMtd5sxdKIua5g1frA2f7IydaM0e6w2fq41fK01eqo3grgubJgta5cxdKI1f7AydaQydaMxc6EubJgvbJkwcZ4ubZkwcJwubZgubJcydqUydKIxapgubJctbJcubZcubJcvbJYubJcvbZkubJctbJctbZcubJg2f7AubJcrbZcubJcubJcua5g3grY0fq8ubJcubJdEkdEwhsw6i88vhswuhcsuhMtBjMgthMsrg8srgss6is8qgcs8i9A9iMYtg8spgcoogMo7hcMngMonf8olfso4gr8kfck5iM8jfMk4iM8he8k1fro7itAgesk2hs8eecgzfLcofssdeMg0hc4cd8g2hcsxeLQbdsgZdcgxeLImfcszhM0vda4xgckzhM4xg84wf8Yxgs4udKsvfcQucqhUndROmdM1fK0wcZ8vb5w0eqpQm9MzeKhXoNVcpdYydKNWn9VZotVKltJFjsIwcJ1Rms9OlslLmtH///8+kc9epdYzd6dbo9VHkMM2f7FHmNBClM8ydqVcpNY9hro3gLM9hLczealQmcw3fa46f7A8gLMxc6I3eagyc6FIldJMl9JSnNRSntNNl9JPnNJFi75UnM9ZodVKksg8kM45jc09e6ZHltFBk883gbRBh7pDk9EwcaBzn784g7dKkcY2i81Om9M7j85Llc81is09g7Q4grY/j9A0eqxKmdFFltBEjcXf6fFImdBCiLxJl9FGlNFBi78yiMxVndEvbpo6js74+vx+psPP3+o/ks5HkcpGmNCjwdZCkNDM3ehYoNJEls+lxNkxh8xHks0+jdC1zd5Lg6r+/v/H2ufz9/o3jM3t8/edvdM/k89Th61OiLBSjbZklbaTt9BfptdjmL1AicBHj8hGk9FAgK1dkLNTjLRekrdClc/k7fM0icy0y9tgp9c4jc2NtM9Dlc8zicxeXZn3AAAAQ3RSTlMAHDdTb4yPA+LtnEQmC4L2EmHqB7XA0d0sr478x4/Yd5i1zOfyPkf1sLVq4Nh3FvjxopQ2/STNuFzUwFIwxKaejILpIBEV9wAABhVJREFUeF6s1NdyFEcYBeBeoQIhRAkLlRDGrhIgY3BJL8CVeKzuyXFzzjkn5ZxzzuScg3PO8cKzu70JkO0LfxdTU//pM9vTu7Xgf6KqOVTb9X7toRrVEfBf1HTVjZccrT/2by1VV928Yty9ZbVuucdz90frG8DBjl9pVApbOstvmMuvVgaNXSfAAd6pGxpy6yxf5ph43pS/4f3uoaGm2rdu72S9xzOvMymkZFq/ptDrk90mhW7e4zl7HLzhxGWPR20xmSxJ/VqldG5m9XhaVOA1DadsNh3Pu5L2N6QtPO/32JpqQBVVk20oy/Pi2s23WEvyfHbe1thadVQttvm7Llf65gGmXK67XtupyoM7HQhmXdLS8oGWJNeOJ3C5fG5XCEJnkez3/oFdsvgJ4l2ANZwhrJKk/7OSXa+3Vw2WJMlKnGkobouYk6T0TyX30klOUnTD9HJ5qpckL3EW/w4XF3Xd0FGywXUrstrclVsqz5Pd/sXFYyDnPdrLcQODmGOK47IZb4CmibmMn+MYRzFZ5jg33ZL/EJrWcszHmANy3ARBK/IXtciJy8VsitPSdE3uuHxzougojcUdr8/32atnz/ev3f/K5wtpxUTpcaI45zusVDpYtZi+jg0oU9b3x74h7+n9ABvYEZeKaVq0sh0AtLKsFtqNBdeT0MrSzwwlq9+x6xAO4tgOtSzbCjrNQQiNvQUbUEubvzBUeGw26yDCsRHCoLkTHDa7IdOLIThs/gHvChszh2CimE8peRs47cxANI0lYNB5y1DljpOF0IhzBDPOZnDOqYYbeGKECbPzWnXludPphw5c2YBq5zlwXphIbO4VDCZ0gnPfUO1TwZoYwAs2ExPCedAu9DAjfQUjzITQb3jNj0KG2Sgt6BHaQUdYzWz+XmBktOHwanXjaSTcwwziBcuMOtwBmqPrTOxFQR/DRKKPqyur0aiW6cULYsx6tBm0jXpR/AUWR6HRq9WVW6MRhIq5jLyjbaCTDCijyYJNpCajdyobP/eTw0iexBAKkJ3gA5KcQb2zBXsIBckn+xVv8jkZSaEFHE+jFEleAEfayRU0MouNoBmB/L50Ai/HSLIHxcrpCvnhSQAuakKp2C/YbCylJjXRVy/z3+Kv/RrNcCo+WUzlVEhzKffnTQnxeN9fWF88fiNCUdSTsaufaChKWInHeysygfpIqagoakW+vV20J8uyl6TyNKEZWV4oRSPyCkWpgOLSbkCObT8o2r6tlG58HQquf6O0v50tB7JM7F4EORd2dx/K0w/KHsVkLPaoYrwgP/y7krr3SSMA4zj+OBgmjYkxcdIJQyQRKgg2viX9Hddi9UBb29LrKR7CVVEEEXWojUkXNyfTNDE14W9gbHJNuhjDettN3ZvbOvdOqCD3Jp/9l+/wJE+9PkYGjx/fqkys3S2rMozM/o2106rfMUINo6hVqz+eu/hd1c4xTg0TAfy5kV+4UG6+IthHTU9woWmxuKNbTfuCSfovBCxq7EtHqvYL4Sm6F8GVxsSXHMQ07TOi1DKtZxjWaaIyi4CXWjxPccUw8WVbMYY5wxC1mzEyXMJWkllpRloi+Kkoq69sxBTlElF6aAxYUbjXNlhlDZilDnM4U5SlN5biRsRHnbx3mbeWjEh4mEyiuJDl5XcWVmX5GvNkFgLWZM5qwsop4/AWfLhU1cR7k1VVvcYCWRkOI6Xy5gmnphCYIkvzuNYzHzosq2oNk2RtSs8khfUOfHIDgR6ysYBaMpl4uEgk2U/oJTs9AaTSwma7dT69geAE2ZpEjUsn2ieJNHeKfrI3EcAGJ2ZaNgVuC8EBctCLc57P5u5led6IOBkIYkuQMrmmjChs4VkfOerHqSBkPzZlhe06RslZ3zMjk2sscqKwY0RcjKK+LWbzd7KiHhkncs/siFJ+V5eXxD34B8nVuJEpGJNmxN2gH3vSvp7J70tF+D1Ej8qUJD1TkErAND2GZwTFg/LubvmgiBG3SOvdlsqFQrkEzJCL1rstlnVFROixZoDDSuXQFHESwVGlcuQcMb/b42NgjLowh5MTDFE3vNB5qStRIErdCQEh6pLPR92anSUb/wAIhldAaDMpGgAAAABJRU5ErkJggg==",markerIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=",markerShadow="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAQAAAACach9AAACMUlEQVR4Ae3ShY7jQBAE0Aoz/f9/HTMzhg1zrdKUrJbdx+Kd2nD8VNudfsL/Th///dyQN2TH6f3y/BGpC379rV+S+qqetBOxImNQXL8JCAr2V4iMQXHGNJxeCfZXhSRBcQMfvkOWUdtfzlLgAENmZDcmo2TVmt8OSM2eXxBp3DjHSMFutqS7SbmemzBiR+xpKCNUIRkdkkYxhAkyGoBvyQFEJEefwSmmvBfJuJ6aKqKWnAkvGZOaZXTUgFqYULWNSHUckZuR1HIIimUExutRxwzOLROIG4vKmCKQt364mIlhSyzAf1m9lHZHJZrlAOMMztRRiKimp/rpdJDc9Awry5xTZCte7FHtuS8wJgeYGrex28xNTd086Dik7vUMscQOa8y4DoGtCCSkAKlNwpgNtphjrC6MIHUkR6YWxxs6Sc5xqn222mmCRFzIt8lEdKx+ikCtg91qS2WpwVfBelJCiQJwvzixfI9cxZQWgiSJelKnwBElKYtDOb2MFbhmUigbReQBV0Cg4+qMXSxXSyGUn4UbF8l+7qdSGnTC0XLCmahIgUHLhLOhpVCtw4CzYXvLQWQbJNmxoCsOKAxSgBJno75avolkRw8iIAFcsdc02e9iyCd8tHwmeSSoKTowIgvscSGZUOA7PuCN5b2BX9mQM7S0wYhMNU74zgsPBj3HU7wguAfnxxjFQGBE6pwN+GjME9zHY7zGp8wVxMShYX9NXvEWD3HbwJf4giO4CFIQxXScH1/TM+04kkBiAAAAAElFTkSuQmCC",queue=new queue$1;let scale,markersLayer,pathsLayer,moveLayer,handlerClickMarker;delete L$2.Icon.Default.prototype._getIconUrl;L$2.Icon.Default.mergeOptions({iconRetinaUrl:markerIcon2x,iconUrl:markerIcon,shadowUrl:markerShadow});const messageTypes={0:"text",1:"air",2:"garbage",3:"water",4:"fire",5:"forest",6:"alert ",7:"notif",8:"recycle",9:"parking",42:"gank"};let messageIconName={},messageIconType={};const messagesLayers=Object.values(messageTypes).reduce((e,t)=>(e[t]=null,e),{});async function init$2(e,t,r){for(const o of Object.keys(messageTypes)){try{messageIconType[o]=(await __variableDynamicImportRuntimeHelper(Object.assign({"../../assets/message/msg-air.png":()=>__vitePreload(()=>import("./msg-air.abb754d3.js"),[]),"../../assets/message/msg-alert.png":()=>__vitePreload(()=>import("./msg-alert.9404c396.js"),[]),"../../assets/message/msg-fire.png":()=>__vitePreload(()=>import("./msg-fire.faa011b0.js"),[]),"../../assets/message/msg-forest.png":()=>__vitePreload(()=>import("./msg-forest.a623a1f9.js"),[]),"../../assets/message/msg-gank.png":()=>__vitePreload(()=>import("./msg-gank.34a748fe.js"),[]),"../../assets/message/msg-garbage.png":()=>__vitePreload(()=>import("./msg-garbage.b797b882.js"),[]),"../../assets/message/msg-notif.png":()=>__vitePreload(()=>import("./msg-notif.d72c5a6f.js"),[]),"../../assets/message/msg-parking.png":()=>__vitePreload(()=>import("./msg-parking.5da4fdeb.js"),[]),"../../assets/message/msg-recycle.png":()=>__vitePreload(()=>import("./msg-recycle.eab79c00.js"),[]),"../../assets/message/msg-text.png":()=>__vitePreload(()=>import("./msg-text.470fee8d.js"),[]),"../../assets/message/msg-water.png":()=>__vitePreload(()=>import("./msg-water.b0066085.js"),[])}),`../../assets/message/msg-${messageTypes[o]}.png`)).default}catch{messageIconType[o]=(await __vitePreload(()=>import("./msg-text.470fee8d.js"),[])).default}messageIconName[messageTypes[o]]=messageIconType[o]}handlerClickMarker=o=>{/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?e.setActiveArea({position:"absolute",top:"90px",left:"0px",right:"0px",height:"20%"}):e.setActiveArea({position:"absolute",top:"0px",left:"0px",right:"50%",height:"100%"}),e.panTo(o.latlng),r(o.target.options.data)};const n=getMeasurementByName(t);scale=generate$1(n.colors,n.range),markersLayer=new L$2.MarkerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:120,iconCreateFunction:iconCreate}),e.addLayer(markersLayer),pathsLayer=new L$2.layerGroup,e.addLayer(pathsLayer),moveLayer=new L$2.layerGroup,e.addLayer(moveLayer);for(const o of Object.values(messageTypes))messagesLayers[o]=new L$2.MarkerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:120,iconCreateFunction:a=>iconCreateMsg(a,o)});for(const o of Object.values(messagesLayers))e.addLayer(o)}function isReadyLayers(){return!!(markersLayer&&pathsLayer&&moveLayer)}function iconCreate(e){const t=e.getAllChildMarkers(),r=e.getChildCount();let n=0,o=0;t.forEach(u=>{u.options.data.value===void 0&&u.options.data.value!==""||(n++,o+=Number(u.options.data.value))}),n>0&&(o=o/n);const a=getColorRGB(scale,o),l=getColorDarkenRGB(scale,o),c=scale(o).luminance()<.4;return new L$2.DivIcon({html:`
${r}
`,className:"marker-cluster",iconSize:new L$2.Point(40,40)})}function iconCreateMsg(e,t="text"){const r=e.getChildCount();return new L$2.DivIcon({html:`
${r}
`,className:"marker-cluster",iconSize:new L$2.Point(40,40)})}function findMarker(e){return new Promise(t=>{markersLayer&&markersLayer.eachLayer(r=>{r.options.data.sensor_id===e&&t(r)}),t(!1)})}function findMarkerMoved(e){return new Promise(t=>{moveLayer&&moveLayer.eachLayer(r=>{r.options.data.sensor_id===e&&t(r)}),t(!1)})}function createIconBrand(e,t){return L$2.divIcon({html:``,iconSize:[40,40],className:"marker-icon"})}function createIconMsg(e=0){return L$2.divIcon({html:``,iconSize:[40,40],className:"marker-icon"})}function createIconArrow(e,t,r){return L$2.divIcon({className:"",html:`
+ */(function(e,t){(function(r,n){e.exports=n()})(commonjsGlobal$2,function(){for(var r=function(Te,De,We){return De===void 0&&(De=0),We===void 0&&(We=1),TeWe?We:Te},n=r,o=function(Te){Te._clipped=!1,Te._unclipped=Te.slice(0);for(var De=0;De<=3;De++)De<3?((Te[De]<0||Te[De]>255)&&(Te._clipped=!0),Te[De]=n(Te[De],0,255)):De===3&&(Te[De]=n(Te[De],0,1));return Te},a={},l=0,c=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"];l=3?Array.prototype.slice.call(Te):b(Te[0])=="object"&&De?De.split("").filter(function(We){return Te[0][We]!==void 0}).map(function(We){return Te[0][We]}):Te[0]},E=_,I=function(Te){if(Te.length<2)return null;var De=Te.length-1;return E(Te[De])=="string"?Te[De].toLowerCase():null},k=Math.PI,T={clip_rgb:o,limit:r,type:_,unpack:x,last:I,PI:k,TWOPI:k*2,PITHIRD:k/3,DEG2RAD:k/180,RAD2DEG:180/k},O={format:{},autodetect:[]},$=T.last,D=T.clip_rgb,N=T.type,H=O,ie=function(){for(var De=[],We=arguments.length;We--;)De[We]=arguments[We];var Qe=this;if(N(De[0])==="object"&&De[0].constructor&&De[0].constructor===this.constructor)return De[0];var ht=$(De),ft=!1;if(!ht){ft=!0,H.sorted||(H.autodetect=H.autodetect.sort(function(bt,At){return At.p-bt.p}),H.sorted=!0);for(var ct=0,pt=H.autodetect;ct4?Te[4]:1;return ft===1?[0,0,0,ct]:[We>=1?0:255*(1-We)*(1-ft),Qe>=1?0:255*(1-Qe)*(1-ft),ht>=1?0:255*(1-ht)*(1-ft),ct]},te=xe,ae=le,ge=ue,se=O,Se=T.unpack,Pe=T.type,Ue=he;ge.prototype.cmyk=function(){return Ue(this._rgb)},ae.cmyk=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(ge,[null].concat(Te,["cmyk"])))},se.format.cmyk=te,se.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Se(Te,"cmyk"),Pe(Te)==="array"&&Te.length===4)return"cmyk"}});var Be=T.unpack,fe=T.last,ye=function(Te){return Math.round(Te*100)/100},Ce=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Be(Te,"hsla"),Qe=fe(Te)||"lsa";return We[0]=ye(We[0]||0),We[1]=ye(We[1]*100)+"%",We[2]=ye(We[2]*100)+"%",Qe==="hsla"||We.length>3&&We[3]<1?(We[3]=We.length>3?We[3]:1,Qe="hsla"):We.length=3,Qe+"("+We.join(",")+")"},Le=Ce,Fe=T.unpack,Oe=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Fe(Te,"rgba");var We=Te[0],Qe=Te[1],ht=Te[2];We/=255,Qe/=255,ht/=255;var ft=Math.min(We,Qe,ht),ct=Math.max(We,Qe,ht),pt=(ct+ft)/2,gt,vt;return ct===ft?(gt=0,vt=Number.NaN):gt=pt<.5?(ct-ft)/(ct+ft):(ct-ft)/(2-ct-ft),We==ct?vt=(Qe-ht)/(ct-ft):Qe==ct?vt=2+(ht-We)/(ct-ft):ht==ct&&(vt=4+(We-Qe)/(ct-ft)),vt*=60,vt<0&&(vt+=360),Te.length>3&&Te[3]!==void 0?[vt,gt,pt,Te[3]]:[vt,gt,pt]},be=Oe,Re=T.unpack,Ie=T.last,we=Le,oe=be,pe=Math.round,ke=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Re(Te,"rgba"),Qe=Ie(Te)||"rgb";return Qe.substr(0,3)=="hsl"?we(oe(We),Qe):(We[0]=pe(We[0]),We[1]=pe(We[1]),We[2]=pe(We[2]),(Qe==="rgba"||We.length>3&&We[3]<1)&&(We[3]=We.length>3?We[3]:1,Qe="rgba"),Qe+"("+We.slice(0,Qe==="rgb"?3:4).join(",")+")")},Ne=ke,ze=T.unpack,Xe=Math.round,Je=function(){for(var Te,De=[],We=arguments.length;We--;)De[We]=arguments[We];De=ze(De,"hsl");var Qe=De[0],ht=De[1],ft=De[2],ct,pt,gt;if(ht===0)ct=pt=gt=ft*255;else{var vt=[0,0,0],bt=[0,0,0],At=ft<.5?ft*(1+ht):ft+ht-ft*ht,wt=2*ft-At,It=Qe/360;vt[0]=It+1/3,vt[1]=It,vt[2]=It-1/3;for(var Pt=0;Pt<3;Pt++)vt[Pt]<0&&(vt[Pt]+=1),vt[Pt]>1&&(vt[Pt]-=1),6*vt[Pt]<1?bt[Pt]=wt+(At-wt)*6*vt[Pt]:2*vt[Pt]<1?bt[Pt]=At:3*vt[Pt]<2?bt[Pt]=wt+(At-wt)*(2/3-vt[Pt])*6:bt[Pt]=wt;Te=[Xe(bt[0]*255),Xe(bt[1]*255),Xe(bt[2]*255)],ct=Te[0],pt=Te[1],gt=Te[2]}return De.length>3?[ct,pt,gt,De[3]]:[ct,pt,gt,1]},rt=Je,qe=rt,Ve=O,Ae=/^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/,He=/^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/,Ge=/^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,Ze=/^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,$e=/^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,me=/^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,Ee=Math.round,je=function(Te){Te=Te.toLowerCase().trim();var De;if(Ve.format.named)try{return Ve.format.named(Te)}catch{}if(De=Te.match(Ae)){for(var We=De.slice(1,4),Qe=0;Qe<3;Qe++)We[Qe]=+We[Qe];return We[3]=1,We}if(De=Te.match(He)){for(var ht=De.slice(1,5),ft=0;ft<4;ft++)ht[ft]=+ht[ft];return ht}if(De=Te.match(Ge)){for(var ct=De.slice(1,4),pt=0;pt<3;pt++)ct[pt]=Ee(ct[pt]*2.55);return ct[3]=1,ct}if(De=Te.match(Ze)){for(var gt=De.slice(1,5),vt=0;vt<3;vt++)gt[vt]=Ee(gt[vt]*2.55);return gt[3]=+gt[3],gt}if(De=Te.match($e)){var bt=De.slice(1,4);bt[1]*=.01,bt[2]*=.01;var At=qe(bt);return At[3]=1,At}if(De=Te.match(me)){var wt=De.slice(1,4);wt[1]*=.01,wt[2]*=.01;var It=qe(wt);return It[3]=+De[4],It}};je.test=function(Te){return Ae.test(Te)||He.test(Te)||Ge.test(Te)||Ze.test(Te)||$e.test(Te)||me.test(Te)};var nt=je,ot=le,dt=ue,Ct=O,St=T.type,kt=Ne,Et=nt;dt.prototype.css=function(Te){return kt(this._rgb,Te)},ot.css=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(dt,[null].concat(Te,["css"])))},Ct.format.css=Et,Ct.autodetect.push({p:5,test:function(Te){for(var De=[],We=arguments.length-1;We-- >0;)De[We]=arguments[We+1];if(!De.length&&St(Te)==="string"&&Et.test(Te))return"css"}});var Lt=ue,tr=le,Xt=O,wr=T.unpack;Xt.format.gl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=wr(Te,"rgba");return We[0]*=255,We[1]*=255,We[2]*=255,We},tr.gl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Lt,[null].concat(Te,["gl"])))},Lt.prototype.gl=function(){var Te=this._rgb;return[Te[0]/255,Te[1]/255,Te[2]/255,Te[3]]};var nr=T.unpack,dr=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=nr(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Math.min(Qe,ht,ft),pt=Math.max(Qe,ht,ft),gt=pt-ct,vt=gt*100/255,bt=ct/(255-gt)*100,At;return gt===0?At=Number.NaN:(Qe===pt&&(At=(ht-ft)/gt),ht===pt&&(At=2+(ft-Qe)/gt),ft===pt&&(At=4+(Qe-ht)/gt),At*=60,At<0&&(At+=360)),[At,vt,bt]},pr=dr,po=T.unpack,go=Math.floor,yo=function(){for(var Te,De,We,Qe,ht,ft,ct=[],pt=arguments.length;pt--;)ct[pt]=arguments[pt];ct=po(ct,"hcg");var gt=ct[0],vt=ct[1],bt=ct[2],At,wt,It;bt=bt*255;var Pt=vt*255;if(vt===0)At=wt=It=bt;else{gt===360&&(gt=0),gt>360&&(gt-=360),gt<0&&(gt+=360),gt/=60;var Bt=go(gt),Ht=gt-Bt,jt=bt*(1-vt),Yt=jt+Pt*(1-Ht),gr=jt+Pt*Ht,fr=jt+Pt;switch(Bt){case 0:Te=[fr,gr,jt],At=Te[0],wt=Te[1],It=Te[2];break;case 1:De=[Yt,fr,jt],At=De[0],wt=De[1],It=De[2];break;case 2:We=[jt,fr,gr],At=We[0],wt=We[1],It=We[2];break;case 3:Qe=[jt,Yt,fr],At=Qe[0],wt=Qe[1],It=Qe[2];break;case 4:ht=[gr,jt,fr],At=ht[0],wt=ht[1],It=ht[2];break;case 5:ft=[fr,jt,Yt],At=ft[0],wt=ft[1],It=ft[2];break}}return[At,wt,It,ct.length>3?ct[3]:1]},vo=yo,xi=T.unpack,_o=T.type,bo=le,ns=ue,is=O,Tr=pr;ns.prototype.hcg=function(){return Tr(this._rgb)},bo.hcg=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(ns,[null].concat(Te,["hcg"])))},is.format.hcg=vo,is.autodetect.push({p:1,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=xi(Te,"hcg"),_o(Te)==="array"&&Te.length===3)return"hcg"}});var $t=T.unpack,ss=T.last,En=Math.round,os=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$t(Te,"rgba"),Qe=We[0],ht=We[1],ft=We[2],ct=We[3],pt=ss(Te)||"auto";ct===void 0&&(ct=1),pt==="auto"&&(pt=ct<1?"rgba":"rgb"),Qe=En(Qe),ht=En(ht),ft=En(ft);var gt=Qe<<16|ht<<8|ft,vt="000000"+gt.toString(16);vt=vt.substr(vt.length-6);var bt="0"+En(ct*255).toString(16);switch(bt=bt.substr(bt.length-2),pt.toLowerCase()){case"rgba":return"#"+vt+bt;case"argb":return"#"+bt+vt;default:return"#"+vt}},Ei=os,Si=/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,ls=/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/,hn=function(Te){if(Te.match(Si)){(Te.length===4||Te.length===7)&&(Te=Te.substr(1)),Te.length===3&&(Te=Te.split(""),Te=Te[0]+Te[0]+Te[1]+Te[1]+Te[2]+Te[2]);var De=parseInt(Te,16),We=De>>16,Qe=De>>8&255,ht=De&255;return[We,Qe,ht,1]}if(Te.match(ls)){(Te.length===5||Te.length===9)&&(Te=Te.substr(1)),Te.length===4&&(Te=Te.split(""),Te=Te[0]+Te[0]+Te[1]+Te[1]+Te[2]+Te[2]+Te[3]+Te[3]);var ft=parseInt(Te,16),ct=ft>>24&255,pt=ft>>16&255,gt=ft>>8&255,vt=Math.round((ft&255)/255*100)/100;return[ct,pt,gt,vt]}throw new Error("unknown hex color: "+Te)},Ci=hn,wo=le,cs=ue,xo=T.type,us=O,hs=Ei;cs.prototype.hex=function(Te){return hs(this._rgb,Te)},wo.hex=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(cs,[null].concat(Te,["hex"])))},us.format.hex=Ci,us.autodetect.push({p:4,test:function(Te){for(var De=[],We=arguments.length-1;We-- >0;)De[We]=arguments[We+1];if(!De.length&&xo(Te)==="string"&&[3,4,5,6,7,8,9].indexOf(Te.length)>=0)return"hex"}});var Eo=T.unpack,Sn=T.TWOPI,So=Math.min,Co=Math.sqrt,ko=Math.acos,To=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Eo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2];Qe/=255,ht/=255,ft/=255;var ct,pt=So(Qe,ht,ft),gt=(Qe+ht+ft)/3,vt=gt>0?1-pt/gt:0;return vt===0?ct=NaN:(ct=(Qe-ht+(Qe-ft))/2,ct/=Co((Qe-ht)*(Qe-ht)+(Qe-ft)*(ht-ft)),ct=ko(ct),ft>ht&&(ct=Sn-ct),ct/=Sn),[ct*360,vt,gt]},Ao=To,ki=T.unpack,Kr=T.limit,Yr=T.TWOPI,Gn=T.PITHIRD,Ar=Math.cos,Wt=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=ki(Te,"hsi");var We=Te[0],Qe=Te[1],ht=Te[2],ft,ct,pt;return isNaN(We)&&(We=0),isNaN(Qe)&&(Qe=0),We>360&&(We-=360),We<0&&(We+=360),We/=360,We<1/3?(pt=(1-Qe)/3,ft=(1+Qe*Ar(Yr*We)/Ar(Gn-Yr*We))/3,ct=1-(pt+ft)):We<2/3?(We-=1/3,ft=(1-Qe)/3,ct=(1+Qe*Ar(Yr*We)/Ar(Gn-Yr*We))/3,pt=1-(ft+ct)):(We-=2/3,ct=(1-Qe)/3,pt=(1+Qe*Ar(Yr*We)/Ar(Gn-Yr*We))/3,ft=1-(ct+pt)),ft=Kr(ht*ft*3),ct=Kr(ht*ct*3),pt=Kr(ht*pt*3),[ft*255,ct*255,pt*255,Te.length>3?Te[3]:1]},ir=Wt,qn=T.unpack,fn=T.type,dn=le,Xn=ue,Nt=O,ar=Ao;Xn.prototype.hsi=function(){return ar(this._rgb)},dn.hsi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Xn,[null].concat(Te,["hsi"])))},Nt.format.hsi=ir,Nt.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=qn(Te,"hsi"),fn(Te)==="array"&&Te.length===3)return"hsi"}});var Ti=T.unpack,Zn=T.type,xr=le,fs=ue,Cn=O,Gr=be;fs.prototype.hsl=function(){return Gr(this._rgb)},xr.hsl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(fs,[null].concat(Te,["hsl"])))},Cn.format.hsl=rt,Cn.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Ti(Te,"hsl"),Zn(Te)==="array"&&Te.length===3)return"hsl"}});var lr=T.unpack,qr=Math.min,kn=Math.max,Tn=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=lr(Te,"rgb");var We=Te[0],Qe=Te[1],ht=Te[2],ft=qr(We,Qe,ht),ct=kn(We,Qe,ht),pt=ct-ft,gt,vt,bt;return bt=ct/255,ct===0?(gt=Number.NaN,vt=0):(vt=pt/ct,We===ct&&(gt=(Qe-ht)/pt),Qe===ct&&(gt=2+(ht-We)/pt),ht===ct&&(gt=4+(We-Qe)/pt),gt*=60,gt<0&&(gt+=360)),[gt,vt,bt]},Ai=Tn,An=T.unpack,Pi=Math.floor,Ii=function(){for(var Te,De,We,Qe,ht,ft,ct=[],pt=arguments.length;pt--;)ct[pt]=arguments[pt];ct=An(ct,"hsv");var gt=ct[0],vt=ct[1],bt=ct[2],At,wt,It;if(bt*=255,vt===0)At=wt=It=bt;else{gt===360&&(gt=0),gt>360&&(gt-=360),gt<0&&(gt+=360),gt/=60;var Pt=Pi(gt),Bt=gt-Pt,Ht=bt*(1-vt),jt=bt*(1-vt*Bt),Yt=bt*(1-vt*(1-Bt));switch(Pt){case 0:Te=[bt,Yt,Ht],At=Te[0],wt=Te[1],It=Te[2];break;case 1:De=[jt,bt,Ht],At=De[0],wt=De[1],It=De[2];break;case 2:We=[Ht,bt,Yt],At=We[0],wt=We[1],It=We[2];break;case 3:Qe=[Ht,jt,bt],At=Qe[0],wt=Qe[1],It=Qe[2];break;case 4:ht=[Yt,Ht,bt],At=ht[0],wt=ht[1],It=ht[2];break;case 5:ft=[bt,Ht,jt],At=ft[0],wt=ft[1],It=ft[2];break}}return[At,wt,It,ct.length>3?ct[3]:1]},Qn=Ii,$i=T.unpack,Li=T.type,Jn=le,Ri=ue,ei=O,Po=Ai;Ri.prototype.hsv=function(){return Po(this._rgb)},Jn.hsv=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Ri,[null].concat(Te,["hsv"])))},ei.format.hsv=Qn,ei.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=$i(Te,"hsv"),Li(Te)==="array"&&Te.length===3)return"hsv"}});var Ot={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},mr=Ot,Qt=T.unpack,Mi=Math.pow,Oi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Qt(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Xr(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2],bt=116*gt-16;return[bt<0?0:bt,500*(pt-gt),200*(gt-vt)]},Pn=function(Te){return(Te/=255)<=.04045?Te/12.92:Mi((Te+.055)/1.055,2.4)},In=function(Te){return Te>mr.t3?Mi(Te,1/3):Te/mr.t2+mr.t0},Xr=function(Te,De,We){Te=Pn(Te),De=Pn(De),We=Pn(We);var Qe=In((.4124564*Te+.3575761*De+.1804375*We)/mr.Xn),ht=In((.2126729*Te+.7151522*De+.072175*We)/mr.Yn),ft=In((.0193339*Te+.119192*De+.9503041*We)/mr.Zn);return[Qe,ht,ft]},ti=Oi,Pr=Ot,ur=T.unpack,Zr=Math.pow,ds=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=ur(Te,"lab");var We=Te[0],Qe=Te[1],ht=Te[2],ft,ct,pt,gt,vt,bt;return ct=(We+16)/116,ft=isNaN(Qe)?ct:ct+Qe/500,pt=isNaN(ht)?ct:ct-ht/200,ct=Pr.Yn*Di(ct),ft=Pr.Xn*Di(ft),pt=Pr.Zn*Di(pt),gt=ri(3.2404542*ft-1.5371385*ct-.4985314*pt),vt=ri(-.969266*ft+1.8760108*ct+.041556*pt),bt=ri(.0556434*ft-.2040259*ct+1.0572252*pt),[gt,vt,bt,Te.length>3?Te[3]:1]},ri=function(Te){return 255*(Te<=.00304?12.92*Te:1.055*Zr(Te,1/2.4)-.055)},Di=function(Te){return Te>Pr.t1?Te*Te*Te:Pr.t2*(Te-Pr.t0)},Ni=ds,Bi=T.unpack,Io=T.type,ps=le,Vt=ue,gs=O,Cr=ti;Vt.prototype.lab=function(){return Cr(this._rgb)},ps.lab=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Vt,[null].concat(Te,["lab"])))},gs.format.lab=Ni,gs.autodetect.push({p:2,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Bi(Te,"lab"),Io(Te)==="array"&&Te.length===3)return"lab"}});var $n=T.unpack,ys=T.RAD2DEG,$o=Math.sqrt,Fi=Math.atan2,Lo=Math.round,vs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$n(Te,"lab"),Qe=We[0],ht=We[1],ft=We[2],ct=$o(ht*ht+ft*ft),pt=(Fi(ft,ht)*ys+360)%360;return Lo(ct*1e4)===0&&(pt=Number.NaN),[Qe,ct,pt]},_s=vs,Ro=T.unpack,Ui=ti,Mo=_s,Ir=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Ro(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Ui(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2];return Mo(pt,gt,vt)},Oo=Ir,bs=T.unpack,Vr=T.DEG2RAD,ws=Math.sin,xs=Math.cos,Do=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=bs(Te,"lch"),Qe=We[0],ht=We[1],ft=We[2];return isNaN(ft)&&(ft=0),ft=ft*Vr,[Qe,xs(ft)*ht,ws(ft)*ht]},Es=Do,Vi=T.unpack,No=Es,Ss=Ni,Cs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Vi(Te,"lch");var We=Te[0],Qe=Te[1],ht=Te[2],ft=No(We,Qe,ht),ct=ft[0],pt=ft[1],gt=ft[2],vt=Ss(ct,pt,gt),bt=vt[0],At=vt[1],wt=vt[2];return[bt,At,wt,Te.length>3?Te[3]:1]},Ln=Cs,Qr=T.unpack,Bo=Ln,Rn=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Qr(Te,"hcl").reverse();return Bo.apply(void 0,We)},Er=Rn,ks=T.unpack,Ts=T.type,As=le,Mn=ue,ni=O,Ps=Oo;Mn.prototype.lch=function(){return Ps(this._rgb)},Mn.prototype.hcl=function(){return Ps(this._rgb).reverse()},As.lch=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Mn,[null].concat(Te,["lch"])))},As.hcl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Mn,[null].concat(Te,["hcl"])))},ni.format.lch=Ln,ni.format.hcl=Er,["lch","hcl"].forEach(function(Te){return ni.autodetect.push({p:2,test:function(){for(var De=[],We=arguments.length;We--;)De[We]=arguments[We];if(De=ks(De,Te),Ts(De)==="array"&&De.length===3)return Te}})});var Hi={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflower:"#6495ed",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},ii=Hi,Fo=ue,Is=O,$s=T.type,On=ii,kr=Ci,pn=Ei;Fo.prototype.name=function(){for(var Te=pn(this._rgb,"rgb"),De=0,We=Object.keys(On);De0;)De[We]=arguments[We+1];if(!De.length&&$s(Te)==="string"&&On[Te.toLowerCase()])return"named"}});var Uo=T.unpack,Jr=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Uo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2];return(Qe<<16)+(ht<<8)+ft},Vo=Jr,mn=T.type,Ho=function(Te){if(mn(Te)=="number"&&Te>=0&&Te<=16777215){var De=Te>>16,We=Te>>8&255,Qe=Te&255;return[De,We,Qe,1]}throw new Error("unknown num color: "+Te)},Dn=Ho,Ls=le,Nn=ue,Rs=O,Hr=T.type,si=Vo;Nn.prototype.num=function(){return si(this._rgb)},Ls.num=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Nn,[null].concat(Te,["num"])))},Rs.format.num=Dn,Rs.autodetect.push({p:5,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te.length===1&&Hr(Te[0])==="number"&&Te[0]>=0&&Te[0]<=16777215)return"num"}});var zo=le,Bn=ue,Ms=O,$r=T.unpack,Os=T.type,en=Math.round;Bn.prototype.rgb=function(Te){return Te===void 0&&(Te=!0),Te===!1?this._rgb.slice(0,3):this._rgb.slice(0,3).map(en)},Bn.prototype.rgba=function(Te){return Te===void 0&&(Te=!0),this._rgb.slice(0,4).map(function(De,We){return We<3?Te===!1?De:en(De):De})},zo.rgb=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Bn,[null].concat(Te,["rgb"])))},Ms.format.rgb=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=$r(Te,"rgba");return We[3]===void 0&&(We[3]=1),We},Ms.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=$r(Te,"rgba"),Os(Te)==="array"&&(Te.length===3||Te.length===4&&Os(Te[3])=="number"&&Te[3]>=0&&Te[3]<=1))return"rgb"}});var oi=Math.log,Rr=function(Te){var De=Te/100,We,Qe,ht;return De<66?(We=255,Qe=De<6?0:-155.25485562709179-.44596950469579133*(Qe=De-2)+104.49216199393888*oi(Qe),ht=De<20?0:-254.76935184120902+.8274096064007395*(ht=De-10)+115.67994401066147*oi(ht)):(We=351.97690566805693+.114206453784165*(We=De-55)-40.25366309332127*oi(We),Qe=325.4494125711974+.07943456536662342*(Qe=De-50)-28.0852963507957*oi(Qe),ht=255),[We,Qe,ht,1]},Fn=Rr,Ds=Fn,zi=T.unpack,ai=Math.round,Wi=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];for(var We=zi(Te,"rgb"),Qe=We[0],ht=We[2],ft=1e3,ct=4e4,pt=.4,gt;ct-ft>pt;){gt=(ct+ft)*.5;var vt=Ds(gt);vt[2]/vt[0]>=ht/Qe?ct=gt:ft=gt}return ai(gt)},li=Wi,zr=le,tn=ue,Un=O,Ns=li;tn.prototype.temp=tn.prototype.kelvin=tn.prototype.temperature=function(){return Ns(this._rgb)},zr.temp=zr.kelvin=zr.temperature=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(tn,[null].concat(Te,["temp"])))},Un.format.temp=Un.format.kelvin=Un.format.temperature=Fn;var Wo=T.unpack,gn=Math.cbrt,jo=Math.pow,Bs=Math.sign,Ko=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Wo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=[Ki(Qe/255),Ki(ht/255),Ki(ft/255)],pt=ct[0],gt=ct[1],vt=ct[2],bt=gn(.4122214708*pt+.5363325363*gt+.0514459929*vt),At=gn(.2119034982*pt+.6806995451*gt+.1073969566*vt),wt=gn(.0883024619*pt+.2817188376*gt+.6299787005*vt);return[.2104542553*bt+.793617785*At-.0040720468*wt,1.9779984951*bt-2.428592205*At+.4505937099*wt,.0259040371*bt+.7827717662*At-.808675766*wt]},ji=Ko;function Ki(Te){var De=Math.abs(Te);return De<.04045?Te/12.92:(Bs(Te)||1)*jo((De+.055)/1.055,2.4)}var Lr=T.unpack,rn=Math.pow,Yo=Math.sign,ci=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Lr(Te,"lab");var We=Te[0],Qe=Te[1],ht=Te[2],ft=rn(We+.3963377774*Qe+.2158037573*ht,3),ct=rn(We-.1055613458*Qe-.0638541728*ht,3),pt=rn(We-.0894841775*Qe-1.291485548*ht,3);return[255*ui(4.0767416621*ft-3.3077115913*ct+.2309699292*pt),255*ui(-1.2684380046*ft+2.6097574011*ct-.3413193965*pt),255*ui(-.0041960863*ft-.7034186147*ct+1.707614701*pt),Te.length>3?Te[3]:1]},Fs=ci;function ui(Te){var De=Math.abs(Te);return De>.0031308?(Yo(Te)||1)*(1.055*rn(De,1/2.4)-.055):Te*12.92}var Go=T.unpack,Vn=T.type,qo=le,nn=ue,Yi=O,Us=ji;nn.prototype.oklab=function(){return Us(this._rgb)},qo.oklab=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(nn,[null].concat(Te,["oklab"])))},Yi.format.oklab=Fs,Yi.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Go(Te,"oklab"),Vn(Te)==="array"&&Te.length===3)return"oklab"}});var Xo=T.unpack,Mr=ji,Vs=_s,Hs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];var We=Xo(Te,"rgb"),Qe=We[0],ht=We[1],ft=We[2],ct=Mr(Qe,ht,ft),pt=ct[0],gt=ct[1],vt=ct[2];return Vs(pt,gt,vt)},Hn=Hs,Zo=T.unpack,hi=Es,zn=Fs,zs=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];Te=Zo(Te,"lch");var We=Te[0],Qe=Te[1],ht=Te[2],ft=hi(We,Qe,ht),ct=ft[0],pt=ft[1],gt=ft[2],vt=zn(ct,pt,gt),bt=vt[0],At=vt[1],wt=vt[2];return[bt,At,wt,Te.length>3?Te[3]:1]},Ws=zs,Qo=T.unpack,js=T.type,Ks=le,Gi=ue,qi=O,Ys=Hn;Gi.prototype.oklch=function(){return Ys(this._rgb)},Ks.oklch=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];return new(Function.prototype.bind.apply(Gi,[null].concat(Te,["oklch"])))},qi.format.oklch=Ws,qi.autodetect.push({p:3,test:function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];if(Te=Qo(Te,"oklch"),js(Te)==="array"&&Te.length===3)return"oklch"}});var Gs=ue,qs=T.type;Gs.prototype.alpha=function(Te,De){return De===void 0&&(De=!1),Te!==void 0&&qs(Te)==="number"?De?(this._rgb[3]=Te,this):new Gs([this._rgb[0],this._rgb[1],this._rgb[2],Te],"rgb"):this._rgb[3]};var Xs=ue;Xs.prototype.clipped=function(){return this._rgb._clipped||!1};var sn=ue,g=Ot;sn.prototype.darken=function(Te){Te===void 0&&(Te=1);var De=this,We=De.lab();return We[0]-=g.Kn*Te,new sn(We,"lab").alpha(De.alpha(),!0)},sn.prototype.brighten=function(Te){return Te===void 0&&(Te=1),this.darken(-Te)},sn.prototype.darker=sn.prototype.darken,sn.prototype.brighter=sn.prototype.brighten;var S=ue;S.prototype.get=function(Te){var De=Te.split("."),We=De[0],Qe=De[1],ht=this[We]();if(Qe){var ft=We.indexOf(Qe)-(We.substr(0,2)==="ok"?2:0);if(ft>-1)return ht[ft];throw new Error("unknown channel "+Qe+" in mode "+We)}else return ht};var B=ue,_e=T.type,Me=Math.pow,Ye=1e-7,lt=20;B.prototype.luminance=function(Te){if(Te!==void 0&&_e(Te)==="number"){if(Te===0)return new B([0,0,0,this._rgb[3]],"rgb");if(Te===1)return new B([255,255,255,this._rgb[3]],"rgb");var De=this.luminance(),We="rgb",Qe=lt,ht=function(ct,pt){var gt=ct.interpolate(pt,.5,We),vt=gt.luminance();return Math.abs(Te-vt)Te?ht(ct,gt):ht(gt,pt)},ft=(De>Te?ht(new B([0,0,0]),this):ht(this,new B([255,255,255]))).rgb();return new B(ft.concat([this._rgb[3]]))}return mt.apply(void 0,this._rgb.slice(0,3))};var mt=function(Te,De,We){return Te=yt(Te),De=yt(De),We=yt(We),.2126*Te+.7152*De+.0722*We},yt=function(Te){return Te/=255,Te<=.03928?Te/12.92:Me((Te+.055)/1.055,2.4)},_t={},Tt=ue,Mt=T.type,Dt=_t,br=function(Te,De,We){We===void 0&&(We=.5);for(var Qe=[],ht=arguments.length-3;ht-- >0;)Qe[ht]=arguments[ht+3];var ft=Qe[0]||"lrgb";if(!Dt[ft]&&!Qe.length&&(ft=Object.keys(Dt)[0]),!Dt[ft])throw new Error("interpolation mode "+ft+" is not defined");return Mt(Te)!=="object"&&(Te=new Tt(Te)),Mt(De)!=="object"&&(De=new Tt(De)),Dt[ft](Te,De,We).alpha(Te.alpha()+We*(De.alpha()-Te.alpha()))},Wr=ue,fi=br;Wr.prototype.mix=Wr.prototype.interpolate=function(Te,De){De===void 0&&(De=.5);for(var We=[],Qe=arguments.length-2;Qe-- >0;)We[Qe]=arguments[Qe+2];return fi.apply(void 0,[this,Te,De].concat(We))};var Or=ue;Or.prototype.premultiply=function(Te){Te===void 0&&(Te=!1);var De=this._rgb,We=De[3];return Te?(this._rgb=[De[0]*We,De[1]*We,De[2]*We,We],this):new Or([De[0]*We,De[1]*We,De[2]*We,We],"rgb")};var Wn=ue,Jo=Ot;Wn.prototype.saturate=function(Te){Te===void 0&&(Te=1);var De=this,We=De.lch();return We[1]+=Jo.Kn*Te,We[1]<0&&(We[1]=0),new Wn(We,"lch").alpha(De.alpha(),!0)},Wn.prototype.desaturate=function(Te){return Te===void 0&&(Te=1),this.saturate(-Te)};var Zs=ue,Qs=T.type;Zs.prototype.set=function(Te,De,We){We===void 0&&(We=!1);var Qe=Te.split("."),ht=Qe[0],ft=Qe[1],ct=this[ht]();if(ft){var pt=ht.indexOf(ft)-(ht.substr(0,2)==="ok"?2:0);if(pt>-1){if(Qs(De)=="string")switch(De.charAt(0)){case"+":ct[pt]+=+De;break;case"-":ct[pt]+=+De;break;case"*":ct[pt]*=+De.substr(1);break;case"/":ct[pt]/=+De.substr(1);break;default:ct[pt]=+De}else if(Qs(De)==="number")ct[pt]=De;else throw new Error("unsupported value for Color.set");var gt=new Zs(ct,ht);return We?(this._rgb=gt._rgb,this):gt}throw new Error("unknown channel "+ft+" in mode "+ht)}else return ct};var Js=ue,ea=function(Te,De,We){var Qe=Te._rgb,ht=De._rgb;return new Js(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"rgb")};_t.rgb=ea;var eo=ue,sr=Math.sqrt,Dr=Math.pow,ta=function(Te,De,We){var Qe=Te._rgb,ht=Qe[0],ft=Qe[1],ct=Qe[2],pt=De._rgb,gt=pt[0],vt=pt[1],bt=pt[2];return new eo(sr(Dr(ht,2)*(1-We)+Dr(gt,2)*We),sr(Dr(ft,2)*(1-We)+Dr(vt,2)*We),sr(Dr(ct,2)*(1-We)+Dr(bt,2)*We),"rgb")};_t.lrgb=ta;var ra=ue,na=function(Te,De,We){var Qe=Te.lab(),ht=De.lab();return new ra(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"lab")};_t.lab=na;var di=ue,an=function(Te,De,We,Qe){var ht,ft,ct,pt;Qe==="hsl"?(ct=Te.hsl(),pt=De.hsl()):Qe==="hsv"?(ct=Te.hsv(),pt=De.hsv()):Qe==="hcg"?(ct=Te.hcg(),pt=De.hcg()):Qe==="hsi"?(ct=Te.hsi(),pt=De.hsi()):Qe==="lch"||Qe==="hcl"?(Qe="hcl",ct=Te.hcl(),pt=De.hcl()):Qe==="oklch"&&(ct=Te.oklch().reverse(),pt=De.oklch().reverse());var gt,vt,bt,At,wt,It;(Qe.substr(0,1)==="h"||Qe==="oklch")&&(ht=ct,gt=ht[0],bt=ht[1],wt=ht[2],ft=pt,vt=ft[0],At=ft[1],It=ft[2]);var Pt,Bt,Ht,jt;return!isNaN(gt)&&!isNaN(vt)?(vt>gt&&vt-gt>180?jt=vt-(gt+360):vt180?jt=vt+360-gt:jt=vt-gt,Bt=gt+We*jt):isNaN(gt)?isNaN(vt)?Bt=Number.NaN:(Bt=vt,(wt==1||wt==0)&&Qe!="hsv"&&(Pt=At)):(Bt=gt,(It==1||It==0)&&Qe!="hsv"&&(Pt=bt)),Pt===void 0&&(Pt=bt+We*(At-bt)),Ht=wt+We*(It-wt),Qe==="oklch"?new di([Ht,Pt,Bt],Qe):new di([Bt,Pt,Ht],Qe)},ia=an,xa=function(Te,De,We){return ia(Te,De,We,"lch")};_t.lch=xa,_t.hcl=xa;var Wa=ue,ja=function(Te,De,We){var Qe=Te.num(),ht=De.num();return new Wa(Qe+We*(ht-Qe),"num")};_t.num=ja;var Ka=an,Ya=function(Te,De,We){return Ka(Te,De,We,"hcg")};_t.hcg=Ya;var Ga=an,qa=function(Te,De,We){return Ga(Te,De,We,"hsi")};_t.hsi=qa;var Xa=an,Za=function(Te,De,We){return Xa(Te,De,We,"hsl")};_t.hsl=Za;var Qa=an,Ja=function(Te,De,We){return Qa(Te,De,We,"hsv")};_t.hsv=Ja;var el=ue,tl=function(Te,De,We){var Qe=Te.oklab(),ht=De.oklab();return new el(Qe[0]+We*(ht[0]-Qe[0]),Qe[1]+We*(ht[1]-Qe[1]),Qe[2]+We*(ht[2]-Qe[2]),"oklab")};_t.oklab=tl;var rl=an,nl=function(Te,De,We){return rl(Te,De,We,"oklch")};_t.oklch=nl;var sa=ue,il=T.clip_rgb,oa=Math.pow,aa=Math.sqrt,la=Math.PI,Ea=Math.cos,Sa=Math.sin,sl=Math.atan2,ol=function(Te,De,We){De===void 0&&(De="lrgb"),We===void 0&&(We=null);var Qe=Te.length;We||(We=Array.from(new Array(Qe)).map(function(){return 1}));var ht=Qe/We.reduce(function(Bt,Ht){return Bt+Ht});if(We.forEach(function(Bt,Ht){We[Ht]*=ht}),Te=Te.map(function(Bt){return new sa(Bt)}),De==="lrgb")return al(Te,We);for(var ft=Te.shift(),ct=ft.get(De),pt=[],gt=0,vt=0,bt=0;bt=360;)Pt-=360;ct[It]=Pt}else ct[It]=ct[It]/pt[It];return wt/=Qe,new sa(ct,De).alpha(wt>.99999?1:wt,!0)},al=function(Te,De){for(var We=Te.length,Qe=[0,0,0,0],ht=0;ht.9999999&&(Qe[3]=1),new sa(il(Qe))},Nr=le,pi=T.type,ll=Math.pow,ca=function(Te){var De="rgb",We=Nr("#ccc"),Qe=0,ht=[0,1],ft=[],ct=[0,0],pt=!1,gt=[],vt=!1,bt=0,At=1,wt=!1,It={},Pt=!0,Bt=1,Ht=function(xt){if(xt=xt||["#fff","#000"],xt&&pi(xt)==="string"&&Nr.brewer&&Nr.brewer[xt.toLowerCase()]&&(xt=Nr.brewer[xt.toLowerCase()]),pi(xt)==="array"){xt.length===1&&(xt=[xt[0],xt[0]]),xt=xt.slice(0);for(var Rt=0;Rt=pt[Ut];)Ut++;return Ut-1}return 0},Yt=function(xt){return xt},gr=function(xt){return xt},fr=function(xt,Rt){var Ut,Ft;if(Rt==null&&(Rt=!1),isNaN(xt)||xt===null)return We;if(Rt)Ft=xt;else if(pt&&pt.length>2){var yr=jt(xt);Ft=yr/(pt.length-2)}else At!==bt?Ft=(xt-bt)/(At-bt):Ft=1;Ft=gr(Ft),Rt||(Ft=Yt(Ft)),Bt!==1&&(Ft=ll(Ft,Bt)),Ft=ct[0]+Ft*(1-ct[0]-ct[1]),Ft=Math.min(1,Math.max(0,Ft));var er=Math.floor(Ft*1e4);if(Pt&&It[er])Ut=It[er];else{if(pi(gt)==="array")for(var Kt=0;Kt=Gt&&Kt===ft.length-1){Ut=gt[Kt];break}if(Ft>Gt&&Ft2){var Kt=xt.map(function(qt,Zt){return Zt/(xt.length-1)}),Gt=xt.map(function(qt){return(qt-bt)/(At-bt)});Gt.every(function(qt,Zt){return Kt[Zt]===qt})||(gr=function(qt){if(qt<=0||qt>=1)return qt;for(var Zt=0;qt>=Gt[Zt+1];)Zt++;var Fr=(qt-Gt[Zt])/(Gt[Zt+1]-Gt[Zt]),_n=Kt[Zt]+Fr*(Kt[Zt+1]-Kt[Zt]);return _n})}}return ht=[bt,At],zt},zt.mode=function(xt){return arguments.length?(De=xt,Sr(),zt):De},zt.range=function(xt,Rt){return Ht(xt),zt},zt.out=function(xt){return vt=xt,zt},zt.spread=function(xt){return arguments.length?(Qe=xt,zt):Qe},zt.correctLightness=function(xt){return xt==null&&(xt=!0),wt=xt,Sr(),wt?Yt=function(Rt){for(var Ut=fr(0,!0).lab()[0],Ft=fr(1,!0).lab()[0],yr=Ut>Ft,er=fr(Rt,!0).lab()[0],Kt=Ut+(Ft-Ut)*Rt,Gt=er-Kt,qt=0,Zt=1,Fr=20;Math.abs(Gt)>.01&&Fr-- >0;)(function(){return yr&&(Gt*=-1),Gt<0?(qt=Rt,Rt+=(Zt-Rt)*.5):(Zt=Rt,Rt+=(qt-Rt)*.5),er=fr(Rt,!0).lab()[0],Gt=er-Kt})();return Rt}:Yt=function(Rt){return Rt},zt},zt.padding=function(xt){return xt!=null?(pi(xt)==="number"&&(xt=[xt,xt]),ct=xt,zt):ct},zt.colors=function(xt,Rt){arguments.length<2&&(Rt="hex");var Ut=[];if(arguments.length===0)Ut=gt.slice(0);else if(xt===1)Ut=[zt(.5)];else if(xt>1){var Ft=ht[0],yr=ht[1]-Ft;Ut=cl(0,xt,!1).map(function(Zt){return zt(Ft+Zt/(xt-1)*yr)})}else{Te=[];var er=[];if(pt&&pt.length>2)for(var Kt=1,Gt=pt.length,qt=1<=Gt;qt?KtGt;qt?Kt++:Kt--)er.push((pt[Kt-1]+pt[Kt])*.5);else er=ht;Ut=er.map(function(Zt){return zt(Zt)})}return Nr[Rt]&&(Ut=Ut.map(function(Zt){return Zt[Rt]()})),Ut},zt.cache=function(xt){return xt!=null?(Pt=xt,zt):Pt},zt.gamma=function(xt){return xt!=null?(Bt=xt,zt):Bt},zt.nodata=function(xt){return xt!=null?(We=Nr(xt),zt):We},zt};function cl(Te,De,We){for(var Qe=[],ht=Teft;ht?ct++:ct--)Qe.push(ct);return Qe}var Xi=ue,ul=ca,hl=function(Te){for(var De=[1,1],We=1;We=5){var vt,bt,At;vt=Te.map(function(wt){return wt.lab()}),At=Te.length-1,bt=hl(At),ht=function(wt){var It=1-wt,Pt=[0,1,2].map(function(Bt){return vt.reduce(function(Ht,jt,Yt){return Ht+bt[Yt]*Math.pow(It,At-Yt)*Math.pow(wt,Yt)*jt[Bt]},0)});return new Xi(Pt,"lab")}}else throw new RangeError("No point in running bezier with only one color.");return ht},dl=function(Te){var De=fl(Te);return De.scale=function(){return ul(De)},De},ua=le,Br=function(Te,De,We){if(!Br[We])throw new Error("unknown blend mode "+We);return Br[We](Te,De)},yn=function(Te){return function(De,We){var Qe=ua(We).rgb(),ht=ua(De).rgb();return ua.rgb(Te(Qe,ht))}},vn=function(Te){return function(De,We){var Qe=[];return Qe[0]=Te(De[0],We[0]),Qe[1]=Te(De[1],We[1]),Qe[2]=Te(De[2],We[2]),Qe}},pl=function(Te){return Te},ml=function(Te,De){return Te*De/255},gl=function(Te,De){return Te>De?De:Te},yl=function(Te,De){return Te>De?Te:De},vl=function(Te,De){return 255*(1-(1-Te/255)*(1-De/255))},_l=function(Te,De){return De<128?2*Te*De/255:255*(1-2*(1-Te/255)*(1-De/255))},bl=function(Te,De){return 255*(1-(1-De/255)/(Te/255))},wl=function(Te,De){return Te===255?255:(Te=255*(De/255)/(1-Te/255),Te>255?255:Te)};Br.normal=yn(vn(pl)),Br.multiply=yn(vn(ml)),Br.screen=yn(vn(vl)),Br.overlay=yn(vn(_l)),Br.darken=yn(vn(gl)),Br.lighten=yn(vn(yl)),Br.dodge=yn(vn(wl)),Br.burn=yn(vn(bl));for(var xl=Br,ha=T.type,El=T.clip_rgb,Sl=T.TWOPI,Cl=Math.pow,kl=Math.sin,Tl=Math.cos,Ca=le,Al=function(Te,De,We,Qe,ht){Te===void 0&&(Te=300),De===void 0&&(De=-1.5),We===void 0&&(We=1),Qe===void 0&&(Qe=1),ht===void 0&&(ht=[0,1]);var ft=0,ct;ha(ht)==="array"?ct=ht[1]-ht[0]:(ct=0,ht=[ht,ht]);var pt=function(gt){var vt=Sl*((Te+120)/360+De*gt),bt=Cl(ht[0]+ct*gt,Qe),At=ft!==0?We[0]+gt*ft:We,wt=At*bt*(1-bt)/2,It=Tl(vt),Pt=kl(vt),Bt=bt+wt*(-.14861*It+1.78277*Pt),Ht=bt+wt*(-.29227*It-.90649*Pt),jt=bt+wt*(1.97294*It);return Ca(El([Bt*255,Ht*255,jt*255,1]))};return pt.start=function(gt){return gt==null?Te:(Te=gt,pt)},pt.rotations=function(gt){return gt==null?De:(De=gt,pt)},pt.gamma=function(gt){return gt==null?Qe:(Qe=gt,pt)},pt.hue=function(gt){return gt==null?We:(We=gt,ha(We)==="array"?(ft=We[1]-We[0],ft===0&&(We=We[1])):ft=0,pt)},pt.lightness=function(gt){return gt==null?ht:(ha(gt)==="array"?(ht=gt,ct=gt[1]-gt[0]):(ht=[gt,gt],ct=0),pt)},pt.scale=function(){return Ca.scale(pt)},pt.hue(We),pt},Pl=ue,Il="0123456789abcdef",$l=Math.floor,Ll=Math.random,Rl=function(){for(var Te="#",De=0;De<6;De++)Te+=Il.charAt($l(Ll()*16));return new Pl(Te,"hex")},fa=_,ka=Math.log,Ml=Math.pow,Ol=Math.floor,Dl=Math.abs,Ta=function(Te,De){De===void 0&&(De=null);var We={min:Number.MAX_VALUE,max:Number.MAX_VALUE*-1,sum:0,values:[],count:0};return fa(Te)==="object"&&(Te=Object.values(Te)),Te.forEach(function(Qe){De&&fa(Qe)==="object"&&(Qe=Qe[De]),Qe!=null&&!isNaN(Qe)&&(We.values.push(Qe),We.sum+=Qe,QeWe.max&&(We.max=Qe),We.count+=1)}),We.domain=[We.min,We.max],We.limits=function(Qe,ht){return Aa(We,Qe,ht)},We},Aa=function(Te,De,We){De===void 0&&(De="equal"),We===void 0&&(We=7),fa(Te)=="array"&&(Te=Ta(Te));var Qe=Te.min,ht=Te.max,ft=Te.values.sort(function(pa,ma){return pa-ma});if(We===1)return[Qe,ht];var ct=[];if(De.substr(0,1)==="c"&&(ct.push(Qe),ct.push(ht)),De.substr(0,1)==="e"){ct.push(Qe);for(var pt=1;pt 0");var gt=Math.LOG10E*ka(Qe),vt=Math.LOG10E*ka(ht);ct.push(Qe);for(var bt=1;bt200&&(gr=!1)}for(var bn={},mi=0;miQe?(We+.05)/(Qe+.05):(Qe+.05)/(We+.05)},$a=ue,ln=Math.sqrt,cr=Math.pow,Bl=Math.min,Fl=Math.max,La=Math.atan2,Ra=Math.abs,ro=Math.cos,Ma=Math.sin,Ul=Math.exp,Oa=Math.PI,Vl=function(Te,De,We,Qe,ht){We===void 0&&(We=1),Qe===void 0&&(Qe=1),ht===void 0&&(ht=1);var ft=function(Kn){return 360*Kn/(2*Oa)},ct=function(Kn){return 2*Oa*Kn/360};Te=new $a(Te),De=new $a(De);var pt=Array.from(Te.lab()),gt=pt[0],vt=pt[1],bt=pt[2],At=Array.from(De.lab()),wt=At[0],It=At[1],Pt=At[2],Bt=(gt+wt)/2,Ht=ln(cr(vt,2)+cr(bt,2)),jt=ln(cr(It,2)+cr(Pt,2)),Yt=(Ht+jt)/2,gr=.5*(1-ln(cr(Yt,7)/(cr(Yt,7)+cr(25,7)))),fr=vt*(1+gr),Sr=It*(1+gr),zt=ln(cr(fr,2)+cr(bt,2)),xt=ln(cr(Sr,2)+cr(Pt,2)),Rt=(zt+xt)/2,Ut=ft(La(bt,fr)),Ft=ft(La(Pt,Sr)),yr=Ut>=0?Ut:Ut+360,er=Ft>=0?Ft:Ft+360,Kt=Ra(yr-er)>180?(yr+er+360)/2:(yr+er)/2,Gt=1-.17*ro(ct(Kt-30))+.24*ro(ct(2*Kt))+.32*ro(ct(3*Kt+6))-.2*ro(ct(4*Kt-63)),qt=er-yr;qt=Ra(qt)<=180?qt:er<=yr?qt+360:qt-360,qt=2*ln(zt*xt)*Ma(ct(qt)/2);var Zt=wt-gt,Fr=xt-zt,_n=1+.015*cr(Bt-50,2)/ln(20+cr(Bt-50,2)),bn=1+.045*Rt,mi=1+.015*Rt*Gt,gi=30*Ul(-cr((Kt-275)/25,2)),cn=2*ln(cr(Rt,7)/(cr(Rt,7)+cr(25,7))),jn=-cn*Ma(2*ct(gi)),Zi=ln(cr(Zt/(We*_n),2)+cr(Fr/(Qe*bn),2)+cr(qt/(ht*mi),2)+jn*(Fr/(Qe*bn))*(qt/(ht*mi)));return Fl(0,Bl(100,Zi))},Da=ue,Hl=function(Te,De,We){We===void 0&&(We="lab"),Te=new Da(Te),De=new Da(De);var Qe=Te.get(We),ht=De.get(We),ft=0;for(var ct in Qe){var pt=(Qe[ct]||0)-(ht[ct]||0);ft+=pt*pt}return Math.sqrt(ft)},zl=ue,Wl=function(){for(var Te=[],De=arguments.length;De--;)Te[De]=arguments[De];try{return new(Function.prototype.bind.apply(zl,[null].concat(Te))),!0}catch{return!1}},Na=le,Ba=ca,jl={cool:function(){return Ba([Na.hsl(180,1,.9),Na.hsl(250,.7,.4)])},hot:function(){return Ba(["#000","#f00","#ff0","#fff"]).mode("rgb")}},no={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},da=0,Fa=Object.keys(no);dal===o);if(r[a])return r[a]}return r[r.length-1]}const markerIcon2x="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAMAAAAhFXfZAAAC91BMVEVMaXEzeak2f7I4g7g3g7cua5gzeKg8hJo3grY4g7c3grU0gLI2frE0daAubJc2gbQwd6QzeKk2gLMtd5sxdKIua5g1frA2f7IydaM0e6w2fq41fK01eqo3grgubJgta5cxdKI1f7AydaQydaMxc6EubJgvbJkwcZ4ubZkwcJwubZgubJcydqUydKIxapgubJctbJcubZcubJcvbJYubJcvbZkubJctbJctbZcubJg2f7AubJcrbZcubJcubJcua5g3grY0fq8ubJcubJdEkdEwhsw6i88vhswuhcsuhMtBjMgthMsrg8srgss6is8qgcs8i9A9iMYtg8spgcoogMo7hcMngMonf8olfso4gr8kfck5iM8jfMk4iM8he8k1fro7itAgesk2hs8eecgzfLcofssdeMg0hc4cd8g2hcsxeLQbdsgZdcgxeLImfcszhM0vda4xgckzhM4xg84wf8Yxgs4udKsvfcQucqhUndROmdM1fK0wcZ8vb5w0eqpQm9MzeKhXoNVcpdYydKNWn9VZotVKltJFjsIwcJ1Rms9OlslLmtH///8+kc9epdYzd6dbo9VHkMM2f7FHmNBClM8ydqVcpNY9hro3gLM9hLczealQmcw3fa46f7A8gLMxc6I3eagyc6FIldJMl9JSnNRSntNNl9JPnNJFi75UnM9ZodVKksg8kM45jc09e6ZHltFBk883gbRBh7pDk9EwcaBzn784g7dKkcY2i81Om9M7j85Llc81is09g7Q4grY/j9A0eqxKmdFFltBEjcXf6fFImdBCiLxJl9FGlNFBi78yiMxVndEvbpo6js74+vx+psPP3+o/ks5HkcpGmNCjwdZCkNDM3ehYoNJEls+lxNkxh8xHks0+jdC1zd5Lg6r+/v/H2ufz9/o3jM3t8/edvdM/k89Th61OiLBSjbZklbaTt9BfptdjmL1AicBHj8hGk9FAgK1dkLNTjLRekrdClc/k7fM0icy0y9tgp9c4jc2NtM9Dlc8zicxeXZn3AAAAQ3RSTlMAHDdTb4yPA+LtnEQmC4L2EmHqB7XA0d0sr478x4/Yd5i1zOfyPkf1sLVq4Nh3FvjxopQ2/STNuFzUwFIwxKaejILpIBEV9wAABhVJREFUeF6s1NdyFEcYBeBeoQIhRAkLlRDGrhIgY3BJL8CVeKzuyXFzzjkn5ZxzzuScg3PO8cKzu70JkO0LfxdTU//pM9vTu7Xgf6KqOVTb9X7toRrVEfBf1HTVjZccrT/2by1VV928Yty9ZbVuucdz90frG8DBjl9pVApbOstvmMuvVgaNXSfAAd6pGxpy6yxf5ph43pS/4f3uoaGm2rdu72S9xzOvMymkZFq/ptDrk90mhW7e4zl7HLzhxGWPR20xmSxJ/VqldG5m9XhaVOA1DadsNh3Pu5L2N6QtPO/32JpqQBVVk20oy/Pi2s23WEvyfHbe1thadVQttvm7Llf65gGmXK67XtupyoM7HQhmXdLS8oGWJNeOJ3C5fG5XCEJnkez3/oFdsvgJ4l2ANZwhrJKk/7OSXa+3Vw2WJMlKnGkobouYk6T0TyX30klOUnTD9HJ5qpckL3EW/w4XF3Xd0FGywXUrstrclVsqz5Pd/sXFYyDnPdrLcQODmGOK47IZb4CmibmMn+MYRzFZ5jg33ZL/EJrWcszHmANy3ARBK/IXtciJy8VsitPSdE3uuHxzougojcUdr8/32atnz/ev3f/K5wtpxUTpcaI45zusVDpYtZi+jg0oU9b3x74h7+n9ABvYEZeKaVq0sh0AtLKsFtqNBdeT0MrSzwwlq9+x6xAO4tgOtSzbCjrNQQiNvQUbUEubvzBUeGw26yDCsRHCoLkTHDa7IdOLIThs/gHvChszh2CimE8peRs47cxANI0lYNB5y1DljpOF0IhzBDPOZnDOqYYbeGKECbPzWnXludPphw5c2YBq5zlwXphIbO4VDCZ0gnPfUO1TwZoYwAs2ExPCedAu9DAjfQUjzITQb3jNj0KG2Sgt6BHaQUdYzWz+XmBktOHwanXjaSTcwwziBcuMOtwBmqPrTOxFQR/DRKKPqyur0aiW6cULYsx6tBm0jXpR/AUWR6HRq9WVW6MRhIq5jLyjbaCTDCijyYJNpCajdyobP/eTw0iexBAKkJ3gA5KcQb2zBXsIBckn+xVv8jkZSaEFHE+jFEleAEfayRU0MouNoBmB/L50Ai/HSLIHxcrpCvnhSQAuakKp2C/YbCylJjXRVy/z3+Kv/RrNcCo+WUzlVEhzKffnTQnxeN9fWF88fiNCUdSTsaufaChKWInHeysygfpIqagoakW+vV20J8uyl6TyNKEZWV4oRSPyCkWpgOLSbkCObT8o2r6tlG58HQquf6O0v50tB7JM7F4EORd2dx/K0w/KHsVkLPaoYrwgP/y7krr3SSMA4zj+OBgmjYkxcdIJQyQRKgg2viX9Hddi9UBb29LrKR7CVVEEEXWojUkXNyfTNDE14W9gbHJNuhjDettN3ZvbOvdOqCD3Jp/9l+/wJE+9PkYGjx/fqkys3S2rMozM/o2106rfMUINo6hVqz+eu/hd1c4xTg0TAfy5kV+4UG6+IthHTU9woWmxuKNbTfuCSfovBCxq7EtHqvYL4Sm6F8GVxsSXHMQ07TOi1DKtZxjWaaIyi4CXWjxPccUw8WVbMYY5wxC1mzEyXMJWkllpRloi+Kkoq69sxBTlElF6aAxYUbjXNlhlDZilDnM4U5SlN5biRsRHnbx3mbeWjEh4mEyiuJDl5XcWVmX5GvNkFgLWZM5qwsop4/AWfLhU1cR7k1VVvcYCWRkOI6Xy5gmnphCYIkvzuNYzHzosq2oNk2RtSs8khfUOfHIDgR6ysYBaMpl4uEgk2U/oJTs9AaTSwma7dT69geAE2ZpEjUsn2ieJNHeKfrI3EcAGJ2ZaNgVuC8EBctCLc57P5u5led6IOBkIYkuQMrmmjChs4VkfOerHqSBkPzZlhe06RslZ3zMjk2sscqKwY0RcjKK+LWbzd7KiHhkncs/siFJ+V5eXxD34B8nVuJEpGJNmxN2gH3vSvp7J70tF+D1Ej8qUJD1TkErAND2GZwTFg/LubvmgiBG3SOvdlsqFQrkEzJCL1rstlnVFROixZoDDSuXQFHESwVGlcuQcMb/b42NgjLowh5MTDFE3vNB5qStRIErdCQEh6pLPR92anSUb/wAIhldAaDMpGgAAAABJRU5ErkJggg==",markerIcon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=",markerShadow="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAQAAAACach9AAACMUlEQVR4Ae3ShY7jQBAE0Aoz/f9/HTMzhg1zrdKUrJbdx+Kd2nD8VNudfsL/Th///dyQN2TH6f3y/BGpC379rV+S+qqetBOxImNQXL8JCAr2V4iMQXHGNJxeCfZXhSRBcQMfvkOWUdtfzlLgAENmZDcmo2TVmt8OSM2eXxBp3DjHSMFutqS7SbmemzBiR+xpKCNUIRkdkkYxhAkyGoBvyQFEJEefwSmmvBfJuJ6aKqKWnAkvGZOaZXTUgFqYULWNSHUckZuR1HIIimUExutRxwzOLROIG4vKmCKQt364mIlhSyzAf1m9lHZHJZrlAOMMztRRiKimp/rpdJDc9Awry5xTZCte7FHtuS8wJgeYGrex28xNTd086Dik7vUMscQOa8y4DoGtCCSkAKlNwpgNtphjrC6MIHUkR6YWxxs6Sc5xqn222mmCRFzIt8lEdKx+ikCtg91qS2WpwVfBelJCiQJwvzixfI9cxZQWgiSJelKnwBElKYtDOb2MFbhmUigbReQBV0Cg4+qMXSxXSyGUn4UbF8l+7qdSGnTC0XLCmahIgUHLhLOhpVCtw4CzYXvLQWQbJNmxoCsOKAxSgBJno75avolkRw8iIAFcsdc02e9iyCd8tHwmeSSoKTowIgvscSGZUOA7PuCN5b2BX9mQM7S0wYhMNU74zgsPBj3HU7wguAfnxxjFQGBE6pwN+GjME9zHY7zGp8wVxMShYX9NXvEWD3HbwJf4giO4CFIQxXScH1/TM+04kkBiAAAAAElFTkSuQmCC",queue=new queue$1;let scale,markersLayer,pathsLayer,moveLayer,handlerClickMarker;delete L$2.Icon.Default.prototype._getIconUrl;L$2.Icon.Default.mergeOptions({iconRetinaUrl:markerIcon2x,iconUrl:markerIcon,shadowUrl:markerShadow});const messageTypes={0:"text",1:"air",2:"garbage",3:"water",4:"fire",5:"forest",6:"alert ",7:"notif",8:"recycle",9:"parking",42:"gank"};let messageIconName={},messageIconType={};const messagesLayers=Object.values(messageTypes).reduce((e,t)=>(e[t]=null,e),{});async function init$2(e,t,r){for(const o of Object.keys(messageTypes)){try{messageIconType[o]=(await __variableDynamicImportRuntimeHelper(Object.assign({"../../assets/message/msg-air.png":()=>__vitePreload(()=>import("./msg-air.abb754d3.js"),[]),"../../assets/message/msg-alert.png":()=>__vitePreload(()=>import("./msg-alert.9404c396.js"),[]),"../../assets/message/msg-fire.png":()=>__vitePreload(()=>import("./msg-fire.faa011b0.js"),[]),"../../assets/message/msg-forest.png":()=>__vitePreload(()=>import("./msg-forest.a623a1f9.js"),[]),"../../assets/message/msg-gank.png":()=>__vitePreload(()=>import("./msg-gank.34a748fe.js"),[]),"../../assets/message/msg-garbage.png":()=>__vitePreload(()=>import("./msg-garbage.b797b882.js"),[]),"../../assets/message/msg-notif.png":()=>__vitePreload(()=>import("./msg-notif.d72c5a6f.js"),[]),"../../assets/message/msg-parking.png":()=>__vitePreload(()=>import("./msg-parking.5da4fdeb.js"),[]),"../../assets/message/msg-recycle.png":()=>__vitePreload(()=>import("./msg-recycle.eab79c00.js"),[]),"../../assets/message/msg-text.png":()=>__vitePreload(()=>import("./msg-text.470fee8d.js"),[]),"../../assets/message/msg-water.png":()=>__vitePreload(()=>import("./msg-water.b0066085.js"),[])}),`../../assets/message/msg-${messageTypes[o]}.png`)).default}catch{messageIconType[o]=(await __vitePreload(()=>import("./msg-text.470fee8d.js"),[])).default}messageIconName[messageTypes[o]]=messageIconType[o]}handlerClickMarker=o=>{/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?e.setActiveArea({position:"absolute",top:"90px",left:"0px",right:"0px",height:"20%"}):e.setActiveArea({position:"absolute",top:"0px",left:"0px",right:"50%",height:"100%"}),e.panTo(o.latlng),r(o.target.options.data)};const n=getMeasurementByName(t);scale=generate$1(n.colors,n.range),markersLayer=new L$2.MarkerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:120,iconCreateFunction:iconCreate}),e.addLayer(markersLayer),pathsLayer=new L$2.layerGroup,e.addLayer(pathsLayer),moveLayer=new L$2.layerGroup,e.addLayer(moveLayer);for(const o of Object.values(messageTypes))messagesLayers[o]=new L$2.MarkerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:120,iconCreateFunction:a=>iconCreateMsg(a,o)});for(const o of Object.values(messagesLayers))e.addLayer(o)}function isReadyLayers(){return!!(markersLayer&&pathsLayer&&moveLayer)}function iconCreate(e){const t=e.getAllChildMarkers(),r=e.getChildCount();let n=0,o=0;t.forEach(u=>{u.options.data.value===void 0&&u.options.data.value!==""||(n++,o+=Number(u.options.data.value))}),n>0&&(o=o/n);const a=getColorRGB(scale,o),l=getColorDarkenRGB(scale,o),c=scale(o).luminance()<.4;return new L$2.DivIcon({html:`
${r}
`,className:"marker-cluster",iconSize:new L$2.Point(40,40)})}function iconCreateMsg(e,t="text"){const r=e.getChildCount();return new L$2.DivIcon({html:`
${r}
`,className:"marker-cluster",iconSize:new L$2.Point(40,40)})}function findMarker(e){return new Promise(t=>{markersLayer&&markersLayer.eachLayer(r=>{r.options.data.sensor_id===e&&t(r)}),t(!1)})}function findMarkerMoved(e){return new Promise(t=>{moveLayer&&moveLayer.eachLayer(r=>{r.options.data.sensor_id===e&&t(r)}),t(!1)})}function createIconBrand(e,t){return L$2.divIcon({html:``,iconSize:[40,40],className:"marker-icon"})}function createIconMsg(e=0){return L$2.divIcon({html:``,iconSize:[40,40],className:"marker-icon"})}function createIconArrow(e,t,r){return L$2.divIcon({className:"",html:`
${t} m/s
`,iconSize:new L$2.Point(40,40)})}function iconCreateCircle(e){return new L$2.DivIcon({html:`
`,className:"marker-cluster",iconSize:new L$2.Point(40,40)})}function createMarkerBrand(e,t,r){return L$2.marker(new L$2.LatLng(e[0],e[1]),{icon:createIconBrand(t.sensor_id,r.rgb),data:t,typeMarker:"brand"})}function createMarkerArrow(e,t,r){return L$2.marker(new L$2.LatLng(e[0],e[1]),{icon:createIconArrow(t.data.windang,t.data.windspeed,r.basic),data:t,typeMarker:"arrow"})}function createMarkerCircle(e,t,r){return L$2.marker(new L$2.LatLng(e[0],e[1]),{icon:iconCreateCircle(r),data:t,typeMarker:"circle"})}function createMarkerUser(e,t){return L$2.marker(new L$2.LatLng(e[0],e[1]),{icon:createIconMsg(t.data.type),data:t,typeMarker:"msg"})}function createMarker(e,t){const r=[e.geo.lat,e.geo.lng];let n;return sensors[e.sensor_id]&&sensors[e.sensor_id].icon?n=createMarkerBrand(r,e,t):e.data.windang?n=createMarkerArrow(r,e,t):e.model===4?n=createMarkerUser(r,e):n=createMarkerCircle(r,e,t),n}function updateMarker(e,t,r){if(e.options.typeMarker==="brand"?e.setIcon(createIconBrand(t.sensor_id,r.rgb)):e.options.typeMarker==="arrow"&&Object.prototype.hasOwnProperty.call(t.data,"windang")?e.setIcon(createIconArrow(t.data.windang,t.data.windspeed,r.basic)):e.setIcon(iconCreateCircle(r)),t.model===3){const n=[t.geo.lat,t.geo.lng];e.setLatLng(new L$2.LatLng(n[0],n[1]))}}async function addPoint(e){queue.add(t.bind(queue,e));async function t(r){try{if(r.model===1)console.log(r);else if(r.model===2){await addMarker(r);const n=new BroadcastChannel("sensors");n.postMessage(r),n.close()}else r.model===3?(await addMarker(r),await addPointPath(r)):r.model===4&&await addMarkerUser(r)}catch(n){console.log(n)}this.next()}}async function addMarker(e){const t={basic:"#a1a1a1",border:"#999",rgb:[161,161,161]};e.isEmpty||(t.basic=getColor(scale,e.value),t.border=getColorDarken(scale,e.value),t.rgb=getColorRGB(scale,e.value));const r=await findMarker(e.sensor_id);if(r)updateMarker(r,e,t);else{const n=createMarker(e,t);n.on("click",handlerClickMarker),markersLayer?markersLayer.addLayer(n):console.log("Not found markersLayer")}}async function moveMarkerTime(e,t,r=!1){let n;if(r?(n=await findMarkerMoved(e),n&&moveLayer&&markersLayer&&(moveLayer.removeLayer(n),markersLayer.addLayer(n))):(n=await findMarker(e),n&&moveLayer&&markersLayer?(markersLayer.removeLayer(n),moveLayer.addLayer(n)):n=await findMarkerMoved(e)),n){const o=[t.geo.lat,t.geo.lng];n.setLatLng(new L$2.LatLng(o[0],o[1]))}}const paths={};async function addPointPath(e){const t=e.isEmpty?"#bb4506":getColor(scale,e.value),r=[e.geo.lat,e.geo.lng],n=paths[e.sensor_id]||null;if(n){const o=n.getLatLngs();if(o[o.length-1].lat===Number(r[0])&&o[o.length-1].lng===Number(r[1]))return;o.length===1?n.arrowheads({yawn:30,fill:!0,frequency:"allvertices",size:"15px"}).setStyle({color:t}).addLatLng(r):n.setStyle({color:t}).addLatLng(r)}else{const o=L$2.polyline([r],{color:t,weight:2,opacity:.8,data:e});paths[e.sensor_id]=o}}async function showPath(e){const t=paths[e]||null;t&&pathsLayer&&pathsLayer.addLayer(t)}async function hidePath(e){const t=paths[e]||null;t&&pathsLayer&&pathsLayer.hasLayer(t)&&pathsLayer.removeLayer(t)}async function addMarkerUser(e){const t={basic:"#f99981",border:"#999",rgb:[161,161,161]};if(!await findMarker(e.sensor_id)){const n=createMarker(e,t);n.on("click",handlerClickMarker),messageTypes[e.data.type]&&messagesLayers[messageTypes[e.data.type]]&&messagesLayers[messageTypes[e.data.type]].addLayer(n)}}function clear(){if(markersLayer){markersLayer.clearLayers();const e=new BroadcastChannel("sensorsremoved");e.postMessage(!0),e.close()}pathsLayer&&pathsLayer.clearLayers();for(const e of Object.values(messagesLayers))e&&e.clearLayers()}function switchMessagesLayer(e,t=!1){for(const r of Object.values(messagesLayers))r&&(t?e.addLayer(r):e.removeLayer(r))}function bind$1(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString$7}=Object.prototype,{getPrototypeOf}=Object,kindOf=(e=>t=>{const r=toString$7.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray$3}=Array,isUndefined=typeOfTest("undefined");function isBuffer$1(e){return e!==null&&!isUndefined(e)&&e.constructor!==null&&!isUndefined(e.constructor)&&isFunction$1(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer$1=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&isArrayBuffer$1(e.buffer),t}const isString$1=typeOfTest("string"),isFunction$1=typeOfTest("function"),isNumber$1=typeOfTest("number"),isObject$1=e=>e!==null&&typeof e=="object",isBoolean$1=e=>e===!0||e===!1,isPlainObject$2=e=>{if(kindOf(e)!=="object")return!1;const t=getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},isDate$1=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject$1(e)&&isFunction$1(e.pipe),isFormData=e=>{const t="[object FormData]";return e&&(typeof FormData=="function"&&e instanceof FormData||toString$7.call(e)===t||isFunction$1(e.toString)&&e.toString()===t)},isURLSearchParams=kindOfTest("URLSearchParams"),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,o;if(typeof e!="object"&&(e=[e]),isArray$3(e))for(n=0,o=e.length;n{isPlainObject$2(e[n])&&isPlainObject$2(r)?e[n]=merge$2(e[n],r):isPlainObject$2(r)?e[n]=merge$2({},r):isArray$3(r)?e[n]=r.slice():e[n]=r};for(let r=0,n=arguments.length;r(forEach(t,(o,a)=>{r&&isFunction$1(o)?e[a]=bind$1(o,r):e[a]=o},{allOwnKeys:n}),e),stripBOM=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let o,a,l;const c={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),a=o.length;a-- >0;)l=o[a],(!n||n(l,e,t))&&!c[l]&&(t[l]=e[l],c[l]=!0);e=r!==!1&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return n!==-1&&n===r},toArray$2=e=>{if(!e)return null;if(isArray$3(e))return e;let t=e.length;if(!isNumber$1(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&getPrototypeOf(Uint8Array)),forEachEntry=(e,t)=>{const n=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=n.next())&&!o.done;){const a=o.value;t.call(e,a[0],a[1])}},matchAll=(e,t)=>{let r;const n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,function(r,n,o){return n.toUpperCase()+o}),hasOwnProperty$2=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp$1=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,(o,a)=>{t(o,a,e)!==!1&&(n[a]=o)}),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,(t,r)=>{const n=e[r];if(!!isFunction$1(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not read-only method '"+r+"'")})}})},toObjectSet=(e,t)=>{const r={},n=o=>{o.forEach(a=>{r[a]=!0})};return isArray$3(e)?n(e):n(String(e).split(t)),r},noop$5=()=>{},toFiniteNumber=(e,t)=>(e=+e,Number.isFinite(e)?e:t),utils={isArray:isArray$3,isArrayBuffer:isArrayBuffer$1,isBuffer:isBuffer$1,isFormData,isArrayBufferView,isString:isString$1,isNumber:isNumber$1,isBoolean:isBoolean$1,isObject:isObject$1,isPlainObject:isPlainObject$2,isUndefined,isDate:isDate$1,isFile,isBlob,isRegExp:isRegExp$1,isFunction:isFunction$1,isStream,isURLSearchParams,isTypedArray,isFileList,forEach,merge:merge$2,extend,trim,stripBOM,inherits,toFlatObject,kindOf,kindOfTest,endsWith,toArray:toArray$2,forEachEntry,matchAll,isHTMLForm,hasOwnProperty:hasOwnProperty$2,hasOwnProp:hasOwnProperty$2,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase,noop:noop$5,toFiniteNumber};function AxiosError(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o)}utils.inherits(AxiosError,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const prototype$1=AxiosError.prototype,descriptors={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{descriptors[e]={value:e}});Object.defineProperties(AxiosError,descriptors);Object.defineProperty(prototype$1,"isAxiosError",{value:!0});AxiosError.from=(e,t,r,n,o,a)=>{const l=Object.create(prototype$1);return utils.toFlatObject(e,l,function(u){return u!==Error.prototype},c=>c!=="isAxiosError"),AxiosError.call(l,e.message,t,r,n,o),l.cause=e,l.name=e.name,a&&Object.assign(l,a),l};var browser$8=typeof self=="object"?self.FormData:window.FormData;function isVisitable(e){return utils.isPlainObject(e)||utils.isArray(e)}function removeBrackets(e){return utils.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(o,a){return o=removeBrackets(o),!r&&a?"["+o+"]":o}).join(r?".":""):t}function isFlatArray(e){return utils.isArray(e)&&!e.some(isVisitable)}const predicates=utils.toFlatObject(utils,{},null,function(t){return/^is[A-Z]/.test(t)});function isSpecCompliant(e){return e&&utils.isFunction(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator]}function toFormData(e,t,r){if(!utils.isObject(e))throw new TypeError("target must be an object");t=t||new(browser$8||FormData),r=utils.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(T,O){return!utils.isUndefined(O[T])});const n=r.metaTokens,o=r.visitor||b,a=r.dots,l=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&isSpecCompliant(t);if(!utils.isFunction(o))throw new TypeError("visitor must be a function");function _(k){if(k===null)return"";if(utils.isDate(k))return k.toISOString();if(!u&&utils.isBlob(k))throw new AxiosError("Blob is not supported. Use a Buffer instead.");return utils.isArrayBuffer(k)||utils.isTypedArray(k)?u&&typeof Blob=="function"?new Blob([k]):Buffer.from(k):k}function b(k,T,O){let $=k;if(k&&!O&&typeof k=="object"){if(utils.endsWith(T,"{}"))T=n?T:T.slice(0,-2),k=JSON.stringify(k);else if(utils.isArray(k)&&isFlatArray(k)||utils.isFileList(k)||utils.endsWith(T,"[]")&&($=utils.toArray(k)))return T=removeBrackets(T),$.forEach(function(N,H){!utils.isUndefined(N)&&t.append(l===!0?renderKey([T],H,a):l===null?T:T+"[]",_(N))}),!1}return isVisitable(k)?!0:(t.append(renderKey(O,T,a),_(k)),!1)}const x=[],E=Object.assign(predicates,{defaultVisitor:b,convertValue:_,isVisitable});function I(k,T){if(!utils.isUndefined(k)){if(x.indexOf(k)!==-1)throw Error("Circular reference detected in "+T.join("."));x.push(k),utils.forEach(k,function($,D){(!utils.isUndefined($)&&o.call(t,$,utils.isString(D)?D.trim():D,T,E))===!0&&I($,T?T.concat(D):[D])}),x.pop()}}if(!utils.isObject(e))throw new TypeError("data must be an object");return I(e),t}function encode$f(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData(e,this,t)}const prototype=AxiosURLSearchParams.prototype;prototype.append=function(t,r){this._pairs.push([t,r])};prototype.toString=function(t){const r=t?function(n){return t.call(this,n,encode$f)}:encode$f;return this._pairs.map(function(o){return r(o[0])+"="+r(o[1])},"").join("&")};function encode$e(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(e,t,r){if(!t)return e;const n=e.indexOf("#");n!==-1&&(e=e.slice(0,n));const o=r&&r.encode||encode$e,a=utils.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,r).toString(o);return a&&(e+=(e.indexOf("?")===-1?"?":"&")+a),e}class InterceptorManager{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){utils.forEach(this.handlers,function(n){n!==null&&t(n)})}}const transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$2=typeof URLSearchParams<"u"?URLSearchParams:AxiosURLSearchParams,FormData$1=FormData,isStandardBrowserEnv=(()=>{let e;return typeof navigator<"u"&&((e=navigator.product)==="ReactNative"||e==="NativeScript"||e==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),platform={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$2,FormData:FormData$1,Blob},isStandardBrowserEnv,protocols:["http","https","file","blob","url","data"]};function toURLEncodedForm(e,t){return toFormData(e,new platform.classes.URLSearchParams,Object.assign({visitor:function(r,n,o,a){return platform.isNode&&utils.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function parsePropPath(e){return utils.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function arrayToObject(e){const t={},r=Object.keys(e);let n;const o=r.length;let a;for(n=0;n=r.length;return l=!l&&utils.isArray(o)?o.length:l,u?(utils.hasOwnProp(o,l)?o[l]=[o[l],n]:o[l]=n,!c):((!o[l]||!utils.isObject(o[l]))&&(o[l]=[]),t(r,n,o[l],a)&&utils.isArray(o[l])&&(o[l]=arrayToObject(o[l])),!c)}if(utils.isFormData(e)&&utils.isFunction(e.entries)){const r={};return utils.forEachEntry(e,(n,o)=>{t(parsePropPath(n),o,r,0)}),r}return null}function settle(e,t,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new AxiosError("Request failed with status code "+r.status,[AxiosError.ERR_BAD_REQUEST,AxiosError.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}const cookies=platform.isStandardBrowserEnv?function(){return{write:function(r,n,o,a,l,c){const u=[];u.push(r+"="+encodeURIComponent(n)),utils.isNumber(o)&&u.push("expires="+new Date(o).toGMTString()),utils.isString(a)&&u.push("path="+a),utils.isString(l)&&u.push("domain="+l),c===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(r){const n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function isAbsoluteURL(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t){return e&&!isAbsoluteURL(t)?combineURLs(e,t):t}const isURLSameOrigin=platform.isStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");let n;function o(a){let l=a;return t&&(r.setAttribute("href",l),l=r.href),r.setAttribute("href",l),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=o(window.location.href),function(l){const c=utils.isString(l)?o(l):l;return c.protocol===n.protocol&&c.host===n.host}}():function(){return function(){return!0}}();function CanceledError(e,t,r){AxiosError.call(this,e??"canceled",AxiosError.ERR_CANCELED,t,r),this.name="CanceledError"}utils.inherits(CanceledError,AxiosError,{__CANCEL__:!0});function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}const ignoreDuplicateOf=utils.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=e=>{const t={};let r,n,o;return e&&e.split(` -`).forEach(function(l){o=l.indexOf(":"),r=l.substring(0,o).trim().toLowerCase(),n=l.substring(o+1).trim(),!(!r||t[r]&&ignoreDuplicateOf[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t},$internals=Symbol("internals"),$defaults=Symbol("defaults");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return e===!1||e==null?e:String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}function matchHeaderValue(e,t,r,n){if(utils.isFunction(n))return n.call(this,t,r);if(!!utils.isString(t)){if(utils.isString(n))return t.indexOf(n)!==-1;if(utils.isRegExp(n))return n.test(t)}}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function buildAccessors(e,t){const r=utils.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(o,a,l){return this[n].call(this,t,o,a,l)},configurable:!0})})}function findKey(e,t){t=t.toLowerCase();const r=Object.keys(e);let n=r.length,o;for(;n-- >0;)if(o=r[n],t===o.toLowerCase())return o;return null}function AxiosHeaders(e,t){e&&this.set(e),this[$defaults]=t||null}Object.assign(AxiosHeaders.prototype,{set:function(e,t,r){const n=this;function o(a,l,c){const u=normalizeHeader(l);if(!u)throw new Error("header name must be a non-empty string");const _=findKey(n,u);_&&c!==!0&&(n[_]===!1||c===!1)||(utils.isArray(a)?a=a.map(normalizeValue):a=normalizeValue(a),n[_||l]=a)}return utils.isPlainObject(e)?utils.forEach(e,(a,l)=>{o(a,l,t)}):o(t,e,r),this},get:function(e,t){if(e=normalizeHeader(e),!e)return;const r=findKey(this,e);if(r){const n=this[r];if(!t)return n;if(t===!0)return parseTokens(n);if(utils.isFunction(t))return t.call(this,n,r);if(utils.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}},has:function(e,t){if(e=normalizeHeader(e),e){const r=findKey(this,e);return!!(r&&(!t||matchHeaderValue(this,this[r],r,t)))}return!1},delete:function(e,t){const r=this;let n=!1;function o(a){if(a=normalizeHeader(a),a){const l=findKey(r,a);l&&(!t||matchHeaderValue(r,r[l],l,t))&&(delete r[l],n=!0)}}return utils.isArray(e)?e.forEach(o):o(e),n},clear:function(){return Object.keys(this).forEach(this.delete.bind(this))},normalize:function(e){const t=this,r={};return utils.forEach(this,(n,o)=>{const a=findKey(r,o);if(a){t[a]=normalizeValue(n),delete t[o];return}const l=e?formatHeader(o):String(o).trim();l!==o&&delete t[o],t[l]=normalizeValue(n),r[l]=!0}),this},toJSON:function(){const e=Object.create(null);return utils.forEach(Object.assign({},this[$defaults]||null,this),(t,r)=>{t==null||t===!1||(e[r]=utils.isArray(t)?t.join(", "):t)}),e}});Object.assign(AxiosHeaders,{from:function(e){return utils.isString(e)?new this(parseHeaders(e)):e instanceof this?e:new this(e)},accessor:function(e){const r=(this[$internals]=this[$internals]={accessors:{}}).accessors,n=this.prototype;function o(a){const l=normalizeHeader(a);r[l]||(buildAccessors(n,a),r[l]=!0)}return utils.isArray(e)?e.forEach(o):o(e),this}});AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]);utils.freezeMethods(AxiosHeaders.prototype);utils.freezeMethods(AxiosHeaders);function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o=0,a=0,l;return t=t!==void 0?t:1e3,function(u){const _=Date.now(),b=n[a];l||(l=_),r[o]=u,n[o]=_;let x=a,E=0;for(;x!==o;)E+=r[x++],x=x%e;if(o=(o+1)%e,o===a&&(a=(a+1)%e),_-l{const a=o.loaded,l=o.lengthComputable?o.total:void 0,c=a-r,u=n(c),_=a<=l;r=a;const b={loaded:a,total:l,progress:l?a/l:void 0,bytes:c,rate:u||void 0,estimated:u&&l&&_?(l-a)/u:void 0};b[t?"download":"upload"]=!0,e(b)}}function xhrAdapter(e){return new Promise(function(r,n){let o=e.data;const a=AxiosHeaders.from(e.headers).normalize(),l=e.responseType;let c;function u(){e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}utils.isFormData(o)&&platform.isStandardBrowserEnv&&a.setContentType(!1);let _=new XMLHttpRequest;if(e.auth){const I=e.auth.username||"",k=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";a.set("Authorization","Basic "+btoa(I+":"+k))}const b=buildFullPath(e.baseURL,e.url);_.open(e.method.toUpperCase(),buildURL(b,e.params,e.paramsSerializer),!0),_.timeout=e.timeout;function x(){if(!_)return;const I=AxiosHeaders.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),T={data:!l||l==="text"||l==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:I,config:e,request:_};settle(function($){r($),u()},function($){n($),u()},T),_=null}if("onloadend"in _?_.onloadend=x:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(x)},_.onabort=function(){!_||(n(new AxiosError("Request aborted",AxiosError.ECONNABORTED,e,_)),_=null)},_.onerror=function(){n(new AxiosError("Network Error",AxiosError.ERR_NETWORK,e,_)),_=null},_.ontimeout=function(){let k=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const T=e.transitional||transitionalDefaults;e.timeoutErrorMessage&&(k=e.timeoutErrorMessage),n(new AxiosError(k,T.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,e,_)),_=null},platform.isStandardBrowserEnv){const I=(e.withCredentials||isURLSameOrigin(b))&&e.xsrfCookieName&&cookies.read(e.xsrfCookieName);I&&a.set(e.xsrfHeaderName,I)}o===void 0&&a.setContentType(null),"setRequestHeader"in _&&utils.forEach(a.toJSON(),function(k,T){_.setRequestHeader(T,k)}),utils.isUndefined(e.withCredentials)||(_.withCredentials=!!e.withCredentials),l&&l!=="json"&&(_.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&_.addEventListener("progress",progressEventReducer(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&_.upload&&_.upload.addEventListener("progress",progressEventReducer(e.onUploadProgress)),(e.cancelToken||e.signal)&&(c=I=>{!_||(n(!I||I.type?new CanceledError(null,e,_):I),_.abort(),_=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));const E=parseProtocol(b);if(E&&platform.protocols.indexOf(E)===-1){n(new AxiosError("Unsupported protocol "+E+":",AxiosError.ERR_BAD_REQUEST,e));return}_.send(o||null)})}const adapters={http:xhrAdapter,xhr:xhrAdapter},adapters$1={getAdapter:e=>{if(utils.isString(e)){const t=adapters[e];if(!e)throw Error(utils.hasOwnProp(e)?`Adapter '${e}' is not available in the build`:`Can not resolve adapter '${e}'`);return t}if(!utils.isFunction(e))throw new TypeError("adapter is not a function");return e},adapters},DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function getDefaultAdapter(){let e;return typeof XMLHttpRequest<"u"?e=adapters$1.getAdapter("xhr"):typeof process<"u"&&utils.kindOf(process)==="process"&&(e=adapters$1.getAdapter("http")),e}function stringifySafely(e,t,r){if(utils.isString(e))try{return(t||JSON.parse)(e),utils.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}const defaults$1={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(t,r){const n=r.getContentType()||"",o=n.indexOf("application/json")>-1,a=utils.isObject(t);if(a&&utils.isHTMLForm(t)&&(t=new FormData(t)),utils.isFormData(t))return o&&o?JSON.stringify(formDataToJSON(t)):t;if(utils.isArrayBuffer(t)||utils.isBuffer(t)||utils.isStream(t)||utils.isFile(t)||utils.isBlob(t))return t;if(utils.isArrayBufferView(t))return t.buffer;if(utils.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(t,this.formSerializer).toString();if((c=utils.isFileList(t))||n.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return toFormData(c?{"files[]":t}:t,u&&new u,this.formSerializer)}}return a||o?(r.setContentType("application/json",!1),stringifySafely(t)):t}],transformResponse:[function(t){const r=this.transitional||defaults$1.transitional,n=r&&r.forcedJSONParsing,o=this.responseType==="json";if(t&&utils.isString(t)&&(n&&!this.responseType||o)){const l=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(c){if(l)throw c.name==="SyntaxError"?AxiosError.from(c,AxiosError.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils.forEach(["delete","get","head"],function(t){defaults$1.headers[t]={}});utils.forEach(["post","put","patch"],function(t){defaults$1.headers[t]=utils.merge(DEFAULT_CONTENT_TYPE)});function transformData(e,t){const r=this||defaults$1,n=t||r,o=AxiosHeaders.from(n.headers);let a=n.data;return utils.forEach(e,function(c){a=c.call(r,a,o.normalize(),t?t.status:void 0)}),o.normalize(),a}function isCancel(e){return!!(e&&e.__CANCEL__)}function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}function dispatchRequest(e){return throwIfCancellationRequested(e),e.headers=AxiosHeaders.from(e.headers),e.data=transformData.call(e,e.transformRequest),(e.adapter||defaults$1.adapter)(e).then(function(n){return throwIfCancellationRequested(e),n.data=transformData.call(e,e.transformResponse,n),n.headers=AxiosHeaders.from(n.headers),n},function(n){return isCancel(n)||(throwIfCancellationRequested(e),n&&n.response&&(n.response.data=transformData.call(e,e.transformResponse,n.response),n.response.headers=AxiosHeaders.from(n.response.headers))),Promise.reject(n)})}function mergeConfig(e,t){t=t||{};const r={};function n(_,b){return utils.isPlainObject(_)&&utils.isPlainObject(b)?utils.merge(_,b):utils.isPlainObject(b)?utils.merge({},b):utils.isArray(b)?b.slice():b}function o(_){if(utils.isUndefined(t[_])){if(!utils.isUndefined(e[_]))return n(void 0,e[_])}else return n(e[_],t[_])}function a(_){if(!utils.isUndefined(t[_]))return n(void 0,t[_])}function l(_){if(utils.isUndefined(t[_])){if(!utils.isUndefined(e[_]))return n(void 0,e[_])}else return n(void 0,t[_])}function c(_){if(_ in t)return n(e[_],t[_]);if(_ in e)return n(void 0,e[_])}const u={url:a,method:a,data:a,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:c};return utils.forEach(Object.keys(e).concat(Object.keys(t)),function(b){const x=u[b]||o,E=x(b);utils.isUndefined(E)&&x!==c||(r[b]=E)}),r}const VERSION$2="1.1.2",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};validators$1.transitional=function(t,r,n){function o(a,l){return"[Axios v"+VERSION$2+"] Transitional option '"+a+"'"+l+(n?". "+n:"")}return(a,l,c)=>{if(t===!1)throw new AxiosError(o(l," has been removed"+(r?" in "+r:"")),AxiosError.ERR_DEPRECATED);return r&&!deprecatedWarnings[l]&&(deprecatedWarnings[l]=!0,console.warn(o(l," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(a,l,c):!0}};function assertOptions(e,t,r){if(typeof e!="object")throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const a=n[o],l=t[a];if(l){const c=e[a],u=c===void 0||l(c,a,e);if(u!==!0)throw new AxiosError("option "+a+" must be "+u,AxiosError.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new AxiosError("Unknown option "+a,AxiosError.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;class Axios{constructor(t){this.defaults=t,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=mergeConfig(this.defaults,r);const n=r.transitional;n!==void 0&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),r.method=(r.method||this.defaults.method||"get").toLowerCase();const o=r.headers&&utils.merge(r.headers.common,r.headers[r.method]);o&&utils.forEach(["delete","get","head","post","put","patch","common"],function(I){delete r.headers[I]}),r.headers=new AxiosHeaders(r.headers,o);const a=[];let l=!0;this.interceptors.request.forEach(function(I){typeof I.runWhen=="function"&&I.runWhen(r)===!1||(l=l&&I.synchronous,a.unshift(I.fulfilled,I.rejected))});const c=[];this.interceptors.response.forEach(function(I){c.push(I.fulfilled,I.rejected)});let u,_=0,b;if(!l){const E=[dispatchRequest.bind(this),void 0];for(E.unshift.apply(E,a),E.push.apply(E,c),b=E.length,u=Promise.resolve(r);_{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](o);n._listeners=null}),this.promise.then=o=>{let a;const l=new Promise(c=>{n.subscribe(c),a=c}).then(o);return l.cancel=function(){n.unsubscribe(a)},l},t(function(a,l,c){n.reason||(n.reason=new CanceledError(a,l,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}static source(){let t;return{token:new CancelToken(function(o){t=o}),cancel:t}}}function spread(e){return function(r){return e.apply(null,r)}}function isAxiosError(e){return utils.isObject(e)&&e.isAxiosError===!0}function createInstance(e){const t=new Axios(e),r=bind$1(Axios.prototype.request,t);return utils.extend(r,Axios.prototype,t,{allOwnKeys:!0}),utils.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return createInstance(mergeConfig(e,o))},r}const axios=createInstance(defaults$1);axios.Axios=Axios;axios.CanceledError=CanceledError;axios.CancelToken=CancelToken;axios.isCancel=isCancel;axios.VERSION=VERSION$2;axios.toFormData=toFormData;axios.AxiosError=AxiosError;axios.Cancel=axios.CanceledError;axios.all=function(t){return Promise.all(t)};axios.spread=spread;axios.isAxiosError=isAxiosError;axios.formToJSON=e=>formDataToJSON(utils.isHTMLForm(e)?new FormData(e):e);L.DomUtil.setTransform||(L.DomUtil.setTransform=function(e,t,r){var n=t||new L.Point(0,0);e.style[L.DomUtil.TRANSFORM]=(L.Browser.ie3d?"translate("+n.x+"px,"+n.y+"px)":"translate3d("+n.x+"px,"+n.y+"px,0)")+(r?" scale("+r+")":"")});L.CanvasLayer=(L.Layer?L.Layer:L.Class).extend({initialize:function(t){this._map=null,this._canvas=null,this._frame=null,this._delegate=null,L.setOptions(this,t)},delegate:function(t){return this._delegate=t,this},needRedraw:function(){return this._frame||(this._frame=L.Util.requestAnimFrame(this.drawLayer,this)),this},_onLayerDidResize:function(t){this._canvas.width=t.newSize.x,this._canvas.height=t.newSize.y},_onLayerDidMove:function(){var t=this._map.containerPointToLayerPoint([0,0]);L.DomUtil.setPosition(this._canvas,t),this.drawLayer()},getEvents:function(){var t={resize:this._onLayerDidResize,moveend:this._onLayerDidMove};return this._map.options.zoomAnimation&&L.Browser.any3d&&(t.zoomanim=this._animateZoom),t},onAdd:function(t){this._map=t,this._canvas=L.DomUtil.create("canvas","leaflet-layer"),this.tiles={};var r=this._map.getSize();this._canvas.width=r.x,this._canvas.height=r.y;var n=this._map.options.zoomAnimation&&L.Browser.any3d;L.DomUtil.addClass(this._canvas,"leaflet-zoom-"+(n?"animated":"hide")),this.options.pane.appendChild(this._canvas),t.on(this.getEvents(),this);var o=this._delegate||this;o.onLayerDidMount&&o.onLayerDidMount(),this.needRedraw();var a=this;setTimeout(function(){a._onLayerDidMove()},0)},onRemove:function(t){var r=this._delegate||this;r.onLayerWillUnmount&&r.onLayerWillUnmount(),this.options.pane.removeChild(this._canvas),t.off(this.getEvents(),this),this._canvas=null},addTo:function(t){return t.addLayer(this),this},drawLayer:function(){var t=this._map.getSize(),r=this._map.getBounds(),n=this._map.getZoom(),o=this._map.options.crs.project(this._map.getCenter()),a=this._map.options.crs.project(this._map.containerPointToLatLng(this._map.getSize())),l=this._delegate||this;l.onDrawLayer&&l.onDrawLayer({layer:this,canvas:this._canvas,bounds:r,size:t,zoom:n,center:o,corner:a}),this._frame=null},_setTransform:function(t,r,n){var o=r||new L.Point(0,0);t.style[L.DomUtil.TRANSFORM]=(L.Browser.ie3d?"translate("+o.x+"px,"+o.y+"px)":"translate3d("+o.x+"px,"+o.y+"px,0)")+(n?" scale("+n+")":"")},_animateZoom:function(t){var r=this._map.getZoomScale(t.zoom),n=L.Layer?this._map._latLngToNewLayerPoint(this._map.getBounds().getNorthWest(),t.zoom,t.center):this._map._getCenterOffset(t.center)._multiplyBy(-r).subtract(this._map._getMapPanePos());L.DomUtil.setTransform(this._canvas,n,r)}});L.canvasLayer=function(e){return new L.CanvasLayer(e)};L.Control.Velocity=L.Control.extend({options:{position:"bottomleft",emptyString:"Unavailable",angleConvention:"bearingCCW",showCardinal:!1,speedUnit:"m/s",directionString:"Direction",speedString:"Speed",onAdd:null,onRemove:null},onAdd:function(t){return this._container=L.DomUtil.create("div","leaflet-control-velocity"),L.DomEvent.disableClickPropagation(this._container),t.on("mousemove",this._onMouseMove,this),this._container.innerHTML=this.options.emptyString,this.options.leafletVelocity.options.onAdd&&this.options.leafletVelocity.options.onAdd(),this._container},onRemove:function(t){t.off("mousemove",this._onMouseMove,this),this.options.leafletVelocity.options.onRemove&&this.options.leafletVelocity.options.onRemove()},vectorToSpeed:function(t,r,n){var o=Math.sqrt(Math.pow(t,2)+Math.pow(r,2));return n==="k/h"?this.meterSec2kilometerHour(o):n==="kt"?this.meterSec2Knots(o):n==="mph"?this.meterSec2milesHour(o):o},vectorToDegrees:function(t,r,n){n.endsWith("CCW")&&(r=r>0?r=-r:Math.abs(r));var o=Math.sqrt(Math.pow(t,2)+Math.pow(r,2)),a=Math.atan2(t/o,r/o),l=a*180/Math.PI+180;return(n==="bearingCW"||n==="meteoCCW")&&(l+=180,l>=360&&(l-=360)),l},degreesToCardinalDirection:function(t){var r="";return t>=0&&t<11.25||t>=348.75?r="N":t>=11.25&&t<33.75?r="NNW":t>=33.75&&t<56.25?r="NW":t>=56.25&&t<78.75?r="WNW":t>=78.25&&t<101.25?r="W":t>=101.25&&t<123.75?r="WSW":t>=123.75&&t<146.25?r="SW":t>=146.25&&t<168.75?r="SSW":t>=168.75&&t<191.25?r="S":t>=191.25&&t<213.75?r="SSE":t>=213.75&&t<236.25?r="SE":t>=236.25&&t<258.75?r="ESE":t>=258.75&&t<281.25?r="E":t>=281.25&&t<303.75?r="ENE":t>=303.75&&t<326.25?r="NE":t>=326.25&&t<348.75&&(r="NNE"),r},meterSec2Knots:function(t){return t/.514},meterSec2kilometerHour:function(t){return t*3.6},meterSec2milesHour:function(t){return t*2.23694},_onMouseMove:function(t){var r=this,n=this.options.leafletVelocity._map.containerPointToLatLng(L.point(t.containerPoint.x,t.containerPoint.y)),o=this.options.leafletVelocity._windy.interpolatePoint(n.lng,n.lat),a="";if(o&&!isNaN(o[0])&&!isNaN(o[1])&&o[2]){var l=r.vectorToDegrees(o[0],o[1],this.options.angleConvention),c=this.options.showCardinal?" (".concat(r.degreesToCardinalDirection(l),") "):"";a=" ".concat(this.options.velocityType," ").concat(this.options.directionString,": ").concat(l.toFixed(2),"\xB0").concat(c,", ").concat(this.options.velocityType," ").concat(this.options.speedString,": ").concat(r.vectorToSpeed(o[0],o[1],this.options.speedUnit).toFixed(2)," ").concat(this.options.speedUnit)}else a=this.options.emptyString;r._container.innerHTML=a}});L.Map.mergeOptions({positionControl:!1});L.Map.addInitHook(function(){this.options.positionControl&&(this.positionControl=new L.Control.MousePosition,this.addControl(this.positionControl))});L.control.velocity=function(e){return new L.Control.Velocity(e)};L.VelocityLayer=(L.Layer?L.Layer:L.Class).extend({options:{displayValues:!0,displayOptions:{velocityType:"Velocity",position:"bottomleft",emptyString:"No velocity data"},maxVelocity:10,colorScale:null,data:null},_map:null,_canvasLayer:null,_windy:null,_context:null,_timer:0,_mouseControl:null,initialize:function(t){L.setOptions(this,t)},onAdd:function(t){this._paneName=this.options.paneName||"overlayPane";var r=t._panes.overlayPane;t.getPane&&(r=t.getPane(this._paneName),r||(r=t.createPane(this._paneName))),this._canvasLayer=L.canvasLayer({pane:r}).delegate(this),this._canvasLayer.addTo(t),this._map=t},onRemove:function(t){this._destroyWind()},setData:function(t){this.options.data=t,this._windy&&(this._windy.setData(t),this._clearAndRestart()),this.fire("load")},setOpacity:function(t){this._canvasLayer.setOpacity(t)},setOptions:function(t){this.options=Object.assign(this.options,t),t.hasOwnProperty("displayOptions")&&(this.options.displayOptions=Object.assign(this.options.displayOptions,t.displayOptions),this._initMouseHandler(!0)),t.hasOwnProperty("data")&&(this.options.data=t.data),this._windy&&(this._windy.setOptions(t),t.hasOwnProperty("data")&&this._windy.setData(t.data),this._clearAndRestart()),this.fire("load")},onDrawLayer:function(t,r){var n=this;if(!this._windy){this._initWindy(this);return}!this.options.data||(this._timer&&clearTimeout(n._timer),this._timer=setTimeout(function(){n._startWindy()},750))},_startWindy:function(){var t=this._map.getBounds(),r=this._map.getSize();this._windy.start([[0,0],[r.x,r.y]],r.x,r.y,[[t._southWest.lng,t._southWest.lat],[t._northEast.lng,t._northEast.lat]])},_initWindy:function(t){var r=Object.assign({canvas:t._canvasLayer._canvas,map:this._map},t.options);this._windy=new Windy(r),this._context=this._canvasLayer._canvas.getContext("2d"),this._canvasLayer._canvas.classList.add("velocity-overlay"),this.onDrawLayer(),this._map.on("dragstart",t._windy.stop),this._map.on("dragend",t._clearAndRestart),this._map.on("zoomstart",t._windy.stop),this._map.on("zoomend",t._clearAndRestart),this._map.on("resize",t._clearWind),this._initMouseHandler(!1)},_initMouseHandler:function(t){if(t&&(this._map.removeControl(this._mouseControl),this._mouseControl=!1),!this._mouseControl&&this.options.displayValues){var r=this.options.displayOptions||{};r.leafletVelocity=this,this._mouseControl=L.control.velocity(r).addTo(this._map)}},_clearAndRestart:function(){this._context&&this._context.clearRect(0,0,3e3,3e3),this._windy&&this._startWindy()},_clearWind:function(){this._windy&&this._windy.stop(),this._context&&this._context.clearRect(0,0,3e3,3e3)},_destroyWind:function(){this._timer&&clearTimeout(this._timer),this._windy&&this._windy.stop(),this._context&&this._context.clearRect(0,0,3e3,3e3),this._mouseControl&&this._map.removeControl(this._mouseControl),this._mouseControl=null,this._windy=null,this._map.removeLayer(this._canvasLayer)}});L.velocityLayer=function(e){return new L.VelocityLayer(e)};var Windy=function(t){var r=t.minVelocity||0,n=t.maxVelocity||10,o=(t.velocityScale||.005)*(Math.pow(window.devicePixelRatio,1/3)||1),a=t.particleAge||90,l=t.lineWidth||1,c=t.particleMultiplier||1/300,u=Math.pow(window.devicePixelRatio,1/3)||1.6,_=t.frameRate||15,b=1e3/_,x=.97,E=["rgb(36,104, 180)","rgb(60,157, 194)","rgb(128,205,193 )","rgb(151,218,168 )","rgb(198,231,181)","rgb(238,247,217)","rgb(255,238,159)","rgb(252,217,125)","rgb(255,182,100)","rgb(252,150,75)","rgb(250,112,52)","rgb(245,64,32)","rgb(237,45,28)","rgb(220,24,32)","rgb(180,0,35)"],I=t.colorScale||E,k=[NaN,NaN,null],T,O,$=t.data,D,N,H,ie,ue,de,le,ce=function(oe){$=oe},ve=function(oe){oe.hasOwnProperty("minVelocity")&&(r=oe.minVelocity),oe.hasOwnProperty("maxVelocity")&&(n=oe.maxVelocity),oe.hasOwnProperty("velocityScale")&&(o=(oe.velocityScale||.005)*(Math.pow(window.devicePixelRatio,1/3)||1)),oe.hasOwnProperty("particleAge")&&(a=oe.particleAge),oe.hasOwnProperty("lineWidth")&&(l=oe.lineWidth),oe.hasOwnProperty("particleMultiplier")&&(c=oe.particleMultiplier),oe.hasOwnProperty("opacity")&&(x=+oe.opacity),oe.hasOwnProperty("frameRate")&&(_=oe.frameRate),b=1e3/_},ee=function(oe,pe,ke,Ne,ze,Xe){var Je=1-oe,rt=1-pe,qe=Je*rt,Ve=oe*rt,Ae=Je*pe,He=oe*pe,Ge=ke[0]*qe+Ne[0]*Ve+ze[0]*Ae+Xe[0]*He,Ze=ke[1]*qe+Ne[1]*Ve+ze[1]*Ae+Xe[1]*He;return[Ge,Ze,Math.sqrt(Ge*Ge+Ze*Ze)]},he=function(oe,pe){var ke=oe.data,Ne=pe.data;return{header:oe.header,data:function(Xe){return[ke[Xe],Ne[Xe]]},interpolate:ee}},ne=function(oe){var pe=null,ke=null;return oe.forEach(function(Ne){switch(Ne.header.parameterCategory+","+Ne.header.parameterNumber){case"1,2":case"2,2":pe=Ne;break;case"1,3":case"2,3":ke=Ne;break}}),he(pe,ke)},xe=function(oe,pe){var ke=!0;oe.length<2&&(ke=!1),ke||console.log("Windy Error: data must have at least two components (u,v)"),T=ne(oe);var Ne=T.header;if(Ne.hasOwnProperty("gridDefinitionTemplate")&&Ne.gridDefinitionTemplate!=0&&(ke=!1),ke||console.log("Windy Error: Only data with Latitude_Longitude coordinates is supported"),ke=!0,N=Ne.lo1,H=Ne.la1,ie=Ne.dx,ue=Ne.dy,de=Ne.nx,le=Ne.ny,Ne.hasOwnProperty("scanMode")){var ze=Ne.scanMode.toString(2);ze=("0"+ze).slice(-8);var Xe=ze.split("").map(Number).map(Boolean);Xe[0]&&(ie=-ie),Xe[1]&&(ue=-ue),Xe[2]&&(ke=!1),Xe[3]&&(ke=!1),Xe[4]&&(ke=!1),Xe[5]&&(ke=!1),Xe[6]&&(ke=!1),Xe[7]&&(ke=!1),ke||console.log("Windy Error: Data with scanMode: "+Ne.scanMode+" is not supported.")}D=new Date(Ne.refTime),D.setHours(D.getHours()+Ne.forecastTime),O=[];for(var Je=0,rt=Math.floor(de*ie)>=360,qe=0;qe1e3){setTimeout(Ae,25);return}Ue(rt,pe,Ne)})()},Fe,Oe=function(oe,pe){function ke(Ze,$e){return I.indexFor=function(me){return Math.max(0,Math.min(I.length-1,Math.round((me-Ze)/($e-Ze)*(I.length-1))))},I}var Ne=ke(r,n),ze=Ne.map(function(){return[]}),Xe=Math.round(oe.width*oe.height*c);se()&&(Xe*=u);for(var Je="rgba(0, 0, 0, ".concat(x,")"),rt=[],qe=0;qea&&(pe.randomize(Ze).age=0);var $e=Ze.x,me=Ze.y,Ee=pe($e,me),je=Ee[2];if(je===null)Ze.age=a;else{var nt=$e+Ee[0],ot=me+Ee[1];pe(nt,ot)[2]!==null?(Ze.xt=nt,Ze.yt=ot,ze[Ne.indexFor(je)].push(Ze)):(Ze.x=nt,Ze.y=ot)}Ze.age+=1})}var Ae=t.canvas.getContext("2d");Ae.lineWidth=l,Ae.fillStyle=Je,Ae.globalAlpha=.6;function He(){var Ze="lighter";Ae.globalCompositeOperation="destination-in",Ae.fillRect(oe.x,oe.y,oe.width,oe.height),Ae.globalCompositeOperation=Ze,Ae.globalAlpha=x===0?0:x*.9,ze.forEach(function($e,me){$e.length>0&&(Ae.beginPath(),Ae.strokeStyle=Ne[me],$e.forEach(function(Ee){Ae.moveTo(Ee.x,Ee.y),Ae.lineTo(Ee.xt,Ee.yt),Ee.x=Ee.xt,Ee.y=Ee.yt}),Ae.stroke())})}var Ge=Date.now();(function Ze(){Fe=requestAnimationFrame(Ze);var $e=Date.now(),me=$e-Ge;me>b&&(Ge=$e-me%b,Ve(),He())})()},be=function(oe,pe,ke,Ne){var ze={south:fe(Ne[0][1]),north:fe(Ne[1][1]),east:fe(Ne[1][0]),west:fe(Ne[0][0]),width:pe,height:ke};Re(),xe($,function(Xe){Le(Xe,Be(oe,pe,ke),ze,function(Je,rt){Ie.field=rt,Oe(Je,rt)})})},Re=function(){Ie.field&&Ie.field.release(),Fe&&cancelAnimationFrame(Fe)},Ie={params:t,start:be,stop:Re,createField:Ue,interpolatePoint:te,setData:ce,setOptions:ve};return Ie};window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)});const leafletVelocity="";let windLayer;function init$1(){return axios.get(config$2.WIND_PROVIDER).then(e=>{windLayer=L$2.velocityLayer({displayValues:!1,data:e.data,maxVelocity:15,velocityScale:.01,colorScale:["rgb(60,157,194)","rgb(128,205,193)","rgb(250,112,52)","rgb(245,64,32)"]})})}function switchLayer(e,t=!1){windLayer&&(t?e.addLayer(windLayer):e.removeLayer(windLayer))}const _export_sfc=(e,t)=>{const r=e.__vccOpts||e;for(const[n,o]of t)r[n]=o;return r},_sfc_main$f={data(){return{start:hooks().subtract(1,"days").format("YYYY-MM-DD"),end:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),cities:{},city:"",timePeriod:[{title:this.$t("history.currentDay"),value:"24hours"},{title:this.$t("history.currentMonth"),value:"currentMonth"},{title:this.$t("history.chooseDates"),value:"chooseDates"}],period:"24hours"}},computed:{startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.end+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))},link(){return`${config$2.REMOTE_PROVIDER}api/sensor/csv/${this.startTimestamp}/${this.endTimestamp}/${this.city}`}},watch:{period(e){e==="24hours"?(this.start=hooks().format("YYYY-MM-DD"),this.end=hooks().format("YYYY-MM-DD")):e==="currentMonth"&&(this.start=hooks().subtract(1,"month").format("YYYY-MM-DD"),this.end=hooks().format("YYYY-MM-DD"))}},async created(){try{const e=await axios.get(`${config$2.REMOTE_PROVIDER}api/sensor/cities`);this.cities=e.data.result;const t=Object.keys(this.cities),r=Object.keys(this.cities[t[0]]);this.city=this.cities[t[0]][r[0]][0]}catch(e){console.log(e.message)}}},_hoisted_1$e=["action"],_hoisted_2$a=["label"],_hoisted_3$8=["value"],_hoisted_4$6=["value"],_hoisted_5$6={key:0,class:"flexline"},_hoisted_6$6=["max"],_hoisted_7$6=["max"],_hoisted_8$6=["value"];function _sfc_render$f(e,t,r,n,o,a){return openBlock(),createElementBlock("form",{action:a.link},[createBaseVNode("section",null,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[0]||(t[0]=l=>o.city=l),class:"block"},[(openBlock(!0),createElementBlock(Fragment,null,renderList(Object.keys(o.cities),(l,c)=>(openBlock(),createElementBlock("optgroup",{label:l,key:c},[(openBlock(!0),createElementBlock(Fragment,null,renderList(Object.keys(o.cities[l]),(u,_)=>(openBlock(),createElementBlock(Fragment,{key:_},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.cities[l][u],(b,x)=>(openBlock(),createElementBlock("option",{value:b,key:x},toDisplayString$1(b),9,_hoisted_3$8))),128))],64))),128))],8,_hoisted_2$a))),128))],512),[[vModelSelect,o.city]])]),createBaseVNode("section",null,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[1]||(t[1]=l=>o.period=l),class:"block"},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.timePeriod,l=>(openBlock(),createElementBlock("option",{value:l.value,key:l.value},toDisplayString$1(l.title),9,_hoisted_4$6))),128))],512),[[vModelSelect,o.period]])]),o.period==="chooseDates"?(openBlock(),createElementBlock("section",_hoisted_5$6,[withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[2]||(t[2]=l=>o.start=l),max:o.maxDate},null,8,_hoisted_6$6),[[vModelText,o.start]]),createTextVNode(" \u2013 "),withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[3]||(t[3]=l=>o.end=l),max:o.maxDate},null,8,_hoisted_7$6),[[vModelText,o.end]])])):createCommentVNode("",!0),createBaseVNode("section",null,[createBaseVNode("input",{type:"submit",value:e.$t("history.button"),class:"block"},null,8,_hoisted_8$6)])],8,_hoisted_1$e)}const HistoryImport=_export_sfc(_sfc_main$f,[["render",_sfc_render$f]]),_sfc_main$e={props:["current"],data(){return{type:this.current,measurements:Object.entries(measurements),store:useStore()}},computed:{availableunits(){let e=[];return this.store.sensors.forEach(t=>{Object.keys(t.data).forEach(r=>{e.push(r)})}),[...new Set(e)]},availableoptions(){let e=[];return this.availableunits.forEach(t=>{measurements[t]&&e.push({name:measurements[t].label,value:t})}),e}},watch:{type:async function(){await this.$router.push({name:"main",params:{provider:this.$route.params.provider||"realtime",type:this.type,zoom:this.$route.params.zoom,lat:this.$route.params.lat,lng:this.$route.params.lng,sensor:this.$route.params.sensor}}),this.$router.go(0)}}},_hoisted_1$d=["value"];function _sfc_render$e(e,t,r,n,o,a){return o.store.sensors.length>0?withDirectives((openBlock(),createElementBlock("select",{key:0,"onUpdate:modelValue":t[0]||(t[0]=l=>o.type=l)},[(openBlock(!0),createElementBlock(Fragment,null,renderList(a.availableoptions,l=>(openBlock(),createElementBlock("option",{key:l.value,value:l.value},toDisplayString$1(l.name),9,_hoisted_1$d))),128))],512)),[[vModelSelect,o.type]]):createCommentVNode("",!0)}const Measures=_export_sfc(_sfc_main$e,[["render",_sfc_render$e]]);function IDBworkflow(e,t,r,n,o){const a=window.indexedDB||window.webkitIndexedDB;if(!a)return;let l=null;const c=a.open(e,t);c.addEventListener("error",u=>{console.warn(u)}),c.addEventListener("success",u=>{if(l=u.target.result,l.objectStoreNames.contains(r)){let _=l.transaction(r,n);_.addEventListener("error",x=>{console.warn(x)});const b=_.objectStore(r);o(b)}}),c.addEventListener("upgradeneeded",u=>{l=u.target.result;const _=u.oldVersion,b=u.newVersion||l.version;console.log("DB updated from version",_,"to",b),l.objectStoreNames.contains(r)||l.createObjectStore(r,{keyPath:"id",autoIncrement:!0})})}function IDBgettable(e,t,r){return new Promise(n=>{let o=[];IDBworkflow(e,t,r,"readonly",a=>{a.openCursor().addEventListener("success",l=>{const c=l.target.result;c?(o.push(c.value),c.continue()):n(o)})})})}const Bookmarks_vue_vue_type_style_index_0_scoped_972c83b9_lang="",_sfc_main$d={data(){return{bookmarks:[],store:useStore()}},methods:{async getbookmarks(){this.bookmarks=await IDBgettable(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable)},deletebookmark(e){IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",t=>{t.delete(e),this.getbookmarks()})},showsensor(){this.$router.go()}},mounted(){this.getbookmarks();const e=new BroadcastChannel(this.store.idbWatcherBroadcast);e.onmessage=t=>{t.data&&this.getbookmarks()}}},_hoisted_1$c=["href"],_hoisted_2$9={key:0,class:"name"},_hoisted_3$7=["onClick"];function _sfc_render$d(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return!o.bookmarks||o.bookmarks.length<1?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("bookmarks.listempty")),1)],64)):(openBlock(!0),createElementBlock(Fragment,{key:1},renderList(o.bookmarks,c=>(openBlock(),createElementBlock("section",{key:c.id,class:"flexline"},[createBaseVNode("a",{href:c.link,onClick:t[0]||(t[0]=withModifiers((...u)=>a.showsensor&&a.showsensor(...u),["prevent"]))},[c.customName?(openBlock(),createElementBlock("b",_hoisted_2$9,toDisplayString$1(c.customName),1)):createCommentVNode("",!0),c.address?(openBlock(),createElementBlock("b",{key:1,class:normalizeClass(c.customName?"addresssm":"adresslg")},toDisplayString$1(c.address),3)):createCommentVNode("",!0)],8,_hoisted_1$c),createBaseVNode("button",{title:"Remove this sensor",onClick:withModifiers(u=>a.deletebookmark(c.id),["prevent"])},[createVNode(l,{icon:"fa-solid fa-xmark"})],8,_hoisted_3$7)]))),128))}const Bookmarks=_export_sfc(_sfc_main$d,[["render",_sfc_render$d],["__scopeId","data-v-972c83b9"]]),Footer_vue_vue_type_style_index_0_scoped_dd20d5cc_lang="",_sfc_main$c={emits:["history"],props:["currentProvider","canHistory","measuretype"],components:{HistoryImport,Measures,Bookmarks},data(){return{isActive:!1,isActiveMenu:!1,isMeasuresPopupOpen:!1,realtime:this.currentProvider==="realtime",wind:!1,messages:config$2.SHOW_MESSAGES,start:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),store:useStore()}},computed:{startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.start+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))}},watch:{async realtime(e){await this.$router.push({name:"main",params:{provider:e?"realtime":"remote",type:this.$route.params.type,zoom:this.$route.params.zoom,lat:this.$route.params.lat,lng:this.$route.params.lng,sensor:this.$route.params.sensor}}),this.$router.go(0)},start(){this.getHistory()},canHistory:{handler(e){e&&this.getHistory()},immediate:!0},wind(e){switchLayer(instanceMap(),e)},messages(e){switchMessagesLayer(instanceMap(),e)}},methods:{toggleOpen(e){this[e]?(this[e]=!1,this.store.removeColorMap()):(this[e]=!0,this.store.colorMap())},toggleIsActive(){this.toggleOpen("isActive")},toggleMobileMenu(){this.toggleOpen("isActiveMenu")},toggleMeasurePopup(e){e.target.classList.contains("footer__close-popup")&&this.$refs.details.open?this.$refs.details.open=!1:this.toggleOpen("isMeasuresPopupOpen")},getHistory(){this.realtime||this.$emit("history",{start:this.startTimestamp,end:this.endTimestamp})}}},_withScopeId$6=e=>(pushScopeId("data-v-dd20d5cc"),e=e(),popScopeId(),e),_hoisted_1$b={class:"mapcontrols"},_hoisted_2$8={style:{display:"none"}},_hoisted_3$6={class:"flexline"},_hoisted_4$5={id:"bookmarks",class:"popover-bottom-left",popover:""},_hoisted_5$5={class:"popovercontrol",popovertarget:"bookmarks"},_hoisted_6$5=["max","disabled"],_hoisted_7$5={class:"flexline"},_hoisted_8$5={id:"mapsettings",class:"popover-bottom-right",popover:""},_hoisted_9$5=["checked"],_hoisted_10$4={for:"realtime"},_hoisted_11$2=["disabled","checked"],_hoisted_12$2={for:"wind"},_hoisted_13$2=["checked"],_hoisted_14$2={for:"messages"},_hoisted_15$3=_withScopeId$6(()=>createBaseVNode("hr",null,null,-1)),_hoisted_16$2={class:"popovercontrol",popovertarget:"mapsettings"};function _sfc_render$c(e,t,r,n,o,a){const l=resolveComponent("Bookmarks"),c=resolveComponent("font-awesome-icon"),u=resolveComponent("Measures"),_=resolveComponent("HistoryImport");return openBlock(),createElementBlock("div",_hoisted_1$b,[createBaseVNode("div",_hoisted_2$8,toDisplayString$1(e.bufer),1),createBaseVNode("div",_hoisted_3$6,[createBaseVNode("div",_hoisted_4$5,[createBaseVNode("h3",null,toDisplayString$1(e.$t("bookmarks.listtitle")),1),createVNode(l)]),createBaseVNode("button",_hoisted_5$5,[createVNode(c,{icon:"fa-solid fa-bookmark"})]),withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[0]||(t[0]=b=>o.start=b),max:o.maxDate,disabled:r.currentProvider=="realtime"},null,8,_hoisted_6$5),[[vModelText,o.start]]),createVNode(u,{current:r.measuretype.toLowerCase()},null,8,["current"])]),createBaseVNode("div",_hoisted_7$5,[createBaseVNode("div",_hoisted_8$5,[createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"realtime","onUpdate:modelValue":t[1]||(t[1]=b=>o.realtime=b),type:"checkbox",checked:o.realtime},null,8,_hoisted_9$5),[[vModelCheckbox,o.realtime]]),createBaseVNode("label",_hoisted_10$4,toDisplayString$1(e.$t("provider.realtime")),1)]),createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"wind","onUpdate:modelValue":t[2]||(t[2]=b=>o.wind=b),type:"checkbox",disabled:!o.realtime,checked:o.wind&&o.realtime},null,8,_hoisted_11$2),[[vModelCheckbox,o.wind]]),createBaseVNode("label",_hoisted_12$2,toDisplayString$1(e.$t("layer.wind")),1)]),createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"messages","onUpdate:modelValue":t[3]||(t[3]=b=>o.messages=b),type:"checkbox",checked:o.messages},null,8,_hoisted_13$2),[[vModelCheckbox,o.messages]]),createBaseVNode("label",_hoisted_14$2,toDisplayString$1(e.$t("layer.messages")),1)]),_hoisted_15$3,createBaseVNode("section",null,[createBaseVNode("h3",null,toDisplayString$1(e.$t("history.title")),1),createVNode(_)])]),createBaseVNode("button",_hoisted_16$2,[createVNode(c,{icon:"fa-solid fa-gear"})]),renderSlot(e.$slots,"default",{},void 0,!0)])])}const Footer=_export_sfc(_sfc_main$c,[["render",_sfc_render$c],["__scopeId","data-v-dd20d5cc"]]),Map_vue_vue_type_style_index_0_lang="",Map_vue_vue_type_style_index_1_scoped_6ae48b21_lang="",_sfc_main$b={emits:["city","clickMarker","close"],props:["measuretype","historyready","historyhandler"],components:{Footer},data(){return{store:useStore(),locale:localStorage.getItem("locale")||this.$i18n.locale||"en",theme:window?.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",userposition:null,geoavailable:!1}},computed:{zoom(){return this.store.mapposition.zoom},lat(){return this.store.mapposition.lat},lng(){return this.store.mapposition.lng},provider(){return this.$route.params.provider||config$2.DEFAUL_TYPE_PROVIDER}},methods:{themelistener({matches:e,media:t}){!e||(t==="(prefers-color-scheme: dark)"?this.theme="dark":t==="(prefers-color-scheme: light)"&&(this.theme="light"),setTheme(this.theme))},relocatemap(e,t,r,n){const o={name:"main",params:{provider:this.provider||config$2.DEFAUL_TYPE_PROVIDER,type:this.$route.params.type||"pm10",zoom:r,lat:e,lng:t,sensor:this.$route.params.sensor}};this.$router.currentRoute.value.name==="main"&&(console.log(o),n==="reload"?(this.$router.push(o).catch(a=>{console.warn(a)}),setview([e,t],r)):this.$router.replace(o).catch(a=>{console.warn(a)}))},getlocalmappos(){if(localStorage.getItem("map-position")){const e=localStorage.getItem("map-position");this.store.setmapposition(JSON.parse(e).lat,JSON.parse(e).lng,JSON.parse(e).zoom)}},setgeo(){return new Promise(e=>{"geolocation"in navigator?navigator.geolocation.getCurrentPosition(t=>{this.userposition=[t.coords.latitude,t.coords.longitude],this.store.setmapposition(this.userposition[0],this.userposition[1],20),this.geoavailable=!0,e()},t=>{console.warn(`ERROR(${t.code}): ${t.message}`),this.getlocalmappos(),e()}):(this.getlocalmappos(),e())})},resetgeo(){this.setgeo().then(()=>{this.relocatemap(this.lat,this.lng,this.zoom,"reload")})}},unmounted(){removeMap()},async mounted(){window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",this.themelistener),window.matchMedia("(prefers-color-scheme: light)").addEventListener("change",this.themelistener)),this.setgeo().then(async()=>{const t=init$3([this.lat,this.lng],this.zoom,this.theme);this.relocatemap(this.lat,this.lng,this.zoom,"reload"),this.userposition&&drawuser(this.userposition,this.zoom),t.on("zoomend",r=>{this.relocatemap(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom()),this.store.setmapposition(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom())}),t.on("moveend",r=>{this.relocatemap(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom()),this.store.setmapposition(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom())}),init$2(t,this.measuretype,r=>{this.$emit("clickMarker",r)}),this.provider==="realtime"&&await init$1()})}},_hoisted_1$a=["area-label","title"];function _sfc_render$b(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveComponent("Footer");return openBlock(),createElementBlock(Fragment,null,[createBaseVNode("div",{class:normalizeClass([{inactive:o.store.isColored},"mapcontainer"]),id:"map"},null,2),createVNode(c,{currentProvider:a.provider,canHistory:r.historyready,onHistory:r.historyhandler,measuretype:r.measuretype},{default:withCtx(()=>[o.geoavailable?(openBlock(),createElementBlock("button",{key:0,class:"popovercontrol",onClick:t[0]||(t[0]=withModifiers((...u)=>a.resetgeo&&a.resetgeo(...u),["prevent"])),"area-label":e.$t("showlocation"),title:e.$t("showlocation")},[createVNode(l,{icon:"fa-solid fa-location-arrow"})],8,_hoisted_1$a)):createCommentVNode("",!0)]),_:1},8,["currentProvider","canHistory","onHistory","measuretype"])],64)}const Map$1=_export_sfc(_sfc_main$b,[["render",_sfc_render$b],["__scopeId","data-v-6ae48b21"]]),_imports_0$1="/assets/app-icon-512.a5eb7b3f.png",Header_vue_vue_type_style_index_0_scoped_89779538_lang="",_sfc_main$a={data(){return{locale:localStorage.getItem("locale")||this.$i18n.locale||"en",store:useStore()}},watch:{locale(e){this.$i18n.locale=e,localStorage.setItem("locale",e)}},computed:{countPoints(){return this.store.sensors.length}}},_withScopeId$5=e=>(pushScopeId("data-v-89779538"),e=e(),popScopeId(),e),_hoisted_1$9={class:"flexline space-between"},_hoisted_2$7={class:"flexline align-start"},_hoisted_3$5=_withScopeId$5(()=>createBaseVNode("img",{alt:"App logo",src:_imports_0$1},null,-1)),_hoisted_4$4={key:0,class:"text-changabletheme"},_hoisted_5$4={class:"flexline"},_hoisted_6$4=_withScopeId$5(()=>createBaseVNode("option",{value:"en"},"English",-1)),_hoisted_7$4=_withScopeId$5(()=>createBaseVNode("option",{value:"ru"},"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",-1)),_hoisted_8$4=[_hoisted_6$4,_hoisted_7$4],_hoisted_9$4={id:"about",class:"popover-top-right",popover:""},_hoisted_10$3=createStaticVNode('

Web3 \u043E\u0442\u043A\u0440\u044B\u0442\u0430\u044F \u0441\u0435\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432

\u0414\u043E\u0431\u0440\u043E \u043F\u043E\u0436\u0430\u043B\u043E\u0432\u0430\u0442\u044C \u0432 \u043E\u0442\u043A\u0440\u044B\u0442\u0443\u044E \u0441\u0435\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u0430\u044F \u043F\u043E\u0441\u0442\u0440\u043E\u0435\u043D\u0430 \u043D\u0430 open-source \u043F\u0440\u0438\u043D\u0446\u0438\u043F\u0430\u0445 \u0438 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F \u044D\u043D\u0442\u0443\u0437\u0438\u0430\u0441\u0442\u0430\u043C\u0438 (\u0441\u043C. the free will of individuals). \u041A\u0430\u0440\u0442\u0430 \u043F\u0440\u0435\u0434\u043B\u0430\u0433\u0430\u0435\u0442 \u0434\u0432\u0430 \u0440\u0430\u0437\u043D\u044B\u0445 \u0443\u0440\u043E\u0432\u043D\u044F \u0434\u0435\u0446\u0435\u043D\u0442\u0440\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438: \u043F\u0440\u044F\u043C\u0430\u044F peer-to-peer \u0441\u0432\u044F\u0437\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432 \u0438 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D \u0434\u043B\u044F \u0441\u0431\u043E\u0440\u0430 \u0438 \u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u043D\u0438\u0439 \u0441 \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432. \u0422\u0443\u0442 \u043C\u043E\u0436\u043D\u043E \u043E\u0437\u043D\u0430\u043A\u043E\u043C\u0438\u0442\u044C\u0441\u044F \u0431\u043E\u043B\u0435\u0435 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u043E \u0441 \u0442\u0435\u0445\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0441\u0442\u043E\u0440\u043E\u043D\u043E\u0439.

\u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u0441\u0432\u043E\u0439 \u0434\u0430\u0442\u0447\u0438\u043A \u043D\u0430 \u043A\u0430\u0440\u0442\u0443

\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0441\u043E\u0431\u0440\u0430\u0442\u044C \u0441\u0432\u043E\u0439 \u0434\u0430\u0442\u0447\u0438\u043A, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u043A\u043E\u043C\u043F\u043B\u0435\u043A\u0442\u0443\u044E\u0449\u0438\u0435 \u043D\u0430 \u043E\u0442\u043A\u0440\u044B\u0442\u043E\u043C \u0440\u044B\u043D\u043A\u0435 \u044D\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u0438\u043A\u0438, \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A \u043D\u0430 \u043A\u0430\u0440\u0442\u0443. \u041C\u044B \u0441 \u0440\u0430\u0434\u043E\u0441\u0442\u044C\u044E \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u043C \u043D\u043E\u0432\u044B\u0445 \u0443\u0447\u0430\u0441\u0442\u043D\u0438\u043A\u043E\u0432 \u0441\u043E\u043E\u0431\u0449\u0435\u0441\u0442\u0432\u0430. \u041F\u0440\u0438\u0441\u043E\u0435\u0434\u0438\u043D\u044F\u0439\u0442\u0435\u0441\u044C!

\u0412\u0438\u0434\u0435\u043E-\u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u044F \u043D\u0430 YouTube

',5),_hoisted_15$2=createStaticVNode('

Web3 public sensors map

Welcome to the decentralized opensource sensors map which operates with the sole intent of serving the free will of individuals, without any beneficiaries. It offers two distinct layers of decentralization at your choise: peer-to-peer connectivity for direct access to sensor data, and the federative concept for accumulating sensor data and displaying measurement history. Click here for further technical details.

Add your sensor on this map

You can assemble your own sensor using components available on the free market. Follow the instructions provided to connect your sensor to the map. We welcome your participation and look forward to expanding our community together. Join us today!

YouTube video guide

',5),_hoisted_20$2=_withScopeId$5(()=>createBaseVNode("hr",null,null,-1)),_hoisted_21$2={class:"navlinks"},_hoisted_22$2={href:"https://github.com/airalab/sensors.robonomics.network",target:"_blank",rel:"noopener"},_hoisted_23$2={class:"popovercontrol",popovertarget:"about"};function _sfc_render$a(e,t,r,n,o,a){const l=resolveComponent("router-link"),c=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("header",_hoisted_1$9,[createBaseVNode("div",_hoisted_2$7,[createVNode(l,{to:"/",class:"appicon"},{default:withCtx(()=>[_hoisted_3$5]),_:1}),a.countPoints>0?(openBlock(),createElementBlock("b",_hoisted_4$4,toDisplayString$1(e.$t("loadedsesnsors"))+": "+toDisplayString$1(a.countPoints),1)):createCommentVNode("",!0)]),createBaseVNode("div",_hoisted_5$4,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[0]||(t[0]=u=>o.locale=u)},_hoisted_8$4,512),[[vModelSelect,o.locale]]),createBaseVNode("div",_hoisted_9$4,[o.locale==="ru"?(openBlock(),createElementBlock(Fragment,{key:0},[_hoisted_10$3],64)):(openBlock(),createElementBlock(Fragment,{key:1},[_hoisted_15$2],64)),_hoisted_20$2,createBaseVNode("section",_hoisted_21$2,[createBaseVNode("a",_hoisted_22$2,toDisplayString$1(e.$t("links.github")),1),createVNode(l,{to:"/air-measurements"},{default:withCtx(()=>[createTextVNode(toDisplayString$1(e.$t("links.measurement")),1)]),_:1}),createVNode(l,{to:"/privacy-policy"},{default:withCtx(()=>[createTextVNode(toDisplayString$1(e.$t("links.privacy")),1)]),_:1})])]),createBaseVNode("button",_hoisted_23$2,[createVNode(c,{icon:"fa-solid fa-bars"})])])])}const Header=_export_sfc(_sfc_main$a,[["render",_sfc_render$a],["__scopeId","data-v-89779538"]]),_imports_0="/assets/sensors-world-app.8a0828bb.png",InstallPWA_vue_vue_type_style_index_0_scoped_b59a209f_lang="",_sfc_main$9={data(){return{deferredPrompt:null,isSupported:!1,db:null,isInstalled:"loading",isBrowserSupport:!0,browsers:{chrome:!1,safari:!1,firefox:!1,edge:!1,opera:!1}}},methods:{async getDb(){return new Promise((e,t)=>{let r=window.indexedDB.open("SensorsDB",1);r.onerror=n=>{console.log("Error opening db",n),t("Error")},r.onsuccess=n=>{e(n.target.result)},r.onupgradeneeded=n=>{n.target.result.createObjectStore("install",{autoIncrement:!0,keyPath:"id"})}})},async getData(){return new Promise(e=>{let t=this.db.transaction(["install"],"readonly");t.oncomplete=()=>{e(n)};let r=t.objectStore("install"),n=null;r.openCursor().onsuccess=o=>{let a=o.target.result;a&&(n=a.value,a.continue())}})},async addDataToDb(e=!1,t=!1){return new Promise(r=>{let n=this.db.transaction(["install"],"readwrite");n.oncomplete=()=>{r()};let o=n.objectStore("install");o.delete(1),o.add({id:1,removed:e,installed:t})})},async installApp(){if(this.addDataToDb(!1,!0),this.deferredPrompt!==null){this.deferredPrompt.prompt();const{outcome:e}=await this.deferredPrompt.userChoice;e==="accepted"&&(this.deferredPrompt=null,this.isSupported=!1,this.isInstalled="installed")}},removeInstall(){this.addDataToDb(!0,!1),this.isInstalled="removed"},checkBrowser(){let e=navigator.userAgent;this.browsers.chrome=e.indexOf("Chrome")>-1,this.browsers.firefox=e.indexOf("Firefox")>-1,this.browsers.safari=e.indexOf("Safari")>-1,this.browsers.chrome&&this.browsers.safari&&(this.browsers.safari=!1),this.browsers.opera=e.indexOf("OP")>-1,this.browsers.chrome&&this.browsers.opera&&(this.browsers.chrome=!1)}},async created(){this.db=await this.getDb(),this.isInstalled=await this.getData()?await this.getData():null},mounted(){window.addEventListener("beforeinstallprompt",e=>{this.isSupported=!0,this.deferredPrompt=e}),window.matchMedia("(display-mode: standalone)").matches?this.isSupported=!0:this.isSupported=!1,this.checkBrowser(),(this.browsers.safari||this.browsers.firefox||this.browsers.opera)&&(this.isBrowserSupport=!1)}},_withScopeId$4=e=>(pushScopeId("data-v-b59a209f"),e=e(),popScopeId(),e),_hoisted_1$8={key:0,class:"container install-pwa__container"},_hoisted_2$6={class:"install-pwa__content"},_hoisted_3$4=_withScopeId$4(()=>createBaseVNode("img",{src:_imports_0,alt:"sensors-cy-app"},null,-1)),_hoisted_4$3={class:"install-pwa__text"},_hoisted_5$3=_withScopeId$4(()=>createBaseVNode("h3",null,"Available as web application (PWA)",-1));function _sfc_render$9(e,t,r,n,o,a){return!o.isInstalled&&o.isBrowserSupport?(openBlock(),createElementBlock("div",_hoisted_1$8,[createBaseVNode("div",_hoisted_2$6,[_hoisted_3$4,createBaseVNode("div",_hoisted_4$3,[_hoisted_5$3,createBaseVNode("button",{onClick:t[0]||(t[0]=(...l)=>a.installApp&&a.installApp(...l)),class:"install-pwa__btn"},"Install")])]),createBaseVNode("button",{onClick:t[1]||(t[1]=(...l)=>a.removeInstall&&a.removeInstall(...l)),class:"install-pwa__remove"})])):createCommentVNode("",!0)}const InstallPWA=_export_sfc(_sfc_main$9,[["render",_sfc_render$9],["__scopeId","data-v-b59a209f"]]),MessagePopup_vue_vue_type_style_index_0_scoped_c5bfb7c2_lang="";function preloadImages(e,t){let r=0;const n={};function o(){if(r++,r==e.length){const a=[],l=[];for(const c of e)n[c]&&n[c]>0?(console.log(`Bad image ${c}`),l.push(c)):a.push(c);t(a,l)}}for(let a of e){let l=document.createElement("img");l.onload=()=>{n[a]=0,o()},l.onerror=()=>{n[a]||(n[a]=0),n[a]++,n[a]<3?l.src=a:o()},l.src=a}}const _sfc_main$8={props:["data"],data(){return{isImages:!1,images:[],badImages:[],imagesLoaded:!1,state:"neutral"}},computed:{dateMsg:function(){return hooks(this.data.timestamp,"X").format("DD.MM.YYYY HH:mm:ss")},classList(){return{["sensor-popup__header"]:!0,[`sensor-popup__header--${this.state}`]:this.state}}},watch:{data(){this.imagesLoad()}},created(){this.imagesLoad()},methods:{replaceWithBr(e){return e.replace(/\n/g,"
")},imagesLoad(){if(this.data.images&&this.data.images.length>0){this.images=[],this.badImages=[],this.imagesLoaded=!1,this.isImages=!0;const e=this.data.images.map(t=>`https://aira.mypinata.cloud/ipfs/${this.data.ipfs}/${t}`);preloadImages(e,(t,r)=>{t.length>0&&(this.images=t),r.length>0&&(this.badImages=r),this.imagesLoaded=!0})}else this.isImages=!1,this.images=[],this.badImages=[],this.imagesLoaded=!1}}},_hoisted_1$7={class:"container sensor-popup sensors-panel sensors-panel--center-right active popup-js"},_hoisted_2$5={class:"sensor-popup__header-icon"},_hoisted_3$3={class:"sensor-popup__header-wrapper"},_hoisted_4$2={class:"sensor-popup--subtitle"},_hoisted_5$2={ref:"content",class:"sensor-popup--content"},_hoisted_6$3=["innerHTML"],_hoisted_7$3={key:0},_hoisted_8$3=["href"],_hoisted_9$3=["src"],_hoisted_10$2=["href"];function _sfc_render$8(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("div",_hoisted_1$7,[createBaseVNode("div",{class:normalizeClass(a.classList)},[createBaseVNode("div",_hoisted_2$5,[createVNode(l,{icon:"fa-solid fa-face-meh"})]),createBaseVNode("div",_hoisted_3$3,[createBaseVNode("h2",null,toDisplayString$1(e.$t("details.user"))+" "+toDisplayString$1(r.data.username),1),createBaseVNode("div",_hoisted_4$2,[createBaseVNode("span",null,[createVNode(l,{icon:"fa-solid fa-stopwatch"}),createTextVNode(" "+toDisplayString$1(a.dateMsg),1)])])])],2),createBaseVNode("div",_hoisted_5$2,[createBaseVNode("div",{innerHTML:a.replaceWithBr(r.data.message)},null,8,_hoisted_6$3),o.isImages?(openBlock(),createElementBlock(Fragment,{key:0},[createBaseVNode("h2",null,toDisplayString$1(e.$t("details.photos")),1),o.imagesLoaded?(openBlock(),createElementBlock(Fragment,{key:1},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.images,(c,u)=>(openBlock(),createElementBlock("div",{key:u},[createBaseVNode("a",{href:c,target:"_blank"},[createBaseVNode("img",{style:{"max-width":"400px"},src:c},null,8,_hoisted_9$3)],8,_hoisted_8$3)]))),128)),createBaseVNode("template",null,[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.badImages,(c,u)=>(openBlock(),createElementBlock("a",{key:u,href:c,target:"_blank"},toDisplayString$1(c),9,_hoisted_10$2))),128))])],64)):(openBlock(),createElementBlock("div",_hoisted_7$3,"..."))],64)):createCommentVNode("",!0)],512),createBaseVNode("a",{class:"popup__close",href:"javascript:;",onClick:t[0]||(t[0]=withModifiers(c=>e.$emit("close"),["stop","prevent"]))},[createVNode(l,{icon:"fa-solid fa-xmark"})])])}const MessagePopup=_export_sfc(_sfc_main$8,[["render",_sfc_render$8],["__scopeId","data-v-c5bfb7c2"]]),Bookmark_vue_vue_type_style_index_0_scoped_8cca7f79_lang="",_sfc_main$7={props:["address","link"],data(){return{IsBookmarked:!1,db:null,bookmarks:[],bookmarkid:null,bookmarkname:"",store:useStore()}},computed:{buttonclasses(){return{button:!0,["button-green"]:this.IsBookmarked}}},methods:{async findbookmark(){return(await IDBgettable(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable)).find(t=>t.address===this.$props.address)},async addbookmark(){await this.findbookmark()?this.bookmarkid&&IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",r=>{const n=r.get(this.bookmarkid);n.addEventListener("error",o=>{console.log(o)}),n.addEventListener("success",o=>{const a=o.target.result;a.customName=this.bookmarkname;const l=r.put(a);l.addEventListener("error",c=>{console.log(c)}),l.addEventListener("success",c=>{this.IsBookmarked=!0})})}):IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",r=>{r.add({customName:this.bookmarkname,address:this.$props.address,link:this.$props.link}),this.IsBookmarked=!0});const t=new BroadcastChannel(this.store.idbWatcherBroadcast);t.postMessage(!0),t.close()}},async mounted(){const e=await this.findbookmark();e&&(this.IsBookmarked=!0,this.bookmarkid=e.id,this.bookmarkname=e.customName)}},_hoisted_1$6=["placeholder"],_hoisted_2$4=["disabled","area-label"];function _sfc_render$7(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("form",{class:"flexline",onSubmit:t[2]||(t[2]=withModifiers((...c)=>a.addbookmark&&a.addbookmark(...c),["prevent"]))},[withDirectives(createBaseVNode("input",{type:"text","onUpdate:modelValue":t[0]||(t[0]=c=>o.bookmarkname=c),placeholder:e.$t("sensorpopup.bookmarkplaceholder"),onInput:t[1]||(t[1]=c=>o.IsBookmarked=!1)},null,40,_hoisted_1$6),[[vModelText,o.bookmarkname]]),createBaseVNode("button",{class:normalizeClass(a.buttonclasses),disabled:o.IsBookmarked,"area-label":e.$t("sensorpopup.bookmarkbutton")},[o.IsBookmarked?(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-check"})):(openBlock(),createBlock(l,{key:0,icon:"fa-solid fa-bookmark"}))],10,_hoisted_2$4)],32)}const Bookmark=_export_sfc(_sfc_main$7,[["render",_sfc_render$7],["__scopeId","data-v-8cca7f79"]]),Chart_vue_vue_type_style_index_0_lang="",_sfc_main$6={props:["log","measurement","sensor_id","model","type","units"],data(){const e=this;return{datacollection:null,options:{title:!1,chart:{type:"spline",height:400},xAxis:{type:"datetime",labels:{formatter:function(){return hooks(this.value,"X").format("HH:mm")}},title:!1},yAxis:{title:!1},tooltip:{shared:!0,crosshairs:!0,formatter:function(){if(e.model===3){const r=e.log.find(n=>n.timestamp===this.x);moveMarkerTime(e.sensor_id,r)}let t="";return this.points.forEach(r=>{t+=""+r.series.name+" = "+r.y+"
"}),""+hooks(this.x,"X").format("DD.MM.YYYY HH:mm:ss")+"
"+t}},plotOptions:{series:{events:{mouseOut:function(){if(e.model===3){const t=e.log[e.log.length-1];moveMarkerTime(e.sensor_id,t,!0)}},legendItemClick:function(t){let r=t;if(t||(r=e.store.currentActiveMeasure),t.target){r=t.target.name;let n=t.target.name;r==="temperature"?n="tmp":r==="humidity"&&(n="hm"),e.store.selectCurrentActiveMeasure(n.toUpperCase(),!0)}if(r){r==="TMP"?r="temperature":r==="HM"&&(r="humidity");const n=e.series.filter(o=>o.name===r.replace(".","").toLowerCase());e.toggleTabState(n[0])}}}}},series:[]},store:useStore()}},computed:{series:function(){if(this.log.length>0&&this.units&&this.units.length>0){const e=this.units.map(n=>n.toLowerCase()),t=[];for(let n of e)t.push({visible:n===this.measurement,name:n,zones:measurements[n.toLowerCase()]?.zones,lineWidth:1,data:[],options:{name:n}});return!t.find(n=>n.visible===!0)&&t.length>0&&(t[0].visible=!0),t}return[{name:this.measurement,color:"#e8b738",lineWidth:1,data:[],options:{name:this.measurement}}]},storeMeasures(){return this.store.currentActiveMeasure}},watch:{sensor_id:function(){this.fillData()},measurement:function(){this.fillData()},log:{immediate:!1,handler:function(e){this.fillData(),this.$nextTick(()=>{const t=this.$refs.chart.chart.series[0].points.length-e.length;if(t<0){let r=[this.measurement];(this.measurement==="pm10"||this.measurement==="pm25")&&(r=["pm10","pm25"]);const n=e.slice(t);for(const o in r)for(let a of n)this.addPoint(o,[Number(a.timestamp),Number(a.data[r[o]])])}})}},storeMeasures:{handler:function(){this.options.plotOptions.series.events.legendItemClick(this.store.currentActiveMeasure)},deep:!0}},methods:{fillData(){const e=this.series;for(const t in e)e[t].data=this.log.map(r=>(r.data=Object.fromEntries(Object.entries(r.data).map(([n,o])=>[n.toLowerCase(),o])),[Number(r.timestamp),Number(r.data[e[t].options.name])]));if(this.options.series=e,!this.store.currentActiveMeasure&&!this.$props.type&&this.store.selectCurrentActiveMeasure(this.options.series[0].name.toUpperCase(),!0),!this.store.currentActiveMeasure&&this.$props.type){let t=this.$props.type;this.$props.type==="temperature"?t="tmp":this.$props.type==="humidity"&&(t="hm"),this.store.selectCurrentActiveMeasure(t.toUpperCase(),!0)}},addPoint(e,t){this.$refs.chart.chart.series[e].addPoint(t,!0,!1)},toggleTabState(e){const t=this.$refs.chart.chart.series.filter(r=>r.name===e.name);this.$refs.chart.chart.series.length&&(this.$refs.chart.chart.series[t[0].index].name==="temperature"?this.store.addToggleState("TMP"):this.$refs.chart.chart.series[t[0].index].name==="humidity"?this.store.addToggleState("HM"):this.store.addToggleState(this.$refs.chart.chart.series[t[0].index].name.toUpperCase().replace(".","")),this.$refs.chart.chart.series[t[0].index].visible?this.$refs.chart.chart.series[t[0].index].hide():this.$refs.chart.chart.series[t[0].index].show())}},mounted(){this.fillData()}},_hoisted_1$5={style:{margin:"20px 0"}};function _sfc_render$6(e,t,r,n,o,a){const l=resolveComponent("highcharts");return openBlock(),createElementBlock("div",_hoisted_1$5,[createVNode(l,{options:o.options,ref:"chart"},null,8,["options"])])}const Chart=_export_sfc(_sfc_main$6,[["render",_sfc_render$6]]),Copy_vue_vue_type_style_index_0_scoped_951f909f_lang="",_sfc_main$5={props:["msg","title","notify"],data(){return{successCopy:!1}},methods:{success(){this.$notify({position:"top right",text:this.notify})},showSuccessesCopy(){this.successCopy=!0,setTimeout(()=>{this.successCopy=!1},2e3)}}},_hoisted_1$4=["title"];function _sfc_render$5(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveDirective("clipboard");return withDirectives((openBlock(),createElementBlock("a",{class:"nowrap copy",title:r.title},[renderSlot(e.$slots,"default",{},void 0,!0),o.successCopy?createCommentVNode("",!0):(openBlock(),createElementBlock("button",{key:0,class:"copy-btn",onClick:t[0]||(t[0]=(...u)=>a.showSuccessesCopy&&a.showSuccessesCopy(...u))})),o.successCopy?(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-check"})):createCommentVNode("",!0)],8,_hoisted_1$4)),[[c,r.msg,"copy"],[c,a.success,"success"]])}const Copy=_export_sfc(_sfc_main$5,[["render",_sfc_render$5],["__scopeId","data-v-951f909f"]]),SensorPopup_vue_vue_type_style_index_0_scoped_ca9b2801_lang="",_sfc_main$4={emits:["close"],props:["type","point"],components:{Chart,Copy,Bookmark},data(){return{select:"",measurement:this.type,isShowPath:!1,store:useStore(),start:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),provider:this.$route.params.provider,rttime:null,rtdata:[]}},computed:{locale(){return localStorage.getItem("locale")||this.$i18n.locale||"en"},address(){return this.point.address},donated_by(){return this.point.donated_by},geo(){return this.point.geo},log(){return this.point?.log},model(){return this.point.model},sender(){return this.point.sender},sensor_id(){return this.point.sensor_id},realtime(){return this.provider==="realtime"},addressformatted(){let e="";return this.address.country&&(e+=this.address.country),this.address.address.length>0&&(e+=", "+this.address.address.join(", ")),e},isLocationRussion(){return this.address.country==="\u0420\u043E\u0441\u0441\u0438\u044F"||this.address.country==="Russia"},measure(){return this.items.find(e=>this.select===e.text)},scale(){return generate$1(measurements[this.type.toLowerCase()].colors,measurements[this.type.toLowerCase()].range)},hasIcon(){return e=>measurements[e.toLowerCase()]&&measurements[e.toLowerCase()].icon},icon:function(){return e=>this.hasIcon(e)?measurements[e.toLowerCase()].icon:"vial"},items(){const e=[];for(const t of Object.keys(this.last.data)){let r=null;measurements[t.toLowerCase()]&&measurements[t.toLowerCase()].colors&&(r=generate$1(measurements[t.toLowerCase()].colors,measurements[t.toLowerCase()].range)),e.push({id:t,title:this.$filters.measurementFormat(this.last.data[t],t),text:this.$filters.measurement(t),state:getState(r,this.last.data[t],measurements[t.toLowerCase()]?measurements[t.toLowerCase()].states:void 0)})}return e},measurementFilter(e){return measurements[e.toLowerCase()]?.label||e},measurementFormat(e,t){return measurements[t.toLowerCase()]?`${toFixed(e)} ${measurements[t.toLowerCase()].unit}`:toFixed(e)},collapse(e){return e?e.slice(0,6)+"..."+e.slice(-4):""},linkSensor:function(){const e=this.$router.resolve({name:"main",params:{provider:this.$route.params.provider||config$2.DEFAUL_TYPE_PROVIDER,type:this.$route.params.type||"pm10",zoom:this.$route.params.zoom||config$2.MAP.zoom,lat:this.geo.lat,lng:this.geo.lng,sensor:this.sensor_id}});return new URL(e.href,window.location.origin).href},link:function(){return sensors[this.sensor_id]?sensors[this.sensor_id].link:""},icon:function(){return sensors[this.sensor_id]?sensors[this.sensor_id].icon:""},last:function(){return this.log[this.log.length-1]},date:function(){return hooks(this.last.timestamp,"X").format("DD.MM.YYYY HH:mm:ss")},startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.start+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))},sharable:function(){return navigator.share&&navigator.canShare},units(){let e=[];return Object.values(this.log).forEach(t=>{Object.keys(t.data).forEach(r=>{e.push(r)})}),[...new Set(e.flat())]},scales:function(){let e=[];return Object.keys(measurements).forEach(t=>{this.units.some(r=>r===t)&&e.push(measurements[t])}),e}},methods:{shareData(){navigator.share({title:"Public Sensor Map",url:this.linkSensor?this.linkSensor:this.link}).then(()=>{console.log("Shared")}).catch(console.error)},getHistory(){this.realtime||this.$emit("history",{sensor_id:this.sensor_id,start:this.startTimestamp,end:this.endTimestamp})},updatert(){if(this.realtime){const e=this.log[this.log.length-1].timestamp*1e3;e&&(this.rttime=new Date(e).toLocaleString());const t=this.log[this.log.length-1].data;let r={};t&&(this.rtdata=[],Object.keys(measurements).forEach(n=>{Object.keys(t).forEach(o=>{n===o&&(r={},r.key=o,r.measure=t[o],r.label=measurements[n].label,r.unit=measurements[n].unit,measurements[n].zones.find(a=>r.measurer.measuremeasurements[n].zones[measurements[n].zones.length-2].value&&(r.color=measurements[n].zones[measurements[n].zones.length-1].color),this.rtdata.push(r))})}))}}},watch:{sensor_id(){this.isShowPath=!1},isShowPath(){this.isShowPath?showPath(this.sensor_id):hidePath(this.sensor_id)},start(){this.getHistory()},log(){this.updatert()}},mounted(){this.updatert()}},_withScopeId$3=e=>(pushScopeId("data-v-ca9b2801"),e=e(),popScopeId(),e),_hoisted_1$3={class:"popup-js active"},_hoisted_2$3={class:"flexline clipoverflow"},_hoisted_3$2=["src"],_hoisted_4$1={class:"scrollable-y"},_hoisted_5$1={class:"flexline space-between"},_hoisted_6$2={class:"flexline"},_hoisted_7$2=["max"],_hoisted_8$2={key:0,class:"flexline"},_hoisted_9$2=_withScopeId$3(()=>createBaseVNode("div",{class:"rt-title"},"Realtime view mode",-1)),_hoisted_10$1={key:0,class:"rt-time"},_hoisted_11$1={class:"rt-unit"},_hoisted_12$1={key:0,class:"infoline flexline"},_hoisted_13$1={class:"infoline-title"},_hoisted_14$1={class:"infoline-info"},_hoisted_15$1={key:1,class:"infoline flexline"},_hoisted_16$1={class:"infoline-title"},_hoisted_17$1={class:"infoline-info"},_hoisted_18$1={key:2,class:"infoline flexline"},_hoisted_19$1={class:"infoline-title"},_hoisted_20$1={class:"infoline-info"},_hoisted_21$1=["href"],_hoisted_22$1={key:3,class:"infoline flexline"},_hoisted_23$1={class:"infoline-title"},_hoisted_24$1={class:"infoline-info"},_hoisted_25$1={key:4,class:"infoline flexline"},_hoisted_26$1={class:"infoline-title"},_hoisted_27$1=_withScopeId$3(()=>createBaseVNode("label",{for:"realtime"},null,-1)),_hoisted_28$1={class:"sensors-switcher-text"},_hoisted_29$1={class:"infoline-info"},_hoisted_30$1={key:1},_hoisted_31$1={class:"scalegrid"},_hoisted_32$1={key:0},_hoisted_33$1={key:1},_hoisted_34$1={class:"textsmall"};function _sfc_render$4(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveComponent("Bookmark"),u=resolveComponent("Chart"),_=resolveComponent("Copy");return openBlock(),createElementBlock("div",_hoisted_1$3,[createBaseVNode("section",null,[createBaseVNode("h3",_hoisted_2$3,[a.icon?(openBlock(),createElementBlock("img",{key:0,src:a.icon,class:"icontitle"},null,8,_hoisted_3$2)):(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-location-dot"})),createTextVNode(" "+toDisplayString$1(a.addressformatted),1)])]),createBaseVNode("div",_hoisted_4$1,[createBaseVNode("section",_hoisted_5$1,[createBaseVNode("div",_hoisted_6$2,[a.realtime?createCommentVNode("",!0):withDirectives((openBlock(),createElementBlock("input",{key:0,type:"date","onUpdate:modelValue":t[0]||(t[0]=b=>o.start=b),max:o.maxDate},null,8,_hoisted_7$2)),[[vModelText,o.start]]),createVNode(c,{address:a.address.address&&a.address.address.join(", "),link:a.linkSensor},null,8,["address","link"])]),a.sharable?(openBlock(),createElementBlock("button",{key:0,onClick:t[1]||(t[1]=(...b)=>a.shareData&&a.shareData(...b)),class:"button"},[createVNode(l,{icon:"fa-solid fa-share-from-square"})])):createCommentVNode("",!0)]),a.realtime?(openBlock(),createElementBlock("section",_hoisted_8$2,[createBaseVNode("div",null,[_hoisted_9$2,o.rttime?(openBlock(),createElementBlock("div",_hoisted_10$1,toDisplayString$1(o.rttime),1)):createCommentVNode("",!0)]),o.rtdata?(openBlock(!0),createElementBlock(Fragment,{key:0},renderList(o.rtdata,b=>(openBlock(),createElementBlock("div",{key:b},[createBaseVNode("div",_hoisted_11$1,toDisplayString$1(b.label),1),createBaseVNode("div",{class:"rt-number",style:normalizeStyle(b.color?"color:"+b.color:"")},toDisplayString$1(b.measure)+" "+toDisplayString$1(b.unit),5)]))),128)):createCommentVNode("",!0)])):createCommentVNode("",!0),createBaseVNode("section",null,[a.log.length>0?(openBlock(),createBlock(u,{key:0,model:a.model,log:a.log,measurement:o.measurement,sensor_id:a.sensor_id,type:r.type,units:a.units},null,8,["model","log","measurement","sensor_id","type","units"])):createCommentVNode("",!0)]),createBaseVNode("section",null,[createBaseVNode("h3",null,toDisplayString$1(e.$t("sensorpopup.infotitle")),1),a.sensor_id?(openBlock(),createElementBlock("div",_hoisted_12$1,[createBaseVNode("div",_hoisted_13$1,toDisplayString$1(e.$t("sensorpopup.infosensorid"))+":",1),createBaseVNode("div",_hoisted_14$1,[createTextVNode(toDisplayString$1(e.$filters.collapse(a.sensor_id))+" ",1),createVNode(_,{msg:a.sensor_id,title:`Sensor id: ${a.sensor_id}`,notify:e.$t("details.copied")},null,8,["msg","title","notify"])])])):createCommentVNode("",!0),a.geo?(openBlock(),createElementBlock("div",_hoisted_15$1,[createBaseVNode("div",_hoisted_16$1,toDisplayString$1(e.$t("sensorpopup.infosensorgeo"))+":",1),createBaseVNode("div",_hoisted_17$1,toDisplayString$1(a.geo.lat)+", "+toDisplayString$1(a.geo.lng),1)])):createCommentVNode("",!0),a.link?(openBlock(),createElementBlock("div",_hoisted_18$1,[createBaseVNode("div",_hoisted_19$1,toDisplayString$1(e.$t("sensorpopup.infosensorowner"))+":",1),createBaseVNode("div",_hoisted_20$1,[createBaseVNode("a",{href:a.link,rel:"noopener",target:"_blank"},toDisplayString$1(a.link),9,_hoisted_21$1)])])):createCommentVNode("",!0),a.donated_by?(openBlock(),createElementBlock("div",_hoisted_22$1,[createBaseVNode("div",_hoisted_23$1,toDisplayString$1(e.$t("sensorpopup.infosensordonated"))+":",1),createBaseVNode("div",_hoisted_24$1,toDisplayString$1(a.donated_by),1)])):createCommentVNode("",!0),a.model===3?(openBlock(),createElementBlock("div",_hoisted_25$1,[createBaseVNode("div",_hoisted_26$1,[_hoisted_27$1,createBaseVNode("span",_hoisted_28$1,toDisplayString$1(e.$t("details.showpath")),1),createTextVNode(":")]),createBaseVNode("div",_hoisted_29$1,[withDirectives(createBaseVNode("input",{type:"checkbox",id:"realtime","onUpdate:modelValue":t[2]||(t[2]=b=>o.isShowPath=b)},null,512),[[vModelCheckbox,o.isShowPath]])])])):createCommentVNode("",!0)]),a.units&&a.scales&&a.scales.length>0?(openBlock(),createElementBlock("section",_hoisted_30$1,[createBaseVNode("h3",null,toDisplayString$1(e.$t("scales.title")),1),createBaseVNode("div",_hoisted_31$1,[(openBlock(!0),createElementBlock(Fragment,null,renderList(a.scales,b=>(openBlock(),createElementBlock("div",{key:b.label},[b?.zones&&(b.name||b.label)?(openBlock(),createElementBlock(Fragment,{key:0},[createBaseVNode("p",null,[b.name?(openBlock(),createElementBlock("b",_hoisted_32$1,toDisplayString$1(a.locale==="en"?b.name.en:b.name.ru),1)):(openBlock(),createElementBlock("b",_hoisted_33$1,toDisplayString$1(b.label),1)),createTextVNode(" ("+toDisplayString$1(b.unit)+") ",1)]),(openBlock(!0),createElementBlock(Fragment,null,renderList(b.zones,x=>(openBlock(),createElementBlock(Fragment,{key:x.color},[x.color&&x.label?(openBlock(),createElementBlock("div",{key:0,class:"scales-color",style:normalizeStyle(`--color: ${x.color}`)},[createBaseVNode("b",null,toDisplayString$1(a.locale==="en"?x.label.en:x.label.ru),1),createTextVNode(" ("),x.value?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("scales.upto"))+" "+toDisplayString$1(x.value),1)],64)):(openBlock(),createElementBlock(Fragment,{key:1},[createTextVNode(toDisplayString$1(e.$t("scales.above")),1)],64)),createTextVNode(") ")],4)):createCommentVNode("",!0)],64))),128))],64)):createCommentVNode("",!0)]))),128))])])):createCommentVNode("",!0),createBaseVNode("div",_hoisted_34$1,[a.isLocationRussion?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("notice_with_fz")),1)],64)):(openBlock(),createElementBlock(Fragment,{key:1},[createTextVNode(toDisplayString$1(e.$t("notice_without_fz")),1)],64))])]),createBaseVNode("button",{onClick:t[3]||(t[3]=withModifiers(b=>e.$emit("close"),["prevent"])),"aria-label":"Close sensor",class:"close"},[createVNode(l,{icon:"fa-solid fa-xmark"})])])}const SensorPopup=_export_sfc(_sfc_main$4,[["render",_sfc_render$4],["__scopeId","data-v-ca9b2801"]]);function asUint8Array(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function alloc(e=0){return globalThis.Buffer?.alloc!=null?asUint8Array(globalThis.Buffer.alloc(e)):new Uint8Array(e)}function allocUnsafe$2(e=0){return globalThis.Buffer?.allocUnsafe!=null?asUint8Array(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}const N1$2=Math.pow(2,7),N2$2=Math.pow(2,14),N3$2=Math.pow(2,21),N4$2=Math.pow(2,28),N5$2=Math.pow(2,35),N6$2=Math.pow(2,42),N7$2=Math.pow(2,49),MSB$4=128,REST$4=127;function encodingLength$2(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function encodeUint8Array(e,t,r=0){switch(encodingLength$2(e)){case 8:t[r++]=e&255|MSB$4,e/=128;case 7:t[r++]=e&255|MSB$4,e/=128;case 6:t[r++]=e&255|MSB$4,e/=128;case 5:t[r++]=e&255|MSB$4,e/=128;case 4:t[r++]=e&255|MSB$4,e>>>=7;case 3:t[r++]=e&255|MSB$4,e>>>=7;case 2:t[r++]=e&255|MSB$4,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function encodeUint8ArrayList(e,t,r=0){switch(encodingLength$2(e)){case 8:t.set(r++,e&255|MSB$4),e/=128;case 7:t.set(r++,e&255|MSB$4),e/=128;case 6:t.set(r++,e&255|MSB$4),e/=128;case 5:t.set(r++,e&255|MSB$4),e/=128;case 4:t.set(r++,e&255|MSB$4),e>>>=7;case 3:t.set(r++,e&255|MSB$4),e>>>=7;case 2:t.set(r++,e&255|MSB$4),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function decodeUint8Array(e,t){let r=e[t],n=0;if(n+=r&REST$4,ro+a.length,0));const r=allocUnsafe$2(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return asUint8Array(r)}function equals$2(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(const n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(isUint8ArrayList(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(const n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(isUint8ArrayList(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){const r=findBufAndOffset(this.bufs,t);return r.buf[r.index]}set(t,r){const n=findBufAndOffset(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){const{bufs:n,length:o}=this._subList(t,r);return concat$1(n,o)}subarray(t,r){const{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:concat$1(n,o)}sublist(t,r){const{bufs:n,length:o}=this._subList(t,r),a=new Uint8ArrayList;return a.length=o,a.bufs=n,a}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];let o=0;for(let a=0;a=u)continue;const _=t>=c&&tc&&r<=u;if(_&&b){if(t===c&&r===u){n.push(l);break}const x=t-c;n.push(l.subarray(x,x+(r-t)));break}if(_){if(t===0){n.push(l);continue}n.push(l.subarray(t-c));continue}if(b){if(r===u){n.push(l);break}n.push(l.subarray(0,r-c));break}n.push(l)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!isUint8ArrayList(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;const o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const a=256,l=new Int32Array(a);for(let x=0;x=0;E--){const I=this.get(x+E);if(n[E]!==I){b=Math.max(1,E-c[I]);break}}if(b===0)return x}return-1}getInt8(t){const r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){const n=allocUnsafe$2(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){const o=alloc(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){const r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){const n=allocUnsafe$2(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){const o=alloc(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof Uint8ArrayList)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;ro+a.byteLength,0)),n.length=r,n}}function isAsyncIterable$a(e){return e[Symbol.asyncIterator]!=null}const defaultEncoder=e=>{const t=encodingLength$2(e),r=allocUnsafe$2(t);return encode$d(e,r),defaultEncoder.bytes=t,r};defaultEncoder.bytes=0;function encode$c(e,t){t=t??{};const r=t.lengthEncoder??defaultEncoder;function*n(o){const a=r(o.byteLength);a instanceof Uint8Array?yield a:yield*a,o instanceof Uint8Array?yield o:yield*o}return isAsyncIterable$a(e)?async function*(){for await(const o of e)yield*n(o)}():function*(){for(const o of e)yield*n(o)}()}encode$c.single=(e,t)=>{t=t??{};const r=t.lengthEncoder??defaultEncoder;return new Uint8ArrayList(r(e.byteLength),e)};function assign$1(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}function createError(e,t,r){if(!e||typeof e=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof t=="object"&&(r=t,t=""),t&&(r.code=t);try{return assign$1(e,r)}catch{r.message=e.message,r.stack=e.stack;const o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(e)),assign$1(new o,r)}}var errCode=createError;const MAX_LENGTH_LENGTH=8,MAX_DATA_LENGTH=1024*1024*4;var ReadMode;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(ReadMode||(ReadMode={}));const defaultDecoder=e=>{const t=decode$b(e);return defaultDecoder.bytes=encodingLength$2(t),t};defaultDecoder.bytes=0;function decode$a(e,t){const r=new Uint8ArrayList;let n=ReadMode.LENGTH,o=-1;const a=t?.lengthDecoder??defaultDecoder,l=t?.maxLengthLength??MAX_LENGTH_LENGTH,c=t?.maxDataLength??MAX_DATA_LENGTH;function*u(){for(;r.byteLength>0;){if(n===ReadMode.LENGTH)try{if(o=a(r),o<0)throw errCode(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>c)throw errCode(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");const _=a.bytes;r.consume(_),t?.onLength!=null&&t.onLength(o),n=ReadMode.DATA}catch(_){if(_ instanceof RangeError){if(r.byteLength>l)throw errCode(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw _}if(n===ReadMode.DATA){if(r.byteLength0)throw errCode(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(const _ of e)r.append(_),yield*u();if(r.byteLength>0)throw errCode(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}decode$a.fromReader=(e,t)=>{let r=1;const n=async function*(){for(;;)try{const{done:a,value:l}=await e.next(r);if(a===!0)return;l!=null&&(yield l)}catch(a){if(a.code==="ERR_UNDER_READ")return{done:!0,value:null};throw a}finally{r=1}}();return decode$a(n,{...t??{},onLength:a=>{r=a}})};function pDefer(){const e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}class FixedFIFO{constructor(t){Ye(this,"buffer");Ye(this,"mask");Ye(this,"top");Ye(this,"btm");Ye(this,"next");if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}}class FIFO{constructor(t={}){Ye(this,"size");Ye(this,"hwm");Ye(this,"head");Ye(this,"tail");this.hwm=t.splitLimit??16,this.head=new FixedFIFO(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const r=this.head;this.head=r.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class AbortError$6 extends Error{constructor(r,n){super(r??"The operation was aborted");Ye(this,"type");Ye(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}}function pushable(e={}){return _pushable(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function pushableV(e={}){return _pushable(r=>{let n;const o=[];for(;!r.isEmpty()&&(n=r.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&o.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:o}},e)}function _pushable(e,t){t=t??{};let r=t.onEnd,n=new FIFO,o,a,l,c=pDefer();const u=async()=>{try{return n.isEmpty()?l?{done:!0}:await new Promise((O,$)=>{a=D=>{a=null,n.push(D);try{O(e(n))}catch(N){$(N)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=pDefer()})}},_=O=>a!=null?a(O):(n.push(O),o),b=O=>(n=new FIFO,a!=null?a({error:O}):(n.push({error:O}),o)),x=O=>{if(l)return o;if(t?.objectMode!==!0&&O?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return _({done:!1,value:O})},E=O=>l?o:(l=!0,O!=null?b(O):_({done:!0})),I=()=>(n=new FIFO,E(),{done:!0}),k=O=>(E(O),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:u,return:I,throw:k,push:x,end:E,get readableLength(){return n.size},onEmpty:async O=>{const $=O?.signal;if($?.throwIfAborted(),n.isEmpty())return;let D,N;$!=null&&(D=new Promise((H,ie)=>{N=()=>{ie(new AbortError$6)},$.addEventListener("abort",N)}));try{await Promise.race([c.promise,D])}finally{N!=null&&$!=null&&$?.removeEventListener("abort",N)}}},r==null)return o;const T=o;return o={[Symbol.asyncIterator](){return this},next(){return T.next()},throw(O){return T.throw(O),r!=null&&(r(O),r=void 0),{done:!0}},return(){return T.return(),r!=null&&(r(),r=void 0),{done:!0}},push:x,end(O){return T.end(O),r!=null&&(r(O),r=void 0),o},get readableLength(){return T.readableLength}},o}class CodeError$2 extends Error{constructor(r,n){super(r);Ye(this,"code");this.code=n}}class AbortError$5 extends CodeError$2{constructor(r){super(r,"ABORT_ERR");Ye(this,"type");this.type="aborted"}}function byteStream(e){const t=pushable();e.sink(t).catch(a=>{t.end(a)}),e.sink=async a=>{for await(const l of a)t.push(l);t.end()};let r=e.source;e.source[Symbol.iterator]!=null?r=e.source[Symbol.iterator]():e.source[Symbol.asyncIterator]!=null&&(r=e.source[Symbol.asyncIterator]());const n=new Uint8ArrayList;return{read:async(a,l)=>{l?.signal?.throwIfAborted();let c;const u=new Promise((_,b)=>{c=()=>{b(new AbortError$5("Read aborted"))},l?.signal?.addEventListener("abort",c)});try{if(a==null){const{done:b,value:x}=await Promise.race([r.next(),u]);return b===!0?new Uint8ArrayList:x}for(;n.byteLength{l?.signal?.throwIfAborted(),a instanceof Uint8Array?t.push(a):t.push(a.subarray()),await t.onEmpty(l)},unwrap:()=>{const a=e.source;return e.source=async function*(){yield*n,yield*a}(),e}}}class CodeError$1 extends Error{constructor(r,n){super(r);Ye(this,"code");this.code=n}}const defaultLengthDecoder=e=>decode$b(e);defaultLengthDecoder.bytes=0;function lpStream(e,t){const r=byteStream(e);return{read:async o=>{let a=-1;const l=new Uint8ArrayList,c=t?.lengthDecoder??defaultLengthDecoder;for(;;){l.append(await r.read(1,o));try{a=c(l)}catch(u){if(u instanceof RangeError)continue;throw u}if(a>-1)break;if(t?.maxLengthLength!=null&&l.byteLength>t.maxLengthLength)throw new CodeError$1("message length length too long","ERR_MSG_LENGTH_TOO_LONG")}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new CodeError$1("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(a,o)},write:async(o,a)=>{await r.write(encode$c.single(o,t),a)},unwrap:()=>r.unwrap()}}function pair(){const e=pDefer();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){yield*await e.promise}()}}function duplexPair(){const e=pair(),t=pair();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}function isAsyncIterable$9(e){return e[Symbol.asyncIterator]!=null}function merge$1(...e){const t=[];for(const r of e)isAsyncIterable$9(r)||t.push(r);return t.length===e.length?function*(){for(const r of t)yield*r}():async function*(){const r=pushable({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(const o of n)r.push(o)})),r.end()}catch(n){r.end(n)}}),yield*r}()}function pipe(e,...t){if(e==null)throw new Error("Empty pipeline");if(isDuplex(e)){const n=e;e=()=>n.source}else if(isIterable(e)||isAsyncIterable$8(e)){const n=e;e=()=>n}const r=[e,...t];if(r.length>1&&isDuplex(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n{let t;for(;e.length>0;)t=e.shift()(t);return t},isAsyncIterable$8=e=>e?.[Symbol.asyncIterator]!=null,isIterable=e=>e?.[Symbol.iterator]!=null,isDuplex=e=>e==null?!1:e.sink!=null&&e.source!=null,duplexPipelineFn=e=>t=>{const r=e.sink(t);if(r?.then!=null){const n=pushable({objectMode:!0});r.then(()=>{n.end()},l=>{n.end(l)});let o;const a=e.source;if(isAsyncIterable$8(a))o=async function*(){yield*a,n.end()};else if(isIterable(a))o=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return merge$1(n,o())}return e.source},NOISE_MSG_MAX_LENGTH_BYTES=65535,NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG=NOISE_MSG_MAX_LENGTH_BYTES-16,DUMP_SESSION_KEYS=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u8a$2=e=>e instanceof Uint8Array,u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView$1=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$1)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$2(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes$2(e){if(typeof e=="string"&&(e=utf8ToBytes$2(e)),!u8a$2(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}const isPlainObject$1=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function checkOpts(e,t){if(t!==void 0&&(typeof t!="object"||!isPlainObject$1(t)))throw new Error("options must be object or undefined");return Object.assign(e,t)}function ensureBytes$1(e,t){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");if(typeof t=="number"&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}function equalBytes$1(e,t){if(e.length!==t.length)throw new Error("equalBytes: Different size of Uint8Arrays");let r=!0;for(let n=0;n>o&a),c=Number(r&a),u=n?4:0,_=n?0:4;e.setUint32(t+u,l,n),e.setUint32(t+_,c,n)}function number$3(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function bytes$1(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash$2(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("hash must be wrapped by utils.wrapConstructor");number$3(e.outputLen),number$3(e.blockLen)}function exists$1(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output$1(e,t){bytes$1(e);const r=t.outputLen;if(e.lengthe[t++]&255|(e[t++]&255)<<8;class Poly1305{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=toBytes$2(t),ensureBytes$1(t,32);const r=u8to16(t,0),n=u8to16(t,2),o=u8to16(t,4),a=u8to16(t,6),l=u8to16(t,8),c=u8to16(t,10),u=u8to16(t,12),_=u8to16(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|a<<9)&8191,this.r[4]=(a>>>4|l<<12)&255,this.r[5]=l>>>1&8190,this.r[6]=(l>>>14|c<<2)&8191,this.r[7]=(c>>>11|u<<5)&8065,this.r[8]=(u>>>8|_<<8)&8191,this.r[9]=_>>>5&127;for(let b=0;b<8;b++)this.pad[b]=u8to16(t,16+2*b)}process(t,r,n=!1){const o=n?0:2048,{h:a,r:l}=this,c=l[0],u=l[1],_=l[2],b=l[3],x=l[4],E=l[5],I=l[6],k=l[7],T=l[8],O=l[9],$=u8to16(t,r+0),D=u8to16(t,r+2),N=u8to16(t,r+4),H=u8to16(t,r+6),ie=u8to16(t,r+8),ue=u8to16(t,r+10),de=u8to16(t,r+12),le=u8to16(t,r+14);let ce=a[0]+($&8191),ve=a[1]+(($>>>13|D<<3)&8191),ee=a[2]+((D>>>10|N<<6)&8191),he=a[3]+((N>>>7|H<<9)&8191),ne=a[4]+((H>>>4|ie<<12)&8191),xe=a[5]+(ie>>>1&8191),te=a[6]+((ie>>>14|ue<<2)&8191),ae=a[7]+((ue>>>11|de<<5)&8191),ge=a[8]+((de>>>8|le<<8)&8191),se=a[9]+(le>>>5|o),Se=0,Pe=Se+ce*c+ve*(5*O)+ee*(5*T)+he*(5*k)+ne*(5*I);Se=Pe>>>13,Pe&=8191,Pe+=xe*(5*E)+te*(5*x)+ae*(5*b)+ge*(5*_)+se*(5*u),Se+=Pe>>>13,Pe&=8191;let Ue=Se+ce*u+ve*c+ee*(5*O)+he*(5*T)+ne*(5*k);Se=Ue>>>13,Ue&=8191,Ue+=xe*(5*I)+te*(5*E)+ae*(5*x)+ge*(5*b)+se*(5*_),Se+=Ue>>>13,Ue&=8191;let Be=Se+ce*_+ve*u+ee*c+he*(5*O)+ne*(5*T);Se=Be>>>13,Be&=8191,Be+=xe*(5*k)+te*(5*I)+ae*(5*E)+ge*(5*x)+se*(5*b),Se+=Be>>>13,Be&=8191;let fe=Se+ce*b+ve*_+ee*u+he*c+ne*(5*O);Se=fe>>>13,fe&=8191,fe+=xe*(5*T)+te*(5*k)+ae*(5*I)+ge*(5*E)+se*(5*x),Se+=fe>>>13,fe&=8191;let ye=Se+ce*x+ve*b+ee*_+he*u+ne*c;Se=ye>>>13,ye&=8191,ye+=xe*(5*O)+te*(5*T)+ae*(5*k)+ge*(5*I)+se*(5*E),Se+=ye>>>13,ye&=8191;let Ce=Se+ce*E+ve*x+ee*b+he*_+ne*u;Se=Ce>>>13,Ce&=8191,Ce+=xe*c+te*(5*O)+ae*(5*T)+ge*(5*k)+se*(5*I),Se+=Ce>>>13,Ce&=8191;let Le=Se+ce*I+ve*E+ee*x+he*b+ne*_;Se=Le>>>13,Le&=8191,Le+=xe*u+te*c+ae*(5*O)+ge*(5*T)+se*(5*k),Se+=Le>>>13,Le&=8191;let Fe=Se+ce*k+ve*I+ee*E+he*x+ne*b;Se=Fe>>>13,Fe&=8191,Fe+=xe*_+te*u+ae*c+ge*(5*O)+se*(5*T),Se+=Fe>>>13,Fe&=8191;let Oe=Se+ce*T+ve*k+ee*I+he*E+ne*x;Se=Oe>>>13,Oe&=8191,Oe+=xe*b+te*_+ae*u+ge*c+se*(5*O),Se+=Oe>>>13,Oe&=8191;let be=Se+ce*O+ve*T+ee*k+he*I+ne*E;Se=be>>>13,be&=8191,be+=xe*x+te*b+ae*_+ge*u+se*c,Se+=be>>>13,be&=8191,Se=(Se<<2)+Se|0,Se=Se+Pe|0,Pe=Se&8191,Se=Se>>>13,Ue+=Se,a[0]=Pe,a[1]=Ue,a[2]=Be,a[3]=fe,a[4]=ye,a[5]=Ce,a[6]=Le,a[7]=Fe,a[8]=Oe,a[9]=be}finalize(){const{h:t,pad:r}=this,n=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let c=2;c<10;c++)t[c]+=o,o=t[c]>>>13,t[c]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let c=1;c<10;c++)n[c]=t[c]+o,o=n[c]>>>13,n[c]&=8191;n[9]-=1<<13;let a=(o^1)-1;for(let c=0;c<10;c++)n[c]&=a;a=~a;for(let c=0;c<10;c++)t[c]=t[c]&a|n[c];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let l=t[0]+r[0];t[0]=l&65535;for(let c=1;c<8;c++)l=(t[c]+r[c]|0)+(l>>>16)|0,t[c]=l&65535}update(t){assert.exists(this);const{buffer:r,blockLen:n}=this;t=toBytes$2(t);const o=t.length;for(let a=0;a>>0,t[a++]=n[l]>>>8;return t}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}}function wrapConstructorWithKey(e){const t=(n,o)=>e(o).update(toBytes$2(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}const poly1305=wrapConstructorWithKey(e=>new Poly1305(e)),sigma16=utf8ToBytes$2("expand 16-byte k"),sigma32=utf8ToBytes$2("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32),isAligned32=e=>!(e.byteOffset%4),salsaBasic=e=>{const{core:t,rounds:r,counterRight:n,counterLen:o,allow128bitKeys:a,extendNonceFn:l,blockLen:c}=checkOpts({rounds:20,counterRight:!1,counterLen:8,allow128bitKeys:!0,blockLen:64},e);assert.number(o),assert.number(r),assert.number(c),assert.bool(n),assert.bool(a);const u=c/4;if(c%4!==0)throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes");return(_,b,x,E,I=0)=>{if(assert.bytes(_),assert.bytes(b),assert.bytes(x),E||(E=new Uint8Array(x.length)),assert.bytes(E),assert.number(I),I<0||I>=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");if(E.length=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");const ee=Math.min(c,le-ce);if(ee===c&&de&&ue){const he=ce/4;if(ce%4!==0)throw new Error("Salsa/ChaCha: invalid block position");for(let ne=0;nee<>>32-t;function chachaCore(e,t,r,n,o,a=20){let l=e[0],c=e[1],u=e[2],_=e[3],b=t[0],x=t[1],E=t[2],I=t[3],k=t[4],T=t[5],O=t[6],$=t[7],D=o,N=r[0],H=r[1],ie=r[2],ue=l,de=c,le=u,ce=_,ve=b,ee=x,he=E,ne=I,xe=k,te=T,ae=O,ge=$,se=D,Se=N,Pe=H,Ue=ie;for(let fe=0;fe{e.update(t);const r=t.length%16;r&&e.update(ZERO.subarray(r))},computeTag=(e,t,r,n,o)=>{const a=e(t,r,new Uint8Array(32)),l=poly1305.create(a);o&&updatePadded(l,o),updatePadded(l,n);const c=new Uint8Array(16),u=createView$1(c);setBigUint64$1(u,0,BigInt(o?o.length:0),!0),setBigUint64$1(u,8,BigInt(n.length),!0),l.update(c);const _=l.digest();return a.fill(0),_},_poly1305_aead=e=>(t,r,n)=>(ensureBytes$1(t,32),ensureBytes$1(r),{tagLength:16,encrypt:(a,l)=>{const c=a.length,u=c+16;l?ensureBytes$1(l,u):l=new Uint8Array(u),e(t,r,a,l,1);const _=computeTag(e,t,r,l.subarray(0,-16),n);return l.set(_,c),l},decrypt:(a,l)=>{const c=a.length,u=c-16;if(c<16)throw new Error(`encrypted data must be at least ${16} bytes`);l?ensureBytes$1(l,u):l=new Uint8Array(u);const _=a.subarray(0,-16),b=a.subarray(-16),x=computeTag(e,t,r,_,n);if(!equalBytes$1(b,x))throw new Error("invalid tag");return e(t,r,_,l,1),l}}),chacha20poly1305=_poly1305_aead(chacha20);function number$2(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bytes(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash$1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(e.outputLen),number$2(e.blockLen)}function exists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output(e,t){bytes(e);const r=t.outputLen;if(e.lengthe instanceof Uint8Array,createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr=(e,t)=>e<<32-t|e>>>t,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$1(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes$1(e){if(typeof e=="string"&&(e=utf8ToBytes$1(e)),!u8a$1(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function concatBytes$1(...e){const t=new Uint8Array(e.reduce((n,o)=>n+o.length,0));let r=0;return e.forEach(n=>{if(!u8a$1(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(e){const t=n=>e().update(toBytes$1(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function randomBytes$1(e=32){if(crypto$3&&typeof crypto$3.getRandomValues=="function")return crypto$3.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const o=BigInt(32),a=BigInt(4294967295),l=Number(r>>o&a),c=Number(r&a),u=n?4:0,_=n?0:4;e.setUint32(t+u,l,n),e.setUint32(t+_,c,n)}class SHA2 extends Hash{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=createView(this.buffer)}update(t){exists(this);const{view:r,buffer:n,blockLen:o}=this;t=toBytes$1(t);const a=t.length;for(let l=0;lo-l&&(this.process(n,0),l=0);for(let x=l;xb.length)throw new Error("_sha2: outputLen bigger than state");for(let x=0;x<_;x++)c.setUint32(4*x,b[x],a)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:a,destroyed:l,pos:c}=this;return t.length=o,t.pos=c,t.finished=a,t.destroyed=l,o%r&&t.buffer.set(n),t}}const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(e,t=!1){return t?{h:Number(e&U32_MASK64),l:Number(e>>_32n&U32_MASK64)}:{h:Number(e>>_32n&U32_MASK64)|0,l:Number(e&U32_MASK64)|0}}function split(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;oBigInt(e>>>0)<<_32n|BigInt(t>>>0),shrSH=(e,t,r)=>e>>>r,shrSL=(e,t,r)=>e<<32-r|t>>>r,rotrSH=(e,t,r)=>e>>>r|t<<32-r,rotrSL=(e,t,r)=>e<<32-r|t>>>r,rotrBH=(e,t,r)=>e<<64-r|t>>>r-32,rotrBL=(e,t,r)=>e>>>r-32|t<<64-r,rotr32H=(e,t)=>t,rotr32L=(e,t)=>e,rotlSH=(e,t,r)=>e<>>32-r,rotlSL=(e,t,r)=>t<>>32-r,rotlBH=(e,t,r)=>t<>>64-r,rotlBL=(e,t,r)=>e<>>64-r;function add(e,t,r,n){const o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}const add3L=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,add5L=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),add5H=(e,t,r,n,o,a)=>t+r+n+o+a+(e/2**32|0)|0,u64={fromBig,split,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L},u64$1=u64,[SHA512_Kh,SHA512_Kl]=(()=>u64$1.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:r,Bh:n,Bl:o,Ch:a,Cl:l,Dh:c,Dl:u,Eh:_,El:b,Fh:x,Fl:E,Gh:I,Gl:k,Hh:T,Hl:O}=this;return[t,r,n,o,a,l,c,u,_,b,x,E,I,k,T,O]}set(t,r,n,o,a,l,c,u,_,b,x,E,I,k,T,O){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=a|0,this.Cl=l|0,this.Dh=c|0,this.Dl=u|0,this.Eh=_|0,this.El=b|0,this.Fh=x|0,this.Fl=E|0,this.Gh=I|0,this.Gl=k|0,this.Hh=T|0,this.Hl=O|0}process(t,r){for(let N=0;N<16;N++,r+=4)SHA512_W_H[N]=t.getUint32(r),SHA512_W_L[N]=t.getUint32(r+=4);for(let N=16;N<80;N++){const H=SHA512_W_H[N-15]|0,ie=SHA512_W_L[N-15]|0,ue=u64$1.rotrSH(H,ie,1)^u64$1.rotrSH(H,ie,8)^u64$1.shrSH(H,ie,7),de=u64$1.rotrSL(H,ie,1)^u64$1.rotrSL(H,ie,8)^u64$1.shrSL(H,ie,7),le=SHA512_W_H[N-2]|0,ce=SHA512_W_L[N-2]|0,ve=u64$1.rotrSH(le,ce,19)^u64$1.rotrBH(le,ce,61)^u64$1.shrSH(le,ce,6),ee=u64$1.rotrSL(le,ce,19)^u64$1.rotrBL(le,ce,61)^u64$1.shrSL(le,ce,6),he=u64$1.add4L(de,ee,SHA512_W_L[N-7],SHA512_W_L[N-16]),ne=u64$1.add4H(he,ue,ve,SHA512_W_H[N-7],SHA512_W_H[N-16]);SHA512_W_H[N]=ne|0,SHA512_W_L[N]=he|0}let{Ah:n,Al:o,Bh:a,Bl:l,Ch:c,Cl:u,Dh:_,Dl:b,Eh:x,El:E,Fh:I,Fl:k,Gh:T,Gl:O,Hh:$,Hl:D}=this;for(let N=0;N<80;N++){const H=u64$1.rotrSH(x,E,14)^u64$1.rotrSH(x,E,18)^u64$1.rotrBH(x,E,41),ie=u64$1.rotrSL(x,E,14)^u64$1.rotrSL(x,E,18)^u64$1.rotrBL(x,E,41),ue=x&I^~x&T,de=E&k^~E&O,le=u64$1.add5L(D,ie,de,SHA512_Kl[N],SHA512_W_L[N]),ce=u64$1.add5H(le,$,H,ue,SHA512_Kh[N],SHA512_W_H[N]),ve=le|0,ee=u64$1.rotrSH(n,o,28)^u64$1.rotrBH(n,o,34)^u64$1.rotrBH(n,o,39),he=u64$1.rotrSL(n,o,28)^u64$1.rotrBL(n,o,34)^u64$1.rotrBL(n,o,39),ne=n&a^n&c^a&c,xe=o&l^o&u^l&u;$=T|0,D=O|0,T=I|0,O=k|0,I=x|0,k=E|0,{h:x,l:E}=u64$1.add(_|0,b|0,ce|0,ve|0),_=c|0,b=u|0,c=a|0,u=l|0,a=n|0,l=o|0;const te=u64$1.add3L(ve,he,xe);n=u64$1.add3H(te,ce,ee,ne),o=te|0}({h:n,l:o}=u64$1.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:a,l}=u64$1.add(this.Bh|0,this.Bl|0,a|0,l|0),{h:c,l:u}=u64$1.add(this.Ch|0,this.Cl|0,c|0,u|0),{h:_,l:b}=u64$1.add(this.Dh|0,this.Dl|0,_|0,b|0),{h:x,l:E}=u64$1.add(this.Eh|0,this.El|0,x|0,E|0),{h:I,l:k}=u64$1.add(this.Fh|0,this.Fl|0,I|0,k|0),{h:T,l:O}=u64$1.add(this.Gh|0,this.Gl|0,T|0,O|0),{h:$,l:D}=u64$1.add(this.Hh|0,this.Hl|0,$|0,D|0),this.set(n,o,a,l,c,u,_,b,x,E,I,k,T,O,$,D)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512$3=wrapConstructor(()=>new SHA512);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$5=BigInt(0),_1n$7=BigInt(1),_2n$4=BigInt(2),u8a=e=>e instanceof Uint8Array,hexes=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(e){if(!u8a(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!u8a(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function equalBytes(e,t){if(e.length!==t.length)return!1;for(let r=0;r_0n$5;e>>=_1n$7,t+=1);return t}function bitGet(e,t){return e>>BigInt(t)&_1n$7}const bitSet=(e,t,r)=>e|(r?_1n$7:_0n$5)<(_2n$4<new Uint8Array(e),u8fr=e=>Uint8Array.from(e);function createHmacDrbg(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=u8n(e),o=u8n(e),a=0;const l=()=>{n.fill(1),o.fill(0),a=0},c=(...x)=>r(o,n,...x),u=(x=u8n())=>{o=c(u8fr([0]),x),n=c(),x.length!==0&&(o=c(u8fr([1]),x),n=c())},_=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let x=0;const E=[];for(;x{l(),u(x);let I;for(;!(I=E(_()));)u();return l(),I}}const validatorFns={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function validateObject(e,t,r={}){const n=(o,a,l)=>{const c=validatorFns[a];if(typeof c!="function")throw new Error(`Invalid validator "${a}", expected function`);const u=e[o];if(!(l&&u===void 0)&&!c(u,e))throw new Error(`Invalid param ${String(o)}=${u} (${typeof u}), expected ${a}`)};for(const[o,a]of Object.entries(t))n(o,a,!1);for(const[o,a]of Object.entries(r))n(o,a,!0);return e}const ut=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex,numberToHexUnpadded,hexToNumber,hexToBytes,bytesToNumberBE,bytesToNumberLE,numberToBytesBE,numberToBytesLE,numberToVarBytesBE,ensureBytes,concatBytes,equalBytes,utf8ToBytes,bitLen,bitGet,bitSet,bitMask,createHmacDrbg,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$6=BigInt(1),_2n$3=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n$1=BigInt(5),_8n$1=BigInt(8);BigInt(9);BigInt(16);function mod(e,t){const r=e%t;return r>=_0n$4?r:t+r}function pow(e,t,r){if(r<=_0n$4||t<_0n$4)throw new Error("Expected power/modulo > 0");if(r===_1n$6)return _0n$4;let n=_1n$6;for(;t>_0n$4;)t&_1n$6&&(n=n*e%r),e=e*e%r,t>>=_1n$6;return n}function pow2(e,t,r){let n=e;for(;t-- >_0n$4;)n*=n,n%=r;return n}function invert(e,t){if(e===_0n$4||t<=_0n$4)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=mod(e,t),n=t,o=_0n$4,a=_1n$6;for(;r!==_0n$4;){const c=n/r,u=n%r,_=o-a*c;n=r,r=u,o=a,a=_}if(n!==_1n$6)throw new Error("invert: does not exist");return mod(o,t)}function tonelliShanks(e){const t=(e-_1n$6)/_2n$3;let r,n,o;for(r=e-_1n$6,n=0;r%_2n$3===_0n$4;r/=_2n$3,n++);for(o=_2n$3;o(mod(e,t)&_1n$6)===_1n$6,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=FIELD_FIELDS.reduce((n,o)=>(n[o]="function",n),t);return validateObject(e,r)}function FpPow(e,t,r){if(r<_0n$4)throw new Error("Expected power > 0");if(r===_0n$4)return e.ONE;if(r===_1n$6)return t;let n=e.ONE,o=t;for(;r>_0n$4;)r&_1n$6&&(n=e.mul(n,o)),o=e.sqr(o),r>>=_1n$6;return n}function FpInvertBatch(e,t){const r=new Array(t.length),n=t.reduce((a,l,c)=>e.is0(l)?a:(r[c]=a,e.mul(a,l)),e.ONE),o=e.inv(n);return t.reduceRight((a,l,c)=>e.is0(l)?a:(r[c]=e.mul(a,r[c]),e.mul(a,l)),o),r}function nLength(e,t){const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Field(e,t,r=!1,n={}){if(e<=_0n$4)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:o,nByteLength:a}=nLength(e,t);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");const l=FpSqrt(e),c=Object.freeze({ORDER:e,BITS:o,BYTES:a,MASK:bitMask(o),ZERO:_0n$4,ONE:_1n$6,create:u=>mod(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof u}`);return _0n$4<=u&&uu===_0n$4,isOdd:u=>(u&_1n$6)===_1n$6,neg:u=>mod(-u,e),eql:(u,_)=>u===_,sqr:u=>mod(u*u,e),add:(u,_)=>mod(u+_,e),sub:(u,_)=>mod(u-_,e),mul:(u,_)=>mod(u*_,e),pow:(u,_)=>FpPow(c,u,_),div:(u,_)=>mod(u*invert(_,e),e),sqrN:u=>u*u,addN:(u,_)=>u+_,subN:(u,_)=>u-_,mulN:(u,_)=>u*_,inv:u=>invert(u,e),sqrt:n.sqrt||(u=>l(c,u)),invertBatch:u=>FpInvertBatch(c,u),cmov:(u,_,b)=>b?_:u,toBytes:u=>r?numberToBytesLE(u,a):numberToBytesBE(u,a),fromBytes:u=>{if(u.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${u.length}`);return r?bytesToNumberLE(u):bytesToNumberBE(u)}});return Object.freeze(c)}function FpSqrtEven(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");const r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function getFieldBytesLength(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(e){const t=getFieldBytesLength(e);return t+Math.ceil(t/2)}function mapHashToField(e,t,r=!1){const n=e.length,o=getFieldBytesLength(t),a=getMinHashLength(t);if(n<16||n1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);const l=r?bytesToNumberBE(e):bytesToNumberLE(e),c=mod(l,t-_1n$6)+_1n$6;return r?numberToBytesLE(c,o):numberToBytesBE(c,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$5=BigInt(1);function wNAF(e,t){const r=(o,a)=>{const l=a.negate();return o?l:a},n=o=>{const a=Math.ceil(t/o)+1,l=2**(o-1);return{windows:a,windowSize:l}};return{constTimeNegate:r,unsafeLadder(o,a){let l=e.ZERO,c=o;for(;a>_0n$3;)a&_1n$5&&(l=l.add(c)),c=c.double(),a>>=_1n$5;return l},precomputeWindow(o,a){const{windows:l,windowSize:c}=n(a),u=[];let _=o,b=_;for(let x=0;x>=I,O>u&&(O-=E,l+=_1n$5);const $=T,D=T+Math.abs(O)-1,N=k%2!==0,H=O<0;O===0?b=b.add(r(N,a[$])):_=_.add(r(H,a[D]))}return{p:_,f:b}},wNAFCached(o,a,l,c){const u=o._WINDOW_SIZE||1;let _=a.get(o);return _||(_=this.precomputeWindow(o,u),u!==1&&a.set(o,c(_))),this.wNAF(u,_,l)}}}function validateBasic(e){return validateField(e.Fp),validateObject(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),_8n=BigInt(8),VERIFY_DEFAULT={zip215:!0};function validateOpts$2(e){const t=validateBasic(e);return validateObject(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function twistedEdwards(e){const t=validateOpts$2(e),{Fp:r,n,prehash:o,hash:a,randomBytes:l,nByteLength:c,h:u}=t,_=_2n$2<{try{return{isValid:!0,value:r.sqrt(se*r.inv(Se))}}catch{return{isValid:!1,value:_0n$2}}}),E=t.adjustScalarBytes||(se=>se),I=t.domain||((se,Se,Pe)=>{if(Se.length||Pe)throw new Error("Contexts/pre-hash are not supported");return se}),k=se=>typeof se=="bigint"&&_0n$2k(se)&&k(Se)&&sese===_0n$2||T(se,_);function $(se,Se){if(T(se,Se))return se;throw new Error(`Expected valid scalar < ${Se}, got ${typeof se} ${se}`)}function D(se){return se===_0n$2?se:$(se,n)}const N=new Map;function H(se){if(!(se instanceof ie))throw new Error("ExtendedPoint expected")}class ie{constructor(Se,Pe,Ue,Be){if(this.ex=Se,this.ey=Pe,this.ez=Ue,this.et=Be,!O(Se))throw new Error("x required");if(!O(Pe))throw new Error("y required");if(!O(Ue))throw new Error("z required");if(!O(Be))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(Se){if(Se instanceof ie)throw new Error("extended point not allowed");const{x:Pe,y:Ue}=Se||{};if(!O(Pe)||!O(Ue))throw new Error("invalid affine point");return new ie(Pe,Ue,_1n$4,b(Pe*Ue))}static normalizeZ(Se){const Pe=r.invertBatch(Se.map(Ue=>Ue.ez));return Se.map((Ue,Be)=>Ue.toAffine(Pe[Be])).map(ie.fromAffine)}_setWindowSize(Se){this._WINDOW_SIZE=Se,N.delete(this)}assertValidity(){const{a:Se,d:Pe}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:Ue,ey:Be,ez:fe,et:ye}=this,Ce=b(Ue*Ue),Le=b(Be*Be),Fe=b(fe*fe),Oe=b(Fe*Fe),be=b(Ce*Se),Re=b(Fe*b(be+Le)),Ie=b(Oe+b(Pe*b(Ce*Le)));if(Re!==Ie)throw new Error("bad point: equation left != right (1)");const we=b(Ue*Be),oe=b(fe*ye);if(we!==oe)throw new Error("bad point: equation left != right (2)")}equals(Se){H(Se);const{ex:Pe,ey:Ue,ez:Be}=this,{ex:fe,ey:ye,ez:Ce}=Se,Le=b(Pe*Ce),Fe=b(fe*Be),Oe=b(Ue*Ce),be=b(ye*Be);return Le===Fe&&Oe===be}is0(){return this.equals(ie.ZERO)}negate(){return new ie(b(-this.ex),this.ey,this.ez,b(-this.et))}double(){const{a:Se}=t,{ex:Pe,ey:Ue,ez:Be}=this,fe=b(Pe*Pe),ye=b(Ue*Ue),Ce=b(_2n$2*b(Be*Be)),Le=b(Se*fe),Fe=Pe+Ue,Oe=b(b(Fe*Fe)-fe-ye),be=Le+ye,Re=be-Ce,Ie=Le-ye,we=b(Oe*Re),oe=b(be*Ie),pe=b(Oe*Ie),ke=b(Re*be);return new ie(we,oe,ke,pe)}add(Se){H(Se);const{a:Pe,d:Ue}=t,{ex:Be,ey:fe,ez:ye,et:Ce}=this,{ex:Le,ey:Fe,ez:Oe,et:be}=Se;if(Pe===BigInt(-1)){const Ve=b((fe-Be)*(Fe+Le)),Ae=b((fe+Be)*(Fe-Le)),He=b(Ae-Ve);if(He===_0n$2)return this.double();const Ge=b(ye*_2n$2*be),Ze=b(Ce*_2n$2*Oe),$e=Ze+Ge,me=Ae+Ve,Ee=Ze-Ge,je=b($e*He),nt=b(me*Ee),ot=b($e*Ee),dt=b(He*me);return new ie(je,nt,dt,ot)}const Re=b(Be*Le),Ie=b(fe*Fe),we=b(Ce*Ue*be),oe=b(ye*Oe),pe=b((Be+fe)*(Le+Fe)-Re-Ie),ke=oe-we,Ne=oe+we,ze=b(Ie-Pe*Re),Xe=b(pe*ke),Je=b(Ne*ze),rt=b(pe*ze),qe=b(ke*Ne);return new ie(Xe,Je,qe,rt)}subtract(Se){return this.add(Se.negate())}wNAF(Se){return le.wNAFCached(this,N,Se,ie.normalizeZ)}multiply(Se){const{p:Pe,f:Ue}=this.wNAF($(Se,n));return ie.normalizeZ([Pe,Ue])[0]}multiplyUnsafe(Se){let Pe=D(Se);return Pe===_0n$2?de:this.equals(de)||Pe===_1n$4?this:this.equals(ue)?this.wNAF(Pe).p:le.unsafeLadder(this,Pe)}isSmallOrder(){return this.multiplyUnsafe(u).is0()}isTorsionFree(){return le.unsafeLadder(this,n).is0()}toAffine(Se){const{ex:Pe,ey:Ue,ez:Be}=this,fe=this.is0();Se==null&&(Se=fe?_8n:r.inv(Be));const ye=b(Pe*Se),Ce=b(Ue*Se),Le=b(Be*Se);if(fe)return{x:_0n$2,y:_1n$4};if(Le!==_1n$4)throw new Error("invZ was invalid");return{x:ye,y:Ce}}clearCofactor(){const{h:Se}=t;return Se===_1n$4?this:this.multiplyUnsafe(Se)}static fromHex(Se,Pe=!1){const{d:Ue,a:Be}=t,fe=r.BYTES;Se=ensureBytes("pointHex",Se,fe);const ye=Se.slice(),Ce=Se[fe-1];ye[fe-1]=Ce&-129;const Le=bytesToNumberLE(ye);Le===_0n$2||(Pe?$(Le,_):$(Le,r.ORDER));const Fe=b(Le*Le),Oe=b(Fe-_1n$4),be=b(Ue*Fe-Be);let{isValid:Re,value:Ie}=x(Oe,be);if(!Re)throw new Error("Point.fromHex: invalid y coordinate");const we=(Ie&_1n$4)===_1n$4,oe=(Ce&128)!==0;if(!Pe&&Ie===_0n$2&&oe)throw new Error("Point.fromHex: x=0 and x_0=1");return oe!==we&&(Ie=b(-Ie)),ie.fromAffine({x:Ie,y:Le})}static fromPrivateKey(Se){return ee(Se).point}toRawBytes(){const{x:Se,y:Pe}=this.toAffine(),Ue=numberToBytesLE(Pe,r.BYTES);return Ue[Ue.length-1]|=Se&_1n$4?128:0,Ue}toHex(){return bytesToHex(this.toRawBytes())}}ie.BASE=new ie(t.Gx,t.Gy,_1n$4,b(t.Gx*t.Gy)),ie.ZERO=new ie(_0n$2,_1n$4,_1n$4,_0n$2);const{BASE:ue,ZERO:de}=ie,le=wNAF(ie,c*8);function ce(se){return mod(se,n)}function ve(se){return ce(bytesToNumberLE(se))}function ee(se){const Se=c;se=ensureBytes("private key",se,Se);const Pe=ensureBytes("hashed private key",a(se),2*Se),Ue=E(Pe.slice(0,Se)),Be=Pe.slice(Se,2*Se),fe=ve(Ue),ye=ue.multiply(fe),Ce=ye.toRawBytes();return{head:Ue,prefix:Be,scalar:fe,point:ye,pointBytes:Ce}}function he(se){return ee(se).pointBytes}function ne(se=new Uint8Array,...Se){const Pe=concatBytes(...Se);return ve(a(I(Pe,ensureBytes("context",se),!!o)))}function xe(se,Se,Pe={}){se=ensureBytes("message",se),o&&(se=o(se));const{prefix:Ue,scalar:Be,pointBytes:fe}=ee(Se),ye=ne(Pe.context,Ue,se),Ce=ue.multiply(ye).toRawBytes(),Le=ne(Pe.context,Ce,fe,se),Fe=ce(ye+Le*Be);D(Fe);const Oe=concatBytes(Ce,numberToBytesLE(Fe,r.BYTES));return ensureBytes("result",Oe,c*2)}const te=VERIFY_DEFAULT;function ae(se,Se,Pe,Ue=te){const{context:Be,zip215:fe}=Ue,ye=r.BYTES;se=ensureBytes("signature",se,2*ye),Se=ensureBytes("message",Se),o&&(Se=o(Se));const Ce=bytesToNumberLE(se.slice(ye,2*ye));let Le,Fe,Oe;try{Le=ie.fromHex(Pe,fe),Fe=ie.fromHex(se.slice(0,ye),fe),Oe=ue.multiplyUnsafe(Ce)}catch{return!1}if(!fe&&Le.isSmallOrder())return!1;const be=ne(Be,Fe.toRawBytes(),Le.toRawBytes(),Se);return Fe.add(Le.multiplyUnsafe(be)).subtract(Oe).clearCofactor().equals(ie.ZERO)}return ue._setWindowSize(8),{CURVE:t,getPublicKey:he,sign:xe,verify:ae,ExtendedPoint:ie,utils:{getExtendedPublicKey:ee,randomPrivateKey:()=>l(r.BYTES),precompute(se=8,Se=ie.BASE){return Se._setWindowSize(se),Se.multiply(BigInt(3)),Se}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$3=BigInt(1);function validateOpts$1(e){return validateObject(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}function montgomery(e){const t=validateOpts$1(e),{P:r}=t,n=N=>mod(N,r),o=t.montgomeryBits,a=Math.ceil(o/8),l=t.nByteLength,c=t.adjustScalarBytes||(N=>N),u=t.powPminus2||(N=>pow(N,r-BigInt(2),r));function _(N,H,ie){const ue=n(N*(H-ie));return H=n(H-ue),ie=n(ie+ue),[H,ie]}function b(N){if(typeof N=="bigint"&&_0n$1<=N&&N=_0n$1;te--){const ae=ue>>te&_1n$3;he^=ae,ne=_(he,le,ve),le=ne[0],ve=ne[1],ne=_(he,ce,ee),ce=ne[0],ee=ne[1],he=ae;const ge=le+ce,se=n(ge*ge),Se=le-ce,Pe=n(Se*Se),Ue=se-Pe,Be=ve+ee,fe=ve-ee,ye=n(fe*ge),Ce=n(Be*Se),Le=ye+Ce,Fe=ye-Ce;ve=n(Le*Le),ee=n(de*n(Fe*Fe)),le=n(se*Pe),ce=n(Ue*(se+n(x*Ue)))}ne=_(he,le,ve),le=ne[0],ve=ne[1],ne=_(he,ce,ee),ce=ne[0],ee=ne[1];const xe=u(ce);return n(le*xe)}function I(N){return numberToBytesLE(n(N),a)}function k(N){const H=ensureBytes("u coordinate",N,a);return l===a&&(H[l-1]&=127),bytesToNumberLE(H)}function T(N){const H=ensureBytes("scalar",N);if(H.length!==a&&H.length!==l)throw new Error(`Expected ${a} or ${l} bytes, got ${H.length}`);return bytesToNumberLE(c(H))}function O(N,H){const ie=k(H),ue=T(N),de=E(ie,ue);if(de===_0n$1)throw new Error("Invalid private or public key received");return I(de)}const $=I(t.Gu);function D(N){return O(N,$)}return{scalarMult:O,scalarMultBase:D,getSharedSecret:(N,H)=>O(N,H),getPublicKey:N=>D(N),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:$}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n$2=BigInt(1),_2n$1=BigInt(2),_5n=BigInt(5),_10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80);function ed25519_pow_2_252_3(e){const t=ED25519_P,n=e*e%t*e%t,o=pow2(n,_2n$1,t)*n%t,a=pow2(o,_1n$2,t)*e%t,l=pow2(a,_5n,t)*a%t,c=pow2(l,_10n,t)*l%t,u=pow2(c,_20n,t)*c%t,_=pow2(u,_40n,t)*u%t,b=pow2(_,_80n,t)*_%t,x=pow2(b,_80n,t)*_%t,E=pow2(x,_10n,t)*l%t;return{pow_p_5_8:pow2(E,_2n$1,t)*e%t,b2:n}}function adjustScalarBytes(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function uvRatio(e,t){const r=ED25519_P,n=mod(t*t*t,r),o=mod(n*n*t,r),a=ed25519_pow_2_252_3(e*o).pow_p_5_8;let l=mod(e*n*a,r);const c=mod(t*l*l,r),u=l,_=mod(l*ED25519_SQRT_M1,r),b=c===e,x=c===mod(-e,r),E=c===mod(-e*ED25519_SQRT_M1,r);return b&&(l=u),(x||E)&&(l=_),isNegativeLE(l,r)&&(l=mod(-l,r)),{isValid:b||x,value:l}}const Fp$1=Field(ED25519_P,void 0,!0),ed25519Defaults={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Fp$1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512$3,randomBytes:randomBytes$1,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults);function ed25519_domain(e,t,r){if(t.length>255)throw new Error("Context is too big");return concatBytes$1(utf8ToBytes$1("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}({...ed25519Defaults});({...ed25519Defaults});const x25519=(()=>montgomery({P:ED25519_P,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=ED25519_P,{pow_p_5_8:r,b2:n}=ed25519_pow_2_252_3(e);return mod(pow2(r,BigInt(3),t)*n,t)},adjustScalarBytes,randomBytes:randomBytes$1}))(),ELL2_C1=(Fp$1.ORDER+BigInt(3))/BigInt(8);Fp$1.pow(_2n$1,ELL2_C1);Fp$1.sqrt(Fp$1.neg(Fp$1.ONE));(Fp$1.ORDER-BigInt(5))/BigInt(8);BigInt(486662);FpSqrtEven(Fp$1,Fp$1.neg(BigInt(486664)));BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class HMAC extends Hash{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,hash$1(t);const n=toBytes$1(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,a=new Uint8Array(o);a.set(n.length>o?t.create().update(n).digest():n);for(let l=0;lnew HMAC(e,t).update(r).digest();hmac$1.create=(e,t)=>new HMAC(e,t);function extract(e,t,r){return hash$1(e),r===void 0&&(r=new Uint8Array(e.outputLen)),hmac$1(e,toBytes$1(r),toBytes$1(t))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,r,n=32){if(hash$1(e),number$2(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(n/e.outputLen);r===void 0&&(r=EMPTY_BUFFER);const a=new Uint8Array(o*e.outputLen),l=hmac$1.create(e,t),c=l._cloneInto(),u=new Uint8Array(l.outputLen);for(let _=0;_e&t^~e&r,Maj=(e,t,r)=>e&t^e&r^t&r,SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:t,B:r,C:n,D:o,E:a,F:l,G:c,H:u}=this;return[t,r,n,o,a,l,c,u]}set(t,r,n,o,a,l,c,u){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=a|0,this.F=l|0,this.G=c|0,this.H=u|0}process(t,r){for(let x=0;x<16;x++,r+=4)SHA256_W[x]=t.getUint32(r,!1);for(let x=16;x<64;x++){const E=SHA256_W[x-15],I=SHA256_W[x-2],k=rotr(E,7)^rotr(E,18)^E>>>3,T=rotr(I,17)^rotr(I,19)^I>>>10;SHA256_W[x]=T+SHA256_W[x-7]+k+SHA256_W[x-16]|0}let{A:n,B:o,C:a,D:l,E:c,F:u,G:_,H:b}=this;for(let x=0;x<64;x++){const E=rotr(c,6)^rotr(c,11)^rotr(c,25),I=b+E+Chi(c,u,_)+SHA256_K[x]+SHA256_W[x]|0,T=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,o,a)|0;b=_,_=u,u=c,c=l+I|0,l=a,a=o,o=n,n=I+T|0}n=n+this.A|0,o=o+this.B|0,a=a+this.C|0,l=l+this.D|0,c=c+this.E|0,u=u+this.F|0,_=_+this.G|0,b=b+this.H|0,this.set(n,o,a,l,c,u,_,b)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256$3=wrapConstructor(()=>new SHA256),pureJsCrypto={hashSHA256(e){return sha256$3(e)},getHKDF(e,t){const r=extract(sha256$3,t,e),o=expand(sha256$3,r,void 0,96),a=o.subarray(0,32),l=o.subarray(32,64),c=o.subarray(64,96);return[a,l,c]},generateX25519KeyPair(){const e=x25519.utils.randomPrivateKey();return{publicKey:x25519.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:x25519.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return x25519.getSharedSecret(e,t)},chaCha20Poly1305Encrypt(e,t,r,n){return chacha20poly1305(n,t,r).encrypt(e)},chaCha20Poly1305Decrypt(e,t,r,n,o){return chacha20poly1305(n,t,r).decrypt(e,o)}},allocUnsafe$1=e=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e),uint16BEEncode=e=>{const t=allocUnsafe$1(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};uint16BEEncode.bytes=2;const uint16BEDecode=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};uint16BEDecode.bytes=2;function encode0(e){return concat$1([e.ne,e.ciphertext],e.ne.length+e.ciphertext.length)}function encode1(e){return concat$1([e.ne,e.ns,e.ciphertext],e.ne.length+e.ns.length+e.ciphertext.length)}function encode2(e){return concat$1([e.ns,e.ciphertext],e.ns.length+e.ciphertext.length)}function decode0(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:new Uint8Array(0)}}function decode1(e){if(e.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}function decode2(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}const CHACHA_TAG_LENGTH=16;function encryptStream(e,t){return async function*(r){for await(const n of r)for(let o=0;on.length&&(a=n.length);const l=e.encrypt(n.subarray(o,a),e.session);t?.encryptedPackets.increment(),yield uint16BEEncode(l.byteLength),yield l}}}function decryptStream(e,t){return async function*(r){for await(const n of r)for(let o=0;on.length&&(a=n.length),a-CHACHA_TAG_LENGTH0;)c.push(_%a),_=_/a|0}for(o=0;e[o]===0&&o=0;--o)n+=t[c[o]]}if(r){var b=new RegExp(".{1,"+r+"}","g");n=n.match(b).join(`\r +`).forEach(function(l){o=l.indexOf(":"),r=l.substring(0,o).trim().toLowerCase(),n=l.substring(o+1).trim(),!(!r||t[r]&&ignoreDuplicateOf[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t},$internals=Symbol("internals"),$defaults=Symbol("defaults");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return e===!1||e==null?e:String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}function matchHeaderValue(e,t,r,n){if(utils.isFunction(n))return n.call(this,t,r);if(!!utils.isString(t)){if(utils.isString(n))return t.indexOf(n)!==-1;if(utils.isRegExp(n))return n.test(t)}}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function buildAccessors(e,t){const r=utils.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(o,a,l){return this[n].call(this,t,o,a,l)},configurable:!0})})}function findKey(e,t){t=t.toLowerCase();const r=Object.keys(e);let n=r.length,o;for(;n-- >0;)if(o=r[n],t===o.toLowerCase())return o;return null}function AxiosHeaders(e,t){e&&this.set(e),this[$defaults]=t||null}Object.assign(AxiosHeaders.prototype,{set:function(e,t,r){const n=this;function o(a,l,c){const u=normalizeHeader(l);if(!u)throw new Error("header name must be a non-empty string");const _=findKey(n,u);_&&c!==!0&&(n[_]===!1||c===!1)||(utils.isArray(a)?a=a.map(normalizeValue):a=normalizeValue(a),n[_||l]=a)}return utils.isPlainObject(e)?utils.forEach(e,(a,l)=>{o(a,l,t)}):o(t,e,r),this},get:function(e,t){if(e=normalizeHeader(e),!e)return;const r=findKey(this,e);if(r){const n=this[r];if(!t)return n;if(t===!0)return parseTokens(n);if(utils.isFunction(t))return t.call(this,n,r);if(utils.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}},has:function(e,t){if(e=normalizeHeader(e),e){const r=findKey(this,e);return!!(r&&(!t||matchHeaderValue(this,this[r],r,t)))}return!1},delete:function(e,t){const r=this;let n=!1;function o(a){if(a=normalizeHeader(a),a){const l=findKey(r,a);l&&(!t||matchHeaderValue(r,r[l],l,t))&&(delete r[l],n=!0)}}return utils.isArray(e)?e.forEach(o):o(e),n},clear:function(){return Object.keys(this).forEach(this.delete.bind(this))},normalize:function(e){const t=this,r={};return utils.forEach(this,(n,o)=>{const a=findKey(r,o);if(a){t[a]=normalizeValue(n),delete t[o];return}const l=e?formatHeader(o):String(o).trim();l!==o&&delete t[o],t[l]=normalizeValue(n),r[l]=!0}),this},toJSON:function(){const e=Object.create(null);return utils.forEach(Object.assign({},this[$defaults]||null,this),(t,r)=>{t==null||t===!1||(e[r]=utils.isArray(t)?t.join(", "):t)}),e}});Object.assign(AxiosHeaders,{from:function(e){return utils.isString(e)?new this(parseHeaders(e)):e instanceof this?e:new this(e)},accessor:function(e){const r=(this[$internals]=this[$internals]={accessors:{}}).accessors,n=this.prototype;function o(a){const l=normalizeHeader(a);r[l]||(buildAccessors(n,a),r[l]=!0)}return utils.isArray(e)?e.forEach(o):o(e),this}});AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]);utils.freezeMethods(AxiosHeaders.prototype);utils.freezeMethods(AxiosHeaders);function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o=0,a=0,l;return t=t!==void 0?t:1e3,function(u){const _=Date.now(),b=n[a];l||(l=_),r[o]=u,n[o]=_;let x=a,E=0;for(;x!==o;)E+=r[x++],x=x%e;if(o=(o+1)%e,o===a&&(a=(a+1)%e),_-l{const a=o.loaded,l=o.lengthComputable?o.total:void 0,c=a-r,u=n(c),_=a<=l;r=a;const b={loaded:a,total:l,progress:l?a/l:void 0,bytes:c,rate:u||void 0,estimated:u&&l&&_?(l-a)/u:void 0};b[t?"download":"upload"]=!0,e(b)}}function xhrAdapter(e){return new Promise(function(r,n){let o=e.data;const a=AxiosHeaders.from(e.headers).normalize(),l=e.responseType;let c;function u(){e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}utils.isFormData(o)&&platform.isStandardBrowserEnv&&a.setContentType(!1);let _=new XMLHttpRequest;if(e.auth){const I=e.auth.username||"",k=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";a.set("Authorization","Basic "+btoa(I+":"+k))}const b=buildFullPath(e.baseURL,e.url);_.open(e.method.toUpperCase(),buildURL(b,e.params,e.paramsSerializer),!0),_.timeout=e.timeout;function x(){if(!_)return;const I=AxiosHeaders.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),T={data:!l||l==="text"||l==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:I,config:e,request:_};settle(function($){r($),u()},function($){n($),u()},T),_=null}if("onloadend"in _?_.onloadend=x:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(x)},_.onabort=function(){!_||(n(new AxiosError("Request aborted",AxiosError.ECONNABORTED,e,_)),_=null)},_.onerror=function(){n(new AxiosError("Network Error",AxiosError.ERR_NETWORK,e,_)),_=null},_.ontimeout=function(){let k=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const T=e.transitional||transitionalDefaults;e.timeoutErrorMessage&&(k=e.timeoutErrorMessage),n(new AxiosError(k,T.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,e,_)),_=null},platform.isStandardBrowserEnv){const I=(e.withCredentials||isURLSameOrigin(b))&&e.xsrfCookieName&&cookies.read(e.xsrfCookieName);I&&a.set(e.xsrfHeaderName,I)}o===void 0&&a.setContentType(null),"setRequestHeader"in _&&utils.forEach(a.toJSON(),function(k,T){_.setRequestHeader(T,k)}),utils.isUndefined(e.withCredentials)||(_.withCredentials=!!e.withCredentials),l&&l!=="json"&&(_.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&_.addEventListener("progress",progressEventReducer(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&_.upload&&_.upload.addEventListener("progress",progressEventReducer(e.onUploadProgress)),(e.cancelToken||e.signal)&&(c=I=>{!_||(n(!I||I.type?new CanceledError(null,e,_):I),_.abort(),_=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));const E=parseProtocol(b);if(E&&platform.protocols.indexOf(E)===-1){n(new AxiosError("Unsupported protocol "+E+":",AxiosError.ERR_BAD_REQUEST,e));return}_.send(o||null)})}const adapters={http:xhrAdapter,xhr:xhrAdapter},adapters$1={getAdapter:e=>{if(utils.isString(e)){const t=adapters[e];if(!e)throw Error(utils.hasOwnProp(e)?`Adapter '${e}' is not available in the build`:`Can not resolve adapter '${e}'`);return t}if(!utils.isFunction(e))throw new TypeError("adapter is not a function");return e},adapters},DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function getDefaultAdapter(){let e;return typeof XMLHttpRequest<"u"?e=adapters$1.getAdapter("xhr"):typeof process<"u"&&utils.kindOf(process)==="process"&&(e=adapters$1.getAdapter("http")),e}function stringifySafely(e,t,r){if(utils.isString(e))try{return(t||JSON.parse)(e),utils.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}const defaults$1={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(t,r){const n=r.getContentType()||"",o=n.indexOf("application/json")>-1,a=utils.isObject(t);if(a&&utils.isHTMLForm(t)&&(t=new FormData(t)),utils.isFormData(t))return o&&o?JSON.stringify(formDataToJSON(t)):t;if(utils.isArrayBuffer(t)||utils.isBuffer(t)||utils.isStream(t)||utils.isFile(t)||utils.isBlob(t))return t;if(utils.isArrayBufferView(t))return t.buffer;if(utils.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(t,this.formSerializer).toString();if((c=utils.isFileList(t))||n.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return toFormData(c?{"files[]":t}:t,u&&new u,this.formSerializer)}}return a||o?(r.setContentType("application/json",!1),stringifySafely(t)):t}],transformResponse:[function(t){const r=this.transitional||defaults$1.transitional,n=r&&r.forcedJSONParsing,o=this.responseType==="json";if(t&&utils.isString(t)&&(n&&!this.responseType||o)){const l=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(c){if(l)throw c.name==="SyntaxError"?AxiosError.from(c,AxiosError.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils.forEach(["delete","get","head"],function(t){defaults$1.headers[t]={}});utils.forEach(["post","put","patch"],function(t){defaults$1.headers[t]=utils.merge(DEFAULT_CONTENT_TYPE)});function transformData(e,t){const r=this||defaults$1,n=t||r,o=AxiosHeaders.from(n.headers);let a=n.data;return utils.forEach(e,function(c){a=c.call(r,a,o.normalize(),t?t.status:void 0)}),o.normalize(),a}function isCancel(e){return!!(e&&e.__CANCEL__)}function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}function dispatchRequest(e){return throwIfCancellationRequested(e),e.headers=AxiosHeaders.from(e.headers),e.data=transformData.call(e,e.transformRequest),(e.adapter||defaults$1.adapter)(e).then(function(n){return throwIfCancellationRequested(e),n.data=transformData.call(e,e.transformResponse,n),n.headers=AxiosHeaders.from(n.headers),n},function(n){return isCancel(n)||(throwIfCancellationRequested(e),n&&n.response&&(n.response.data=transformData.call(e,e.transformResponse,n.response),n.response.headers=AxiosHeaders.from(n.response.headers))),Promise.reject(n)})}function mergeConfig(e,t){t=t||{};const r={};function n(_,b){return utils.isPlainObject(_)&&utils.isPlainObject(b)?utils.merge(_,b):utils.isPlainObject(b)?utils.merge({},b):utils.isArray(b)?b.slice():b}function o(_){if(utils.isUndefined(t[_])){if(!utils.isUndefined(e[_]))return n(void 0,e[_])}else return n(e[_],t[_])}function a(_){if(!utils.isUndefined(t[_]))return n(void 0,t[_])}function l(_){if(utils.isUndefined(t[_])){if(!utils.isUndefined(e[_]))return n(void 0,e[_])}else return n(void 0,t[_])}function c(_){if(_ in t)return n(e[_],t[_]);if(_ in e)return n(void 0,e[_])}const u={url:a,method:a,data:a,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:c};return utils.forEach(Object.keys(e).concat(Object.keys(t)),function(b){const x=u[b]||o,E=x(b);utils.isUndefined(E)&&x!==c||(r[b]=E)}),r}const VERSION$2="1.1.2",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};validators$1.transitional=function(t,r,n){function o(a,l){return"[Axios v"+VERSION$2+"] Transitional option '"+a+"'"+l+(n?". "+n:"")}return(a,l,c)=>{if(t===!1)throw new AxiosError(o(l," has been removed"+(r?" in "+r:"")),AxiosError.ERR_DEPRECATED);return r&&!deprecatedWarnings[l]&&(deprecatedWarnings[l]=!0,console.warn(o(l," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(a,l,c):!0}};function assertOptions(e,t,r){if(typeof e!="object")throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const a=n[o],l=t[a];if(l){const c=e[a],u=c===void 0||l(c,a,e);if(u!==!0)throw new AxiosError("option "+a+" must be "+u,AxiosError.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new AxiosError("Unknown option "+a,AxiosError.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;class Axios{constructor(t){this.defaults=t,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=mergeConfig(this.defaults,r);const n=r.transitional;n!==void 0&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),r.method=(r.method||this.defaults.method||"get").toLowerCase();const o=r.headers&&utils.merge(r.headers.common,r.headers[r.method]);o&&utils.forEach(["delete","get","head","post","put","patch","common"],function(I){delete r.headers[I]}),r.headers=new AxiosHeaders(r.headers,o);const a=[];let l=!0;this.interceptors.request.forEach(function(I){typeof I.runWhen=="function"&&I.runWhen(r)===!1||(l=l&&I.synchronous,a.unshift(I.fulfilled,I.rejected))});const c=[];this.interceptors.response.forEach(function(I){c.push(I.fulfilled,I.rejected)});let u,_=0,b;if(!l){const E=[dispatchRequest.bind(this),void 0];for(E.unshift.apply(E,a),E.push.apply(E,c),b=E.length,u=Promise.resolve(r);_{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](o);n._listeners=null}),this.promise.then=o=>{let a;const l=new Promise(c=>{n.subscribe(c),a=c}).then(o);return l.cancel=function(){n.unsubscribe(a)},l},t(function(a,l,c){n.reason||(n.reason=new CanceledError(a,l,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}static source(){let t;return{token:new CancelToken(function(o){t=o}),cancel:t}}}function spread(e){return function(r){return e.apply(null,r)}}function isAxiosError(e){return utils.isObject(e)&&e.isAxiosError===!0}function createInstance(e){const t=new Axios(e),r=bind$1(Axios.prototype.request,t);return utils.extend(r,Axios.prototype,t,{allOwnKeys:!0}),utils.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return createInstance(mergeConfig(e,o))},r}const axios=createInstance(defaults$1);axios.Axios=Axios;axios.CanceledError=CanceledError;axios.CancelToken=CancelToken;axios.isCancel=isCancel;axios.VERSION=VERSION$2;axios.toFormData=toFormData;axios.AxiosError=AxiosError;axios.Cancel=axios.CanceledError;axios.all=function(t){return Promise.all(t)};axios.spread=spread;axios.isAxiosError=isAxiosError;axios.formToJSON=e=>formDataToJSON(utils.isHTMLForm(e)?new FormData(e):e);L.DomUtil.setTransform||(L.DomUtil.setTransform=function(e,t,r){var n=t||new L.Point(0,0);e.style[L.DomUtil.TRANSFORM]=(L.Browser.ie3d?"translate("+n.x+"px,"+n.y+"px)":"translate3d("+n.x+"px,"+n.y+"px,0)")+(r?" scale("+r+")":"")});L.CanvasLayer=(L.Layer?L.Layer:L.Class).extend({initialize:function(t){this._map=null,this._canvas=null,this._frame=null,this._delegate=null,L.setOptions(this,t)},delegate:function(t){return this._delegate=t,this},needRedraw:function(){return this._frame||(this._frame=L.Util.requestAnimFrame(this.drawLayer,this)),this},_onLayerDidResize:function(t){this._canvas.width=t.newSize.x,this._canvas.height=t.newSize.y},_onLayerDidMove:function(){var t=this._map.containerPointToLayerPoint([0,0]);L.DomUtil.setPosition(this._canvas,t),this.drawLayer()},getEvents:function(){var t={resize:this._onLayerDidResize,moveend:this._onLayerDidMove};return this._map.options.zoomAnimation&&L.Browser.any3d&&(t.zoomanim=this._animateZoom),t},onAdd:function(t){this._map=t,this._canvas=L.DomUtil.create("canvas","leaflet-layer"),this.tiles={};var r=this._map.getSize();this._canvas.width=r.x,this._canvas.height=r.y;var n=this._map.options.zoomAnimation&&L.Browser.any3d;L.DomUtil.addClass(this._canvas,"leaflet-zoom-"+(n?"animated":"hide")),this.options.pane.appendChild(this._canvas),t.on(this.getEvents(),this);var o=this._delegate||this;o.onLayerDidMount&&o.onLayerDidMount(),this.needRedraw();var a=this;setTimeout(function(){a._onLayerDidMove()},0)},onRemove:function(t){var r=this._delegate||this;r.onLayerWillUnmount&&r.onLayerWillUnmount(),this.options.pane.removeChild(this._canvas),t.off(this.getEvents(),this),this._canvas=null},addTo:function(t){return t.addLayer(this),this},drawLayer:function(){var t=this._map.getSize(),r=this._map.getBounds(),n=this._map.getZoom(),o=this._map.options.crs.project(this._map.getCenter()),a=this._map.options.crs.project(this._map.containerPointToLatLng(this._map.getSize())),l=this._delegate||this;l.onDrawLayer&&l.onDrawLayer({layer:this,canvas:this._canvas,bounds:r,size:t,zoom:n,center:o,corner:a}),this._frame=null},_setTransform:function(t,r,n){var o=r||new L.Point(0,0);t.style[L.DomUtil.TRANSFORM]=(L.Browser.ie3d?"translate("+o.x+"px,"+o.y+"px)":"translate3d("+o.x+"px,"+o.y+"px,0)")+(n?" scale("+n+")":"")},_animateZoom:function(t){var r=this._map.getZoomScale(t.zoom),n=L.Layer?this._map._latLngToNewLayerPoint(this._map.getBounds().getNorthWest(),t.zoom,t.center):this._map._getCenterOffset(t.center)._multiplyBy(-r).subtract(this._map._getMapPanePos());L.DomUtil.setTransform(this._canvas,n,r)}});L.canvasLayer=function(e){return new L.CanvasLayer(e)};L.Control.Velocity=L.Control.extend({options:{position:"bottomleft",emptyString:"Unavailable",angleConvention:"bearingCCW",showCardinal:!1,speedUnit:"m/s",directionString:"Direction",speedString:"Speed",onAdd:null,onRemove:null},onAdd:function(t){return this._container=L.DomUtil.create("div","leaflet-control-velocity"),L.DomEvent.disableClickPropagation(this._container),t.on("mousemove",this._onMouseMove,this),this._container.innerHTML=this.options.emptyString,this.options.leafletVelocity.options.onAdd&&this.options.leafletVelocity.options.onAdd(),this._container},onRemove:function(t){t.off("mousemove",this._onMouseMove,this),this.options.leafletVelocity.options.onRemove&&this.options.leafletVelocity.options.onRemove()},vectorToSpeed:function(t,r,n){var o=Math.sqrt(Math.pow(t,2)+Math.pow(r,2));return n==="k/h"?this.meterSec2kilometerHour(o):n==="kt"?this.meterSec2Knots(o):n==="mph"?this.meterSec2milesHour(o):o},vectorToDegrees:function(t,r,n){n.endsWith("CCW")&&(r=r>0?r=-r:Math.abs(r));var o=Math.sqrt(Math.pow(t,2)+Math.pow(r,2)),a=Math.atan2(t/o,r/o),l=a*180/Math.PI+180;return(n==="bearingCW"||n==="meteoCCW")&&(l+=180,l>=360&&(l-=360)),l},degreesToCardinalDirection:function(t){var r="";return t>=0&&t<11.25||t>=348.75?r="N":t>=11.25&&t<33.75?r="NNW":t>=33.75&&t<56.25?r="NW":t>=56.25&&t<78.75?r="WNW":t>=78.25&&t<101.25?r="W":t>=101.25&&t<123.75?r="WSW":t>=123.75&&t<146.25?r="SW":t>=146.25&&t<168.75?r="SSW":t>=168.75&&t<191.25?r="S":t>=191.25&&t<213.75?r="SSE":t>=213.75&&t<236.25?r="SE":t>=236.25&&t<258.75?r="ESE":t>=258.75&&t<281.25?r="E":t>=281.25&&t<303.75?r="ENE":t>=303.75&&t<326.25?r="NE":t>=326.25&&t<348.75&&(r="NNE"),r},meterSec2Knots:function(t){return t/.514},meterSec2kilometerHour:function(t){return t*3.6},meterSec2milesHour:function(t){return t*2.23694},_onMouseMove:function(t){var r=this,n=this.options.leafletVelocity._map.containerPointToLatLng(L.point(t.containerPoint.x,t.containerPoint.y)),o=this.options.leafletVelocity._windy.interpolatePoint(n.lng,n.lat),a="";if(o&&!isNaN(o[0])&&!isNaN(o[1])&&o[2]){var l=r.vectorToDegrees(o[0],o[1],this.options.angleConvention),c=this.options.showCardinal?" (".concat(r.degreesToCardinalDirection(l),") "):"";a=" ".concat(this.options.velocityType," ").concat(this.options.directionString,": ").concat(l.toFixed(2),"\xB0").concat(c,", ").concat(this.options.velocityType," ").concat(this.options.speedString,": ").concat(r.vectorToSpeed(o[0],o[1],this.options.speedUnit).toFixed(2)," ").concat(this.options.speedUnit)}else a=this.options.emptyString;r._container.innerHTML=a}});L.Map.mergeOptions({positionControl:!1});L.Map.addInitHook(function(){this.options.positionControl&&(this.positionControl=new L.Control.MousePosition,this.addControl(this.positionControl))});L.control.velocity=function(e){return new L.Control.Velocity(e)};L.VelocityLayer=(L.Layer?L.Layer:L.Class).extend({options:{displayValues:!0,displayOptions:{velocityType:"Velocity",position:"bottomleft",emptyString:"No velocity data"},maxVelocity:10,colorScale:null,data:null},_map:null,_canvasLayer:null,_windy:null,_context:null,_timer:0,_mouseControl:null,initialize:function(t){L.setOptions(this,t)},onAdd:function(t){this._paneName=this.options.paneName||"overlayPane";var r=t._panes.overlayPane;t.getPane&&(r=t.getPane(this._paneName),r||(r=t.createPane(this._paneName))),this._canvasLayer=L.canvasLayer({pane:r}).delegate(this),this._canvasLayer.addTo(t),this._map=t},onRemove:function(t){this._destroyWind()},setData:function(t){this.options.data=t,this._windy&&(this._windy.setData(t),this._clearAndRestart()),this.fire("load")},setOpacity:function(t){this._canvasLayer.setOpacity(t)},setOptions:function(t){this.options=Object.assign(this.options,t),t.hasOwnProperty("displayOptions")&&(this.options.displayOptions=Object.assign(this.options.displayOptions,t.displayOptions),this._initMouseHandler(!0)),t.hasOwnProperty("data")&&(this.options.data=t.data),this._windy&&(this._windy.setOptions(t),t.hasOwnProperty("data")&&this._windy.setData(t.data),this._clearAndRestart()),this.fire("load")},onDrawLayer:function(t,r){var n=this;if(!this._windy){this._initWindy(this);return}!this.options.data||(this._timer&&clearTimeout(n._timer),this._timer=setTimeout(function(){n._startWindy()},750))},_startWindy:function(){var t=this._map.getBounds(),r=this._map.getSize();this._windy.start([[0,0],[r.x,r.y]],r.x,r.y,[[t._southWest.lng,t._southWest.lat],[t._northEast.lng,t._northEast.lat]])},_initWindy:function(t){var r=Object.assign({canvas:t._canvasLayer._canvas,map:this._map},t.options);this._windy=new Windy(r),this._context=this._canvasLayer._canvas.getContext("2d"),this._canvasLayer._canvas.classList.add("velocity-overlay"),this.onDrawLayer(),this._map.on("dragstart",t._windy.stop),this._map.on("dragend",t._clearAndRestart),this._map.on("zoomstart",t._windy.stop),this._map.on("zoomend",t._clearAndRestart),this._map.on("resize",t._clearWind),this._initMouseHandler(!1)},_initMouseHandler:function(t){if(t&&(this._map.removeControl(this._mouseControl),this._mouseControl=!1),!this._mouseControl&&this.options.displayValues){var r=this.options.displayOptions||{};r.leafletVelocity=this,this._mouseControl=L.control.velocity(r).addTo(this._map)}},_clearAndRestart:function(){this._context&&this._context.clearRect(0,0,3e3,3e3),this._windy&&this._startWindy()},_clearWind:function(){this._windy&&this._windy.stop(),this._context&&this._context.clearRect(0,0,3e3,3e3)},_destroyWind:function(){this._timer&&clearTimeout(this._timer),this._windy&&this._windy.stop(),this._context&&this._context.clearRect(0,0,3e3,3e3),this._mouseControl&&this._map.removeControl(this._mouseControl),this._mouseControl=null,this._windy=null,this._map.removeLayer(this._canvasLayer)}});L.velocityLayer=function(e){return new L.VelocityLayer(e)};var Windy=function(t){var r=t.minVelocity||0,n=t.maxVelocity||10,o=(t.velocityScale||.005)*(Math.pow(window.devicePixelRatio,1/3)||1),a=t.particleAge||90,l=t.lineWidth||1,c=t.particleMultiplier||1/300,u=Math.pow(window.devicePixelRatio,1/3)||1.6,_=t.frameRate||15,b=1e3/_,x=.97,E=["rgb(36,104, 180)","rgb(60,157, 194)","rgb(128,205,193 )","rgb(151,218,168 )","rgb(198,231,181)","rgb(238,247,217)","rgb(255,238,159)","rgb(252,217,125)","rgb(255,182,100)","rgb(252,150,75)","rgb(250,112,52)","rgb(245,64,32)","rgb(237,45,28)","rgb(220,24,32)","rgb(180,0,35)"],I=t.colorScale||E,k=[NaN,NaN,null],T,O,$=t.data,D,N,H,ie,ue,de,le,ce=function(oe){$=oe},ve=function(oe){oe.hasOwnProperty("minVelocity")&&(r=oe.minVelocity),oe.hasOwnProperty("maxVelocity")&&(n=oe.maxVelocity),oe.hasOwnProperty("velocityScale")&&(o=(oe.velocityScale||.005)*(Math.pow(window.devicePixelRatio,1/3)||1)),oe.hasOwnProperty("particleAge")&&(a=oe.particleAge),oe.hasOwnProperty("lineWidth")&&(l=oe.lineWidth),oe.hasOwnProperty("particleMultiplier")&&(c=oe.particleMultiplier),oe.hasOwnProperty("opacity")&&(x=+oe.opacity),oe.hasOwnProperty("frameRate")&&(_=oe.frameRate),b=1e3/_},ee=function(oe,pe,ke,Ne,ze,Xe){var Je=1-oe,rt=1-pe,qe=Je*rt,Ve=oe*rt,Ae=Je*pe,He=oe*pe,Ge=ke[0]*qe+Ne[0]*Ve+ze[0]*Ae+Xe[0]*He,Ze=ke[1]*qe+Ne[1]*Ve+ze[1]*Ae+Xe[1]*He;return[Ge,Ze,Math.sqrt(Ge*Ge+Ze*Ze)]},he=function(oe,pe){var ke=oe.data,Ne=pe.data;return{header:oe.header,data:function(Xe){return[ke[Xe],Ne[Xe]]},interpolate:ee}},ne=function(oe){var pe=null,ke=null;return oe.forEach(function(Ne){switch(Ne.header.parameterCategory+","+Ne.header.parameterNumber){case"1,2":case"2,2":pe=Ne;break;case"1,3":case"2,3":ke=Ne;break}}),he(pe,ke)},xe=function(oe,pe){var ke=!0;oe.length<2&&(ke=!1),ke||console.log("Windy Error: data must have at least two components (u,v)"),T=ne(oe);var Ne=T.header;if(Ne.hasOwnProperty("gridDefinitionTemplate")&&Ne.gridDefinitionTemplate!=0&&(ke=!1),ke||console.log("Windy Error: Only data with Latitude_Longitude coordinates is supported"),ke=!0,N=Ne.lo1,H=Ne.la1,ie=Ne.dx,ue=Ne.dy,de=Ne.nx,le=Ne.ny,Ne.hasOwnProperty("scanMode")){var ze=Ne.scanMode.toString(2);ze=("0"+ze).slice(-8);var Xe=ze.split("").map(Number).map(Boolean);Xe[0]&&(ie=-ie),Xe[1]&&(ue=-ue),Xe[2]&&(ke=!1),Xe[3]&&(ke=!1),Xe[4]&&(ke=!1),Xe[5]&&(ke=!1),Xe[6]&&(ke=!1),Xe[7]&&(ke=!1),ke||console.log("Windy Error: Data with scanMode: "+Ne.scanMode+" is not supported.")}D=new Date(Ne.refTime),D.setHours(D.getHours()+Ne.forecastTime),O=[];for(var Je=0,rt=Math.floor(de*ie)>=360,qe=0;qe1e3){setTimeout(Ae,25);return}Ue(rt,pe,Ne)})()},Fe,Oe=function(oe,pe){function ke(Ze,$e){return I.indexFor=function(me){return Math.max(0,Math.min(I.length-1,Math.round((me-Ze)/($e-Ze)*(I.length-1))))},I}var Ne=ke(r,n),ze=Ne.map(function(){return[]}),Xe=Math.round(oe.width*oe.height*c);se()&&(Xe*=u);for(var Je="rgba(0, 0, 0, ".concat(x,")"),rt=[],qe=0;qea&&(pe.randomize(Ze).age=0);var $e=Ze.x,me=Ze.y,Ee=pe($e,me),je=Ee[2];if(je===null)Ze.age=a;else{var nt=$e+Ee[0],ot=me+Ee[1];pe(nt,ot)[2]!==null?(Ze.xt=nt,Ze.yt=ot,ze[Ne.indexFor(je)].push(Ze)):(Ze.x=nt,Ze.y=ot)}Ze.age+=1})}var Ae=t.canvas.getContext("2d");Ae.lineWidth=l,Ae.fillStyle=Je,Ae.globalAlpha=.6;function He(){var Ze="lighter";Ae.globalCompositeOperation="destination-in",Ae.fillRect(oe.x,oe.y,oe.width,oe.height),Ae.globalCompositeOperation=Ze,Ae.globalAlpha=x===0?0:x*.9,ze.forEach(function($e,me){$e.length>0&&(Ae.beginPath(),Ae.strokeStyle=Ne[me],$e.forEach(function(Ee){Ae.moveTo(Ee.x,Ee.y),Ae.lineTo(Ee.xt,Ee.yt),Ee.x=Ee.xt,Ee.y=Ee.yt}),Ae.stroke())})}var Ge=Date.now();(function Ze(){Fe=requestAnimationFrame(Ze);var $e=Date.now(),me=$e-Ge;me>b&&(Ge=$e-me%b,Ve(),He())})()},be=function(oe,pe,ke,Ne){var ze={south:fe(Ne[0][1]),north:fe(Ne[1][1]),east:fe(Ne[1][0]),west:fe(Ne[0][0]),width:pe,height:ke};Re(),xe($,function(Xe){Le(Xe,Be(oe,pe,ke),ze,function(Je,rt){Ie.field=rt,Oe(Je,rt)})})},Re=function(){Ie.field&&Ie.field.release(),Fe&&cancelAnimationFrame(Fe)},Ie={params:t,start:be,stop:Re,createField:Ue,interpolatePoint:te,setData:ce,setOptions:ve};return Ie};window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)});const leafletVelocity="";let windLayer;function init$1(){return axios.get(config$2.WIND_PROVIDER).then(e=>{windLayer=L$2.velocityLayer({displayValues:!1,data:e.data,maxVelocity:15,velocityScale:.01,colorScale:["rgb(60,157,194)","rgb(128,205,193)","rgb(250,112,52)","rgb(245,64,32)"]})})}function switchLayer(e,t=!1){windLayer&&(t?e.addLayer(windLayer):e.removeLayer(windLayer))}const _export_sfc=(e,t)=>{const r=e.__vccOpts||e;for(const[n,o]of t)r[n]=o;return r},_sfc_main$f={data(){return{start:hooks().subtract(1,"days").format("YYYY-MM-DD"),end:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),cities:{},city:"",timePeriod:[{title:this.$t("history.currentDay"),value:"24hours"},{title:this.$t("history.currentMonth"),value:"currentMonth"},{title:this.$t("history.chooseDates"),value:"chooseDates"}],period:"24hours"}},computed:{startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.end+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))},link(){return`${config$2.REMOTE_PROVIDER}api/sensor/csv/${this.startTimestamp}/${this.endTimestamp}/${this.city}`}},watch:{period(e){e==="24hours"?(this.start=hooks().format("YYYY-MM-DD"),this.end=hooks().format("YYYY-MM-DD")):e==="currentMonth"&&(this.start=hooks().subtract(1,"month").format("YYYY-MM-DD"),this.end=hooks().format("YYYY-MM-DD"))}},async created(){try{const e=await axios.get(`${config$2.REMOTE_PROVIDER}api/sensor/cities`);this.cities=e.data.result;const t=Object.keys(this.cities),r=Object.keys(this.cities[t[0]]);this.city=this.cities[t[0]][r[0]][0]}catch(e){console.log(e.message)}}},_hoisted_1$e=["action"],_hoisted_2$a=["label"],_hoisted_3$8=["value"],_hoisted_4$6=["value"],_hoisted_5$6={key:0,class:"flexline"},_hoisted_6$6=["max"],_hoisted_7$6=["max"],_hoisted_8$6=["value"];function _sfc_render$f(e,t,r,n,o,a){return openBlock(),createElementBlock("form",{action:a.link},[createBaseVNode("section",null,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[0]||(t[0]=l=>o.city=l),class:"block"},[(openBlock(!0),createElementBlock(Fragment,null,renderList(Object.keys(o.cities),(l,c)=>(openBlock(),createElementBlock("optgroup",{label:l,key:c},[(openBlock(!0),createElementBlock(Fragment,null,renderList(Object.keys(o.cities[l]),(u,_)=>(openBlock(),createElementBlock(Fragment,{key:_},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.cities[l][u],(b,x)=>(openBlock(),createElementBlock("option",{value:b,key:x},toDisplayString$1(b),9,_hoisted_3$8))),128))],64))),128))],8,_hoisted_2$a))),128))],512),[[vModelSelect,o.city]])]),createBaseVNode("section",null,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[1]||(t[1]=l=>o.period=l),class:"block"},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.timePeriod,l=>(openBlock(),createElementBlock("option",{value:l.value,key:l.value},toDisplayString$1(l.title),9,_hoisted_4$6))),128))],512),[[vModelSelect,o.period]])]),o.period==="chooseDates"?(openBlock(),createElementBlock("section",_hoisted_5$6,[withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[2]||(t[2]=l=>o.start=l),max:o.maxDate},null,8,_hoisted_6$6),[[vModelText,o.start]]),createTextVNode(" \u2013 "),withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[3]||(t[3]=l=>o.end=l),max:o.maxDate},null,8,_hoisted_7$6),[[vModelText,o.end]])])):createCommentVNode("",!0),createBaseVNode("section",null,[createBaseVNode("input",{type:"submit",value:e.$t("history.button"),class:"block"},null,8,_hoisted_8$6)])],8,_hoisted_1$e)}const HistoryImport=_export_sfc(_sfc_main$f,[["render",_sfc_render$f]]),agents=["QmcQJV9CQ7UCHAtGw55urFS39knSVR2nocNVNv1N1BuWwG","QmYAesHYTymfXyXitPBaHLBrC3dfVrRESFd28gfnbyjo7e","QmQHzQqXe5npsyRfRFrSbjDHTKKRz1cULajerNZrJLAMsK","QmXzPWCya9xakMQY2YLdhscHHhQ7ojNhGJzuunC57FZnta","QmRohqPDqYVwttjxJrhQVtZJH9o5QFBja3NT62aAbNDVkX","QmRjxZ7ccJ5N2HgLmz5we9pezBvP7gDvx2BjDJSw6p1TCE","QmamWhrh3qqaRzbjcZ1Si9k8V2ytoJhhPDzVGyzEAtdUCc","QmZuyyMJRo5Cs4GkARbvkxrBbiP2oRUNpWc7dBmTACZg4T","12D3KooWP2yCMkb67Xj8EkDEDfzvEgMhR7kdun8MvDcvsqoUPmuD","12D3KooWRazGg1wMjjEFaaZGXseHpt3MXrU5oZS2idQZ6M4GPL4U","12D3KooWB7wQJuFyUQL1RjdkEwDQ82msxB4xsLCHHGdJLGxaqrmR","12D3KooWGQAxCSvgAbcVHXxuzaBgzie9HSUStjvnQRQBY2CTjnLU","12D3KooWKDUV8Je6EQLhKDsiQCgzQEDKBo8ukPcxYKmts47nST4D"];function getAgents(){return agents}function setTypeProvider(e){localStorage.setItem("provider_type",e)}function getTypeProvider(){return localStorage.getItem("provider_type")||config$2.DEFAUL_TYPE_PROVIDER}const _sfc_main$e={props:["current"],data(){return{type:this.current,measurements:Object.entries(measurements),store:useStore()}},computed:{availableunits(){let e=[];return this.store.sensors.forEach(t=>{Object.keys(t.data).forEach(r=>{e.push(r)})}),[...new Set(e)]},availableoptions(){let e=[];return this.availableunits.forEach(t=>{measurements[t]&&e.push({name:measurements[t].label,value:t})}),e}},watch:{type:async function(){await this.$router.push({name:"main",params:{provider:getTypeProvider(),type:this.type,zoom:this.$route.params.zoom,lat:this.$route.params.lat,lng:this.$route.params.lng,sensor:this.$route.params.sensor}}),this.$router.go(0)}}},_hoisted_1$d=["value"];function _sfc_render$e(e,t,r,n,o,a){return o.store.sensors.length>0?withDirectives((openBlock(),createElementBlock("select",{key:0,"onUpdate:modelValue":t[0]||(t[0]=l=>o.type=l)},[(openBlock(!0),createElementBlock(Fragment,null,renderList(a.availableoptions,l=>(openBlock(),createElementBlock("option",{key:l.value,value:l.value},toDisplayString$1(l.name),9,_hoisted_1$d))),128))],512)),[[vModelSelect,o.type]]):createCommentVNode("",!0)}const Measures=_export_sfc(_sfc_main$e,[["render",_sfc_render$e]]);function IDBworkflow(e,t,r,n,o){const a=window.indexedDB||window.webkitIndexedDB;if(!a)return;let l=null;const c=a.open(e,t);c.addEventListener("error",u=>{console.warn(u)}),c.addEventListener("success",u=>{if(l=u.target.result,l.objectStoreNames.contains(r)){let _=l.transaction(r,n);_.addEventListener("error",x=>{console.warn(x)});const b=_.objectStore(r);o(b)}}),c.addEventListener("upgradeneeded",u=>{l=u.target.result;const _=u.oldVersion,b=u.newVersion||l.version;console.log("DB updated from version",_,"to",b),l.objectStoreNames.contains(r)||l.createObjectStore(r,{keyPath:"id",autoIncrement:!0})})}function IDBgettable(e,t,r){return new Promise(n=>{let o=[];IDBworkflow(e,t,r,"readonly",a=>{a.openCursor().addEventListener("success",l=>{const c=l.target.result;c?(o.push(c.value),c.continue()):n(o)})})})}const Bookmarks_vue_vue_type_style_index_0_scoped_972c83b9_lang="",_sfc_main$d={data(){return{bookmarks:[],store:useStore()}},methods:{async getbookmarks(){this.bookmarks=await IDBgettable(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable)},deletebookmark(e){IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",t=>{t.delete(e),this.getbookmarks()})},showsensor(){this.$router.go()}},mounted(){this.getbookmarks();const e=new BroadcastChannel(this.store.idbWatcherBroadcast);e.onmessage=t=>{t.data&&this.getbookmarks()}}},_hoisted_1$c=["href"],_hoisted_2$9={key:0,class:"name"},_hoisted_3$7=["onClick"];function _sfc_render$d(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return!o.bookmarks||o.bookmarks.length<1?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("bookmarks.listempty")),1)],64)):(openBlock(!0),createElementBlock(Fragment,{key:1},renderList(o.bookmarks,c=>(openBlock(),createElementBlock("section",{key:c.id,class:"flexline"},[createBaseVNode("a",{href:c.link,onClick:t[0]||(t[0]=withModifiers((...u)=>a.showsensor&&a.showsensor(...u),["prevent"]))},[c.customName?(openBlock(),createElementBlock("b",_hoisted_2$9,toDisplayString$1(c.customName),1)):createCommentVNode("",!0),c.address?(openBlock(),createElementBlock("b",{key:1,class:normalizeClass(c.customName?"addresssm":"adresslg")},toDisplayString$1(c.address),3)):createCommentVNode("",!0)],8,_hoisted_1$c),createBaseVNode("button",{title:"Remove this sensor",onClick:withModifiers(u=>a.deletebookmark(c.id),["prevent"])},[createVNode(l,{icon:"fa-solid fa-xmark"})],8,_hoisted_3$7)]))),128))}const Bookmarks=_export_sfc(_sfc_main$d,[["render",_sfc_render$d],["__scopeId","data-v-972c83b9"]]),Footer_vue_vue_type_style_index_0_scoped_dd20d5cc_lang="",_sfc_main$c={emits:["history"],props:["currentProvider","canHistory","measuretype"],components:{HistoryImport,Measures,Bookmarks},data(){return{isActive:!1,isActiveMenu:!1,isMeasuresPopupOpen:!1,realtime:this.currentProvider==="realtime",wind:!1,messages:config$2.SHOW_MESSAGES,start:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),store:useStore()}},computed:{startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.start+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))}},watch:{async realtime(e){await this.$router.push({name:"main",params:{provider:e?"realtime":"remote",type:this.$route.params.type,zoom:this.$route.params.zoom,lat:this.$route.params.lat,lng:this.$route.params.lng,sensor:this.$route.params.sensor}}),this.$router.go(0)},start(){this.getHistory()},canHistory:{handler(e){e&&this.getHistory()},immediate:!0},wind(e){switchLayer(instanceMap(),e)},messages(e){switchMessagesLayer(instanceMap(),e)}},methods:{toggleOpen(e){this[e]?(this[e]=!1,this.store.removeColorMap()):(this[e]=!0,this.store.colorMap())},toggleIsActive(){this.toggleOpen("isActive")},toggleMobileMenu(){this.toggleOpen("isActiveMenu")},toggleMeasurePopup(e){e.target.classList.contains("footer__close-popup")&&this.$refs.details.open?this.$refs.details.open=!1:this.toggleOpen("isMeasuresPopupOpen")},getHistory(){this.realtime||this.$emit("history",{start:this.startTimestamp,end:this.endTimestamp})}}},_withScopeId$6=e=>(pushScopeId("data-v-dd20d5cc"),e=e(),popScopeId(),e),_hoisted_1$b={class:"mapcontrols"},_hoisted_2$8={style:{display:"none"}},_hoisted_3$6={class:"flexline"},_hoisted_4$5={id:"bookmarks",class:"popover-bottom-left",popover:""},_hoisted_5$5={class:"popovercontrol",popovertarget:"bookmarks"},_hoisted_6$5=["max","disabled"],_hoisted_7$5={class:"flexline"},_hoisted_8$5={id:"mapsettings",class:"popover-bottom-right",popover:""},_hoisted_9$5=["checked"],_hoisted_10$4={for:"realtime"},_hoisted_11$2=["disabled","checked"],_hoisted_12$2={for:"wind"},_hoisted_13$2=["checked"],_hoisted_14$2={for:"messages"},_hoisted_15$3=_withScopeId$6(()=>createBaseVNode("hr",null,null,-1)),_hoisted_16$2={class:"popovercontrol",popovertarget:"mapsettings"};function _sfc_render$c(e,t,r,n,o,a){const l=resolveComponent("Bookmarks"),c=resolveComponent("font-awesome-icon"),u=resolveComponent("Measures"),_=resolveComponent("HistoryImport");return openBlock(),createElementBlock("div",_hoisted_1$b,[createBaseVNode("div",_hoisted_2$8,toDisplayString$1(e.bufer),1),createBaseVNode("div",_hoisted_3$6,[createBaseVNode("div",_hoisted_4$5,[createBaseVNode("h3",null,toDisplayString$1(e.$t("bookmarks.listtitle")),1),createVNode(l)]),createBaseVNode("button",_hoisted_5$5,[createVNode(c,{icon:"fa-solid fa-bookmark"})]),withDirectives(createBaseVNode("input",{type:"date","onUpdate:modelValue":t[0]||(t[0]=b=>o.start=b),max:o.maxDate,disabled:r.currentProvider=="realtime"},null,8,_hoisted_6$5),[[vModelText,o.start]]),createVNode(u,{current:r.measuretype.toLowerCase()},null,8,["current"])]),createBaseVNode("div",_hoisted_7$5,[createBaseVNode("div",_hoisted_8$5,[createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"realtime","onUpdate:modelValue":t[1]||(t[1]=b=>o.realtime=b),type:"checkbox",checked:o.realtime},null,8,_hoisted_9$5),[[vModelCheckbox,o.realtime]]),createBaseVNode("label",_hoisted_10$4,toDisplayString$1(e.$t("provider.realtime")),1)]),createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"wind","onUpdate:modelValue":t[2]||(t[2]=b=>o.wind=b),type:"checkbox",disabled:!o.realtime,checked:o.wind&&o.realtime},null,8,_hoisted_11$2),[[vModelCheckbox,o.wind]]),createBaseVNode("label",_hoisted_12$2,toDisplayString$1(e.$t("layer.wind")),1)]),createBaseVNode("section",null,[withDirectives(createBaseVNode("input",{id:"messages","onUpdate:modelValue":t[3]||(t[3]=b=>o.messages=b),type:"checkbox",checked:o.messages},null,8,_hoisted_13$2),[[vModelCheckbox,o.messages]]),createBaseVNode("label",_hoisted_14$2,toDisplayString$1(e.$t("layer.messages")),1)]),_hoisted_15$3,createBaseVNode("section",null,[createBaseVNode("h3",null,toDisplayString$1(e.$t("history.title")),1),createVNode(_)])]),createBaseVNode("button",_hoisted_16$2,[createVNode(c,{icon:"fa-solid fa-gear"})]),renderSlot(e.$slots,"default",{},void 0,!0)])])}const Footer=_export_sfc(_sfc_main$c,[["render",_sfc_render$c],["__scopeId","data-v-dd20d5cc"]]),Map_vue_vue_type_style_index_0_lang="",Map_vue_vue_type_style_index_1_scoped_f691bb42_lang="",_sfc_main$b={emits:["city","clickMarker","close"],props:["measuretype","historyready","historyhandler"],components:{Footer},data(){return{store:useStore(),locale:localStorage.getItem("locale")||this.$i18n.locale||"en",theme:window?.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",userposition:null,geoavailable:!1}},computed:{zoom(){return this.store.mapposition.zoom},lat(){return this.store.mapposition.lat},lng(){return this.store.mapposition.lng},provider(){return getTypeProvider()}},methods:{themelistener({matches:e,media:t}){!e||(t==="(prefers-color-scheme: dark)"?this.theme="dark":t==="(prefers-color-scheme: light)"&&(this.theme="light"),setTheme(this.theme))},relocatemap(e,t,r,n){const o={name:"main",params:{provider:getTypeProvider(),type:this.$route.params.type||"pm10",zoom:r,lat:e,lng:t,sensor:this.$route.params.sensor}};this.$router.currentRoute.value.name==="main"&&(n==="reload"?(this.$router.push(o).catch(a=>{console.warn(a)}),setview([e,t],r)):this.$router.replace(o).catch(a=>{console.warn(a)}))},getlocalmappos(){if(localStorage.getItem("map-position")){const e=localStorage.getItem("map-position");this.store.setmapposition(JSON.parse(e).lat,JSON.parse(e).lng,JSON.parse(e).zoom)}},setgeo(){return new Promise(e=>{"geolocation"in navigator?navigator.geolocation.getCurrentPosition(t=>{this.userposition=[t.coords.latitude,t.coords.longitude],this.store.setmapposition(this.userposition[0],this.userposition[1],20),this.geoavailable=!0,e()},t=>{console.warn(`ERROR(${t.code}): ${t.message}`),this.getlocalmappos(),e()}):(this.getlocalmappos(),e())})},resetgeo(){this.setgeo().then(()=>{this.relocatemap(this.lat,this.lng,this.zoom,"reload")})}},unmounted(){removeMap()},async mounted(){window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",this.themelistener),window.matchMedia("(prefers-color-scheme: light)").addEventListener("change",this.themelistener)),this.setgeo().then(async()=>{const t=init$3([this.lat,this.lng],this.zoom,this.theme);this.relocatemap(this.lat,this.lng,this.zoom,"reload"),this.userposition&&drawuser(this.userposition,this.zoom),t.on("zoomend",r=>{this.relocatemap(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom()),this.store.setmapposition(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom())}),t.on("moveend",r=>{this.relocatemap(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom()),this.store.setmapposition(r.target.getCenter().lat.toFixed(4),r.target.getCenter().lng.toFixed(4),r.target.getZoom())}),init$2(t,this.measuretype,r=>{this.$emit("clickMarker",r)}),this.provider==="realtime"&&await init$1()})}},_hoisted_1$a=["area-label","title"];function _sfc_render$b(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveComponent("Footer");return openBlock(),createElementBlock(Fragment,null,[createBaseVNode("div",{class:normalizeClass([{inactive:o.store.isColored},"mapcontainer"]),id:"map"},null,2),createVNode(c,{currentProvider:a.provider,canHistory:r.historyready,onHistory:r.historyhandler,measuretype:r.measuretype},{default:withCtx(()=>[o.geoavailable?(openBlock(),createElementBlock("button",{key:0,class:"popovercontrol",onClick:t[0]||(t[0]=withModifiers((...u)=>a.resetgeo&&a.resetgeo(...u),["prevent"])),"area-label":e.$t("showlocation"),title:e.$t("showlocation")},[createVNode(l,{icon:"fa-solid fa-location-arrow"})],8,_hoisted_1$a)):createCommentVNode("",!0)]),_:1},8,["currentProvider","canHistory","onHistory","measuretype"])],64)}const Map$1=_export_sfc(_sfc_main$b,[["render",_sfc_render$b],["__scopeId","data-v-f691bb42"]]),_imports_0$1="/assets/app-icon-512.a5eb7b3f.png",Header_vue_vue_type_style_index_0_scoped_89779538_lang="",_sfc_main$a={data(){return{locale:localStorage.getItem("locale")||this.$i18n.locale||"en",store:useStore()}},watch:{locale(e){this.$i18n.locale=e,localStorage.setItem("locale",e)}},computed:{countPoints(){return this.store.sensors.length}}},_withScopeId$5=e=>(pushScopeId("data-v-89779538"),e=e(),popScopeId(),e),_hoisted_1$9={class:"flexline space-between"},_hoisted_2$7={class:"flexline align-start"},_hoisted_3$5=_withScopeId$5(()=>createBaseVNode("img",{alt:"App logo",src:_imports_0$1},null,-1)),_hoisted_4$4={key:0,class:"text-changabletheme"},_hoisted_5$4={class:"flexline"},_hoisted_6$4=_withScopeId$5(()=>createBaseVNode("option",{value:"en"},"English",-1)),_hoisted_7$4=_withScopeId$5(()=>createBaseVNode("option",{value:"ru"},"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",-1)),_hoisted_8$4=[_hoisted_6$4,_hoisted_7$4],_hoisted_9$4={id:"about",class:"popover-top-right",popover:""},_hoisted_10$3=createStaticVNode('

Web3 \u043E\u0442\u043A\u0440\u044B\u0442\u0430\u044F \u0441\u0435\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432

\u0414\u043E\u0431\u0440\u043E \u043F\u043E\u0436\u0430\u043B\u043E\u0432\u0430\u0442\u044C \u0432 \u043E\u0442\u043A\u0440\u044B\u0442\u0443\u044E \u0441\u0435\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u0430\u044F \u043F\u043E\u0441\u0442\u0440\u043E\u0435\u043D\u0430 \u043D\u0430 open-source \u043F\u0440\u0438\u043D\u0446\u0438\u043F\u0430\u0445 \u0438 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F \u044D\u043D\u0442\u0443\u0437\u0438\u0430\u0441\u0442\u0430\u043C\u0438 (\u0441\u043C. the free will of individuals). \u041A\u0430\u0440\u0442\u0430 \u043F\u0440\u0435\u0434\u043B\u0430\u0433\u0430\u0435\u0442 \u0434\u0432\u0430 \u0440\u0430\u0437\u043D\u044B\u0445 \u0443\u0440\u043E\u0432\u043D\u044F \u0434\u0435\u0446\u0435\u043D\u0442\u0440\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438: \u043F\u0440\u044F\u043C\u0430\u044F peer-to-peer \u0441\u0432\u044F\u0437\u044C \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432 \u0438 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D \u0434\u043B\u044F \u0441\u0431\u043E\u0440\u0430 \u0438 \u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u043D\u0438\u0439 \u0441 \u0434\u0430\u0442\u0447\u0438\u043A\u043E\u0432. \u0422\u0443\u0442 \u043C\u043E\u0436\u043D\u043E \u043E\u0437\u043D\u0430\u043A\u043E\u043C\u0438\u0442\u044C\u0441\u044F \u0431\u043E\u043B\u0435\u0435 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u043E \u0441 \u0442\u0435\u0445\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0441\u0442\u043E\u0440\u043E\u043D\u043E\u0439.

\u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u0441\u0432\u043E\u0439 \u0434\u0430\u0442\u0447\u0438\u043A \u043D\u0430 \u043A\u0430\u0440\u0442\u0443

\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0441\u043E\u0431\u0440\u0430\u0442\u044C \u0441\u0432\u043E\u0439 \u0434\u0430\u0442\u0447\u0438\u043A, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u043A\u043E\u043C\u043F\u043B\u0435\u043A\u0442\u0443\u044E\u0449\u0438\u0435 \u043D\u0430 \u043E\u0442\u043A\u0440\u044B\u0442\u043E\u043C \u0440\u044B\u043D\u043A\u0435 \u044D\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u0438\u043A\u0438, \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0434\u0430\u0442\u0447\u0438\u043A \u043D\u0430 \u043A\u0430\u0440\u0442\u0443. \u041C\u044B \u0441 \u0440\u0430\u0434\u043E\u0441\u0442\u044C\u044E \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u043C \u043D\u043E\u0432\u044B\u0445 \u0443\u0447\u0430\u0441\u0442\u043D\u0438\u043A\u043E\u0432 \u0441\u043E\u043E\u0431\u0449\u0435\u0441\u0442\u0432\u0430. \u041F\u0440\u0438\u0441\u043E\u0435\u0434\u0438\u043D\u044F\u0439\u0442\u0435\u0441\u044C!

\u0412\u0438\u0434\u0435\u043E-\u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u044F \u043D\u0430 YouTube

',5),_hoisted_15$2=createStaticVNode('

Web3 public sensors map

Welcome to the decentralized opensource sensors map which operates with the sole intent of serving the free will of individuals, without any beneficiaries. It offers two distinct layers of decentralization at your choise: peer-to-peer connectivity for direct access to sensor data, and the federative concept for accumulating sensor data and displaying measurement history. Click here for further technical details.

Add your sensor on this map

You can assemble your own sensor using components available on the free market. Follow the instructions provided to connect your sensor to the map. We welcome your participation and look forward to expanding our community together. Join us today!

YouTube video guide

',5),_hoisted_20$2=_withScopeId$5(()=>createBaseVNode("hr",null,null,-1)),_hoisted_21$2={class:"navlinks"},_hoisted_22$2={href:"https://github.com/airalab/sensors.robonomics.network",target:"_blank",rel:"noopener"},_hoisted_23$2={class:"popovercontrol",popovertarget:"about"};function _sfc_render$a(e,t,r,n,o,a){const l=resolveComponent("router-link"),c=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("header",_hoisted_1$9,[createBaseVNode("div",_hoisted_2$7,[createVNode(l,{to:"/",class:"appicon"},{default:withCtx(()=>[_hoisted_3$5]),_:1}),a.countPoints>0?(openBlock(),createElementBlock("b",_hoisted_4$4,toDisplayString$1(e.$t("loadedsesnsors"))+": "+toDisplayString$1(a.countPoints),1)):createCommentVNode("",!0)]),createBaseVNode("div",_hoisted_5$4,[withDirectives(createBaseVNode("select",{"onUpdate:modelValue":t[0]||(t[0]=u=>o.locale=u)},_hoisted_8$4,512),[[vModelSelect,o.locale]]),createBaseVNode("div",_hoisted_9$4,[o.locale==="ru"?(openBlock(),createElementBlock(Fragment,{key:0},[_hoisted_10$3],64)):(openBlock(),createElementBlock(Fragment,{key:1},[_hoisted_15$2],64)),_hoisted_20$2,createBaseVNode("section",_hoisted_21$2,[createBaseVNode("a",_hoisted_22$2,toDisplayString$1(e.$t("links.github")),1),createVNode(l,{to:"/air-measurements"},{default:withCtx(()=>[createTextVNode(toDisplayString$1(e.$t("links.measurement")),1)]),_:1}),createVNode(l,{to:"/privacy-policy"},{default:withCtx(()=>[createTextVNode(toDisplayString$1(e.$t("links.privacy")),1)]),_:1})])]),createBaseVNode("button",_hoisted_23$2,[createVNode(c,{icon:"fa-solid fa-bars"})])])])}const Header=_export_sfc(_sfc_main$a,[["render",_sfc_render$a],["__scopeId","data-v-89779538"]]),_imports_0="/assets/sensors-world-app.8a0828bb.png",InstallPWA_vue_vue_type_style_index_0_scoped_b59a209f_lang="",_sfc_main$9={data(){return{deferredPrompt:null,isSupported:!1,db:null,isInstalled:"loading",isBrowserSupport:!0,browsers:{chrome:!1,safari:!1,firefox:!1,edge:!1,opera:!1}}},methods:{async getDb(){return new Promise((e,t)=>{let r=window.indexedDB.open("SensorsDB",1);r.onerror=n=>{console.log("Error opening db",n),t("Error")},r.onsuccess=n=>{e(n.target.result)},r.onupgradeneeded=n=>{n.target.result.createObjectStore("install",{autoIncrement:!0,keyPath:"id"})}})},async getData(){return new Promise(e=>{let t=this.db.transaction(["install"],"readonly");t.oncomplete=()=>{e(n)};let r=t.objectStore("install"),n=null;r.openCursor().onsuccess=o=>{let a=o.target.result;a&&(n=a.value,a.continue())}})},async addDataToDb(e=!1,t=!1){return new Promise(r=>{let n=this.db.transaction(["install"],"readwrite");n.oncomplete=()=>{r()};let o=n.objectStore("install");o.delete(1),o.add({id:1,removed:e,installed:t})})},async installApp(){if(this.addDataToDb(!1,!0),this.deferredPrompt!==null){this.deferredPrompt.prompt();const{outcome:e}=await this.deferredPrompt.userChoice;e==="accepted"&&(this.deferredPrompt=null,this.isSupported=!1,this.isInstalled="installed")}},removeInstall(){this.addDataToDb(!0,!1),this.isInstalled="removed"},checkBrowser(){let e=navigator.userAgent;this.browsers.chrome=e.indexOf("Chrome")>-1,this.browsers.firefox=e.indexOf("Firefox")>-1,this.browsers.safari=e.indexOf("Safari")>-1,this.browsers.chrome&&this.browsers.safari&&(this.browsers.safari=!1),this.browsers.opera=e.indexOf("OP")>-1,this.browsers.chrome&&this.browsers.opera&&(this.browsers.chrome=!1)}},async created(){this.db=await this.getDb(),this.isInstalled=await this.getData()?await this.getData():null},mounted(){window.addEventListener("beforeinstallprompt",e=>{this.isSupported=!0,this.deferredPrompt=e}),window.matchMedia("(display-mode: standalone)").matches?this.isSupported=!0:this.isSupported=!1,this.checkBrowser(),(this.browsers.safari||this.browsers.firefox||this.browsers.opera)&&(this.isBrowserSupport=!1)}},_withScopeId$4=e=>(pushScopeId("data-v-b59a209f"),e=e(),popScopeId(),e),_hoisted_1$8={key:0,class:"container install-pwa__container"},_hoisted_2$6={class:"install-pwa__content"},_hoisted_3$4=_withScopeId$4(()=>createBaseVNode("img",{src:_imports_0,alt:"sensors-cy-app"},null,-1)),_hoisted_4$3={class:"install-pwa__text"},_hoisted_5$3=_withScopeId$4(()=>createBaseVNode("h3",null,"Available as web application (PWA)",-1));function _sfc_render$9(e,t,r,n,o,a){return!o.isInstalled&&o.isBrowserSupport?(openBlock(),createElementBlock("div",_hoisted_1$8,[createBaseVNode("div",_hoisted_2$6,[_hoisted_3$4,createBaseVNode("div",_hoisted_4$3,[_hoisted_5$3,createBaseVNode("button",{onClick:t[0]||(t[0]=(...l)=>a.installApp&&a.installApp(...l)),class:"install-pwa__btn"},"Install")])]),createBaseVNode("button",{onClick:t[1]||(t[1]=(...l)=>a.removeInstall&&a.removeInstall(...l)),class:"install-pwa__remove"})])):createCommentVNode("",!0)}const InstallPWA=_export_sfc(_sfc_main$9,[["render",_sfc_render$9],["__scopeId","data-v-b59a209f"]]),MessagePopup_vue_vue_type_style_index_0_scoped_c5bfb7c2_lang="";function preloadImages(e,t){let r=0;const n={};function o(){if(r++,r==e.length){const a=[],l=[];for(const c of e)n[c]&&n[c]>0?(console.log(`Bad image ${c}`),l.push(c)):a.push(c);t(a,l)}}for(let a of e){let l=document.createElement("img");l.onload=()=>{n[a]=0,o()},l.onerror=()=>{n[a]||(n[a]=0),n[a]++,n[a]<3?l.src=a:o()},l.src=a}}const _sfc_main$8={props:["data"],data(){return{isImages:!1,images:[],badImages:[],imagesLoaded:!1,state:"neutral"}},computed:{dateMsg:function(){return hooks(this.data.timestamp,"X").format("DD.MM.YYYY HH:mm:ss")},classList(){return{["sensor-popup__header"]:!0,[`sensor-popup__header--${this.state}`]:this.state}}},watch:{data(){this.imagesLoad()}},created(){this.imagesLoad()},methods:{replaceWithBr(e){return e.replace(/\n/g,"
")},imagesLoad(){if(this.data.images&&this.data.images.length>0){this.images=[],this.badImages=[],this.imagesLoaded=!1,this.isImages=!0;const e=this.data.images.map(t=>`https://aira.mypinata.cloud/ipfs/${this.data.ipfs}/${t}`);preloadImages(e,(t,r)=>{t.length>0&&(this.images=t),r.length>0&&(this.badImages=r),this.imagesLoaded=!0})}else this.isImages=!1,this.images=[],this.badImages=[],this.imagesLoaded=!1}}},_hoisted_1$7={class:"container sensor-popup sensors-panel sensors-panel--center-right active popup-js"},_hoisted_2$5={class:"sensor-popup__header-icon"},_hoisted_3$3={class:"sensor-popup__header-wrapper"},_hoisted_4$2={class:"sensor-popup--subtitle"},_hoisted_5$2={ref:"content",class:"sensor-popup--content"},_hoisted_6$3=["innerHTML"],_hoisted_7$3={key:0},_hoisted_8$3=["href"],_hoisted_9$3=["src"],_hoisted_10$2=["href"];function _sfc_render$8(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("div",_hoisted_1$7,[createBaseVNode("div",{class:normalizeClass(a.classList)},[createBaseVNode("div",_hoisted_2$5,[createVNode(l,{icon:"fa-solid fa-face-meh"})]),createBaseVNode("div",_hoisted_3$3,[createBaseVNode("h2",null,toDisplayString$1(e.$t("details.user"))+" "+toDisplayString$1(r.data.username),1),createBaseVNode("div",_hoisted_4$2,[createBaseVNode("span",null,[createVNode(l,{icon:"fa-solid fa-stopwatch"}),createTextVNode(" "+toDisplayString$1(a.dateMsg),1)])])])],2),createBaseVNode("div",_hoisted_5$2,[createBaseVNode("div",{innerHTML:a.replaceWithBr(r.data.message)},null,8,_hoisted_6$3),o.isImages?(openBlock(),createElementBlock(Fragment,{key:0},[createBaseVNode("h2",null,toDisplayString$1(e.$t("details.photos")),1),o.imagesLoaded?(openBlock(),createElementBlock(Fragment,{key:1},[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.images,(c,u)=>(openBlock(),createElementBlock("div",{key:u},[createBaseVNode("a",{href:c,target:"_blank"},[createBaseVNode("img",{style:{"max-width":"400px"},src:c},null,8,_hoisted_9$3)],8,_hoisted_8$3)]))),128)),createBaseVNode("template",null,[(openBlock(!0),createElementBlock(Fragment,null,renderList(o.badImages,(c,u)=>(openBlock(),createElementBlock("a",{key:u,href:c,target:"_blank"},toDisplayString$1(c),9,_hoisted_10$2))),128))])],64)):(openBlock(),createElementBlock("div",_hoisted_7$3,"..."))],64)):createCommentVNode("",!0)],512),createBaseVNode("a",{class:"popup__close",href:"javascript:;",onClick:t[0]||(t[0]=withModifiers(c=>e.$emit("close"),["stop","prevent"]))},[createVNode(l,{icon:"fa-solid fa-xmark"})])])}const MessagePopup=_export_sfc(_sfc_main$8,[["render",_sfc_render$8],["__scopeId","data-v-c5bfb7c2"]]),Bookmark_vue_vue_type_style_index_0_scoped_8cca7f79_lang="",_sfc_main$7={props:["address","link"],data(){return{IsBookmarked:!1,db:null,bookmarks:[],bookmarkid:null,bookmarkname:"",store:useStore()}},computed:{buttonclasses(){return{button:!0,["button-green"]:this.IsBookmarked}}},methods:{async findbookmark(){return(await IDBgettable(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable)).find(t=>t.address===this.$props.address)},async addbookmark(){await this.findbookmark()?this.bookmarkid&&IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",r=>{const n=r.get(this.bookmarkid);n.addEventListener("error",o=>{console.log(o)}),n.addEventListener("success",o=>{const a=o.target.result;a.customName=this.bookmarkname;const l=r.put(a);l.addEventListener("error",c=>{console.log(c)}),l.addEventListener("success",c=>{this.IsBookmarked=!0})})}):IDBworkflow(this.store.idbBookmarkDbname,this.store.idbBookmarkVDbver,this.store.idbBookmarkVDbtable,"readwrite",r=>{r.add({customName:this.bookmarkname,address:this.$props.address,link:this.$props.link}),this.IsBookmarked=!0});const t=new BroadcastChannel(this.store.idbWatcherBroadcast);t.postMessage(!0),t.close()}},async mounted(){const e=await this.findbookmark();e&&(this.IsBookmarked=!0,this.bookmarkid=e.id,this.bookmarkname=e.customName)}},_hoisted_1$6=["placeholder"],_hoisted_2$4=["disabled","area-label"];function _sfc_render$7(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon");return openBlock(),createElementBlock("form",{class:"flexline",onSubmit:t[2]||(t[2]=withModifiers((...c)=>a.addbookmark&&a.addbookmark(...c),["prevent"]))},[withDirectives(createBaseVNode("input",{type:"text","onUpdate:modelValue":t[0]||(t[0]=c=>o.bookmarkname=c),placeholder:e.$t("sensorpopup.bookmarkplaceholder"),onInput:t[1]||(t[1]=c=>o.IsBookmarked=!1)},null,40,_hoisted_1$6),[[vModelText,o.bookmarkname]]),createBaseVNode("button",{class:normalizeClass(a.buttonclasses),disabled:o.IsBookmarked,"area-label":e.$t("sensorpopup.bookmarkbutton")},[o.IsBookmarked?(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-check"})):(openBlock(),createBlock(l,{key:0,icon:"fa-solid fa-bookmark"}))],10,_hoisted_2$4)],32)}const Bookmark=_export_sfc(_sfc_main$7,[["render",_sfc_render$7],["__scopeId","data-v-8cca7f79"]]),Chart_vue_vue_type_style_index_0_lang="",_sfc_main$6={props:["log","measurement","sensor_id","model","type","units"],data(){const e=this;return{datacollection:null,options:{title:!1,chart:{type:"spline",height:400},xAxis:{type:"datetime",labels:{formatter:function(){return hooks(this.value,"X").format("HH:mm")}},title:!1},yAxis:{title:!1},tooltip:{shared:!0,crosshairs:!0,formatter:function(){if(e.model===3){const r=e.log.find(n=>n.timestamp===this.x);moveMarkerTime(e.sensor_id,r)}let t="";return this.points.forEach(r=>{t+=""+r.series.name+" = "+r.y+"
"}),""+hooks(this.x,"X").format("DD.MM.YYYY HH:mm:ss")+"
"+t}},plotOptions:{series:{events:{mouseOut:function(){if(e.model===3){const t=e.log[e.log.length-1];moveMarkerTime(e.sensor_id,t,!0)}},legendItemClick:function(t){let r=t;if(t||(r=e.store.currentActiveMeasure),t.target){r=t.target.name;let n=t.target.name;r==="temperature"?n="tmp":r==="humidity"&&(n="hm"),e.store.selectCurrentActiveMeasure(n.toUpperCase(),!0)}if(r){r==="TMP"?r="temperature":r==="HM"&&(r="humidity");const n=e.series.filter(o=>o.name===r.replace(".","").toLowerCase());e.toggleTabState(n[0])}}}}},series:[]},store:useStore()}},computed:{series:function(){if(this.log.length>0&&this.units&&this.units.length>0){const e=this.units.map(n=>n.toLowerCase()),t=[];for(let n of e)t.push({visible:n===this.measurement,name:n,zones:measurements[n.toLowerCase()]?.zones,lineWidth:1,data:[],options:{name:n}});return!t.find(n=>n.visible===!0)&&t.length>0&&(t[0].visible=!0),t}return[{name:this.measurement,color:"#e8b738",lineWidth:1,data:[],options:{name:this.measurement}}]},storeMeasures(){return this.store.currentActiveMeasure}},watch:{sensor_id:function(){this.fillData()},measurement:function(){this.fillData()},log:{immediate:!1,handler:function(e){this.fillData(),this.$nextTick(()=>{const t=this.$refs.chart.chart.series[0].points.length-e.length;if(t<0){let r=[this.measurement];(this.measurement==="pm10"||this.measurement==="pm25")&&(r=["pm10","pm25"]);const n=e.slice(t);for(const o in r)for(let a of n)this.addPoint(o,[Number(a.timestamp),Number(a.data[r[o]])])}})}},storeMeasures:{handler:function(){this.options.plotOptions.series.events.legendItemClick(this.store.currentActiveMeasure)},deep:!0}},methods:{fillData(){const e=this.series;for(const t in e)e[t].data=this.log.map(r=>(r.data=Object.fromEntries(Object.entries(r.data).map(([n,o])=>[n.toLowerCase(),o])),[Number(r.timestamp),Number(r.data[e[t].options.name])]));if(this.options.series=e,!this.store.currentActiveMeasure&&!this.$props.type&&this.store.selectCurrentActiveMeasure(this.options.series[0].name.toUpperCase(),!0),!this.store.currentActiveMeasure&&this.$props.type){let t=this.$props.type;this.$props.type==="temperature"?t="tmp":this.$props.type==="humidity"&&(t="hm"),this.store.selectCurrentActiveMeasure(t.toUpperCase(),!0)}},addPoint(e,t){this.$refs.chart.chart.series[e].addPoint(t,!0,!1)},toggleTabState(e){const t=this.$refs.chart.chart.series.filter(r=>r.name===e.name);this.$refs.chart.chart.series.length&&(this.$refs.chart.chart.series[t[0].index].name==="temperature"?this.store.addToggleState("TMP"):this.$refs.chart.chart.series[t[0].index].name==="humidity"?this.store.addToggleState("HM"):this.store.addToggleState(this.$refs.chart.chart.series[t[0].index].name.toUpperCase().replace(".","")),this.$refs.chart.chart.series[t[0].index].visible?this.$refs.chart.chart.series[t[0].index].hide():this.$refs.chart.chart.series[t[0].index].show())}},mounted(){this.fillData()}},_hoisted_1$5={style:{margin:"20px 0"}};function _sfc_render$6(e,t,r,n,o,a){const l=resolveComponent("highcharts");return openBlock(),createElementBlock("div",_hoisted_1$5,[createVNode(l,{options:o.options,ref:"chart"},null,8,["options"])])}const Chart=_export_sfc(_sfc_main$6,[["render",_sfc_render$6]]),Copy_vue_vue_type_style_index_0_scoped_951f909f_lang="",_sfc_main$5={props:["msg","title","notify"],data(){return{successCopy:!1}},methods:{success(){this.$notify({position:"top right",text:this.notify})},showSuccessesCopy(){this.successCopy=!0,setTimeout(()=>{this.successCopy=!1},2e3)}}},_hoisted_1$4=["title"];function _sfc_render$5(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveDirective("clipboard");return withDirectives((openBlock(),createElementBlock("a",{class:"nowrap copy",title:r.title},[renderSlot(e.$slots,"default",{},void 0,!0),o.successCopy?createCommentVNode("",!0):(openBlock(),createElementBlock("button",{key:0,class:"copy-btn",onClick:t[0]||(t[0]=(...u)=>a.showSuccessesCopy&&a.showSuccessesCopy(...u))})),o.successCopy?(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-check"})):createCommentVNode("",!0)],8,_hoisted_1$4)),[[c,r.msg,"copy"],[c,a.success,"success"]])}const Copy=_export_sfc(_sfc_main$5,[["render",_sfc_render$5],["__scopeId","data-v-951f909f"]]),SensorPopup_vue_vue_type_style_index_0_scoped_7f5b2702_lang="",_sfc_main$4={emits:["close"],props:["type","point"],components:{Chart,Copy,Bookmark},data(){return{select:"",measurement:this.type,isShowPath:!1,store:useStore(),start:hooks().format("YYYY-MM-DD"),maxDate:hooks().format("YYYY-MM-DD"),provider:this.$route.params.provider,rttime:null,rtdata:[]}},computed:{locale(){return localStorage.getItem("locale")||this.$i18n.locale||"en"},address(){return this.point.address},donated_by(){return this.point.donated_by},geo(){return this.point.geo},log(){return this.point?.log},model(){return this.point.model},sender(){return this.point.sender},sensor_id(){return this.point.sensor_id},realtime(){return this.provider==="realtime"},addressformatted(){let e="";return this.address.country&&(e+=this.address.country),this.address.address.length>0&&(e+=", "+this.address.address.join(", ")),e},isLocationRussion(){return this.address.country==="\u0420\u043E\u0441\u0441\u0438\u044F"||this.address.country==="Russia"},measure(){return this.items.find(e=>this.select===e.text)},scale(){return generate$1(measurements[this.type.toLowerCase()].colors,measurements[this.type.toLowerCase()].range)},hasIcon(){return e=>measurements[e.toLowerCase()]&&measurements[e.toLowerCase()].icon},icon:function(){return e=>this.hasIcon(e)?measurements[e.toLowerCase()].icon:"vial"},items(){const e=[];for(const t of Object.keys(this.last.data)){let r=null;measurements[t.toLowerCase()]&&measurements[t.toLowerCase()].colors&&(r=generate$1(measurements[t.toLowerCase()].colors,measurements[t.toLowerCase()].range)),e.push({id:t,title:this.$filters.measurementFormat(this.last.data[t],t),text:this.$filters.measurement(t),state:getState(r,this.last.data[t],measurements[t.toLowerCase()]?measurements[t.toLowerCase()].states:void 0)})}return e},measurementFilter(e){return measurements[e.toLowerCase()]?.label||e},measurementFormat(e,t){return measurements[t.toLowerCase()]?`${toFixed(e)} ${measurements[t.toLowerCase()].unit}`:toFixed(e)},collapse(e){return e?e.slice(0,6)+"..."+e.slice(-4):""},linkSensor:function(){const e=this.$router.resolve({name:"main",params:{provider:getTypeProvider(),type:this.$route.params.type||"pm10",zoom:this.$route.params.zoom||config$2.MAP.zoom,lat:this.geo.lat,lng:this.geo.lng,sensor:this.sensor_id}});return new URL(e.href,window.location.origin).href},link:function(){return sensors[this.sensor_id]?sensors[this.sensor_id].link:""},icon:function(){return sensors[this.sensor_id]?sensors[this.sensor_id].icon:""},last:function(){return this.log[this.log.length-1]},date:function(){return hooks(this.last.timestamp,"X").format("DD.MM.YYYY HH:mm:ss")},startTimestamp:function(){return Number(hooks(this.start+" 00:00:00","YYYY-MM-DD HH:mm:ss").format("X"))},endTimestamp:function(){return Number(hooks(this.start+" 23:59:59","YYYY-MM-DD HH:mm:ss").format("X"))},sharable:function(){return navigator.share&&navigator.canShare},units(){let e=[];return Object.values(this.log).forEach(t=>{Object.keys(t.data).forEach(r=>{e.push(r)})}),[...new Set(e.flat())]},scales:function(){let e=[];return Object.keys(measurements).forEach(t=>{this.units.some(r=>r===t)&&e.push(measurements[t])}),e}},methods:{shareData(){navigator.share({title:"Public Sensor Map",url:this.linkSensor?this.linkSensor:this.link}).then(()=>{console.log("Shared")}).catch(console.error)},getHistory(){this.realtime||this.$emit("history",{sensor_id:this.sensor_id,start:this.startTimestamp,end:this.endTimestamp})},updatert(){if(this.realtime){const e=this.log[this.log.length-1].timestamp*1e3;e&&(this.rttime=new Date(e).toLocaleString());const t=this.log[this.log.length-1].data;let r={};t&&(this.rtdata=[],Object.keys(measurements).forEach(n=>{Object.keys(t).forEach(o=>{n===o&&(r={},r.key=o,r.measure=t[o],r.label=measurements[n].label,r.unit=measurements[n].unit,measurements[n].zones.find(a=>r.measurer.measuremeasurements[n].zones[measurements[n].zones.length-2].value&&(r.color=measurements[n].zones[measurements[n].zones.length-1].color),this.rtdata.push(r))})}))}}},watch:{sensor_id(){this.isShowPath=!1},isShowPath(){this.isShowPath?showPath(this.sensor_id):hidePath(this.sensor_id)},start(){this.getHistory()},log(){this.updatert()}},mounted(){this.updatert()}},_withScopeId$3=e=>(pushScopeId("data-v-7f5b2702"),e=e(),popScopeId(),e),_hoisted_1$3={class:"popup-js active"},_hoisted_2$3={class:"flexline clipoverflow"},_hoisted_3$2=["src"],_hoisted_4$1={class:"scrollable-y"},_hoisted_5$1={class:"flexline space-between"},_hoisted_6$2={class:"flexline"},_hoisted_7$2=["max"],_hoisted_8$2={key:0,class:"flexline"},_hoisted_9$2=_withScopeId$3(()=>createBaseVNode("div",{class:"rt-title"},"Realtime view mode",-1)),_hoisted_10$1={key:0,class:"rt-time"},_hoisted_11$1={class:"rt-unit"},_hoisted_12$1={key:0,class:"infoline flexline"},_hoisted_13$1={class:"infoline-title"},_hoisted_14$1={class:"infoline-info"},_hoisted_15$1={key:1,class:"infoline flexline"},_hoisted_16$1={class:"infoline-title"},_hoisted_17$1={class:"infoline-info"},_hoisted_18$1={key:2,class:"infoline flexline"},_hoisted_19$1={class:"infoline-title"},_hoisted_20$1={class:"infoline-info"},_hoisted_21$1=["href"],_hoisted_22$1={key:3,class:"infoline flexline"},_hoisted_23$1={class:"infoline-title"},_hoisted_24$1={class:"infoline-info"},_hoisted_25$1={key:4,class:"infoline flexline"},_hoisted_26$1={class:"infoline-title"},_hoisted_27$1=_withScopeId$3(()=>createBaseVNode("label",{for:"realtime"},null,-1)),_hoisted_28$1={class:"sensors-switcher-text"},_hoisted_29$1={class:"infoline-info"},_hoisted_30$1={key:1},_hoisted_31$1={class:"scalegrid"},_hoisted_32$1={key:0},_hoisted_33$1={key:1},_hoisted_34$1={class:"textsmall"};function _sfc_render$4(e,t,r,n,o,a){const l=resolveComponent("font-awesome-icon"),c=resolveComponent("Bookmark"),u=resolveComponent("Chart"),_=resolveComponent("Copy");return openBlock(),createElementBlock("div",_hoisted_1$3,[createBaseVNode("section",null,[createBaseVNode("h3",_hoisted_2$3,[a.icon?(openBlock(),createElementBlock("img",{key:0,src:a.icon,class:"icontitle"},null,8,_hoisted_3$2)):(openBlock(),createBlock(l,{key:1,icon:"fa-solid fa-location-dot"})),createTextVNode(" "+toDisplayString$1(a.addressformatted),1)])]),createBaseVNode("div",_hoisted_4$1,[createBaseVNode("section",_hoisted_5$1,[createBaseVNode("div",_hoisted_6$2,[a.realtime?createCommentVNode("",!0):withDirectives((openBlock(),createElementBlock("input",{key:0,type:"date","onUpdate:modelValue":t[0]||(t[0]=b=>o.start=b),max:o.maxDate},null,8,_hoisted_7$2)),[[vModelText,o.start]]),createVNode(c,{address:a.address.address&&a.address.address.join(", "),link:a.linkSensor},null,8,["address","link"])]),a.sharable?(openBlock(),createElementBlock("button",{key:0,onClick:t[1]||(t[1]=(...b)=>a.shareData&&a.shareData(...b)),class:"button"},[createVNode(l,{icon:"fa-solid fa-share-from-square"})])):createCommentVNode("",!0)]),a.realtime?(openBlock(),createElementBlock("section",_hoisted_8$2,[createBaseVNode("div",null,[_hoisted_9$2,o.rttime?(openBlock(),createElementBlock("div",_hoisted_10$1,toDisplayString$1(o.rttime),1)):createCommentVNode("",!0)]),o.rtdata?(openBlock(!0),createElementBlock(Fragment,{key:0},renderList(o.rtdata,b=>(openBlock(),createElementBlock("div",{key:b},[createBaseVNode("div",_hoisted_11$1,toDisplayString$1(b.label),1),createBaseVNode("div",{class:"rt-number",style:normalizeStyle(b.color?"color:"+b.color:"")},toDisplayString$1(b.measure)+" "+toDisplayString$1(b.unit),5)]))),128)):createCommentVNode("",!0)])):createCommentVNode("",!0),createBaseVNode("section",null,[a.log.length>0?(openBlock(),createBlock(u,{key:0,model:a.model,log:a.log,measurement:o.measurement,sensor_id:a.sensor_id,type:r.type,units:a.units},null,8,["model","log","measurement","sensor_id","type","units"])):createCommentVNode("",!0)]),createBaseVNode("section",null,[createBaseVNode("h3",null,toDisplayString$1(e.$t("sensorpopup.infotitle")),1),a.sensor_id?(openBlock(),createElementBlock("div",_hoisted_12$1,[createBaseVNode("div",_hoisted_13$1,toDisplayString$1(e.$t("sensorpopup.infosensorid"))+":",1),createBaseVNode("div",_hoisted_14$1,[createTextVNode(toDisplayString$1(e.$filters.collapse(a.sensor_id))+" ",1),createVNode(_,{msg:a.sensor_id,title:`Sensor id: ${a.sensor_id}`,notify:e.$t("details.copied")},null,8,["msg","title","notify"])])])):createCommentVNode("",!0),a.geo?(openBlock(),createElementBlock("div",_hoisted_15$1,[createBaseVNode("div",_hoisted_16$1,toDisplayString$1(e.$t("sensorpopup.infosensorgeo"))+":",1),createBaseVNode("div",_hoisted_17$1,toDisplayString$1(a.geo.lat)+", "+toDisplayString$1(a.geo.lng),1)])):createCommentVNode("",!0),a.link?(openBlock(),createElementBlock("div",_hoisted_18$1,[createBaseVNode("div",_hoisted_19$1,toDisplayString$1(e.$t("sensorpopup.infosensorowner"))+":",1),createBaseVNode("div",_hoisted_20$1,[createBaseVNode("a",{href:a.link,rel:"noopener",target:"_blank"},toDisplayString$1(a.link),9,_hoisted_21$1)])])):createCommentVNode("",!0),a.donated_by?(openBlock(),createElementBlock("div",_hoisted_22$1,[createBaseVNode("div",_hoisted_23$1,toDisplayString$1(e.$t("sensorpopup.infosensordonated"))+":",1),createBaseVNode("div",_hoisted_24$1,toDisplayString$1(a.donated_by),1)])):createCommentVNode("",!0),a.model===3?(openBlock(),createElementBlock("div",_hoisted_25$1,[createBaseVNode("div",_hoisted_26$1,[_hoisted_27$1,createBaseVNode("span",_hoisted_28$1,toDisplayString$1(e.$t("details.showpath")),1),createTextVNode(": ")]),createBaseVNode("div",_hoisted_29$1,[withDirectives(createBaseVNode("input",{type:"checkbox",id:"realtime","onUpdate:modelValue":t[2]||(t[2]=b=>o.isShowPath=b)},null,512),[[vModelCheckbox,o.isShowPath]])])])):createCommentVNode("",!0)]),a.units&&a.scales&&a.scales.length>0?(openBlock(),createElementBlock("section",_hoisted_30$1,[createBaseVNode("h3",null,toDisplayString$1(e.$t("scales.title")),1),createBaseVNode("div",_hoisted_31$1,[(openBlock(!0),createElementBlock(Fragment,null,renderList(a.scales,b=>(openBlock(),createElementBlock("div",{key:b.label},[b?.zones&&(b.name||b.label)?(openBlock(),createElementBlock(Fragment,{key:0},[createBaseVNode("p",null,[b.name?(openBlock(),createElementBlock("b",_hoisted_32$1,toDisplayString$1(a.locale==="en"?b.name.en:b.name.ru),1)):(openBlock(),createElementBlock("b",_hoisted_33$1,toDisplayString$1(b.label),1)),createTextVNode(" ("+toDisplayString$1(b.unit)+") ",1)]),(openBlock(!0),createElementBlock(Fragment,null,renderList(b.zones,x=>(openBlock(),createElementBlock(Fragment,{key:x.color},[x.color&&x.label?(openBlock(),createElementBlock("div",{key:0,class:"scales-color",style:normalizeStyle(`--color: ${x.color}`)},[createBaseVNode("b",null,toDisplayString$1(a.locale==="en"?x.label.en:x.label.ru),1),createTextVNode(" ("),x.value?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("scales.upto"))+" "+toDisplayString$1(x.value),1)],64)):(openBlock(),createElementBlock(Fragment,{key:1},[createTextVNode(toDisplayString$1(e.$t("scales.above")),1)],64)),createTextVNode(") ")],4)):createCommentVNode("",!0)],64))),128))],64)):createCommentVNode("",!0)]))),128))])])):createCommentVNode("",!0),createBaseVNode("div",_hoisted_34$1,[a.isLocationRussion?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString$1(e.$t("notice_with_fz")),1)],64)):(openBlock(),createElementBlock(Fragment,{key:1},[createTextVNode(toDisplayString$1(e.$t("notice_without_fz")),1)],64))])]),createBaseVNode("button",{onClick:t[3]||(t[3]=withModifiers(b=>e.$emit("close"),["prevent"])),"aria-label":"Close sensor",class:"close"},[createVNode(l,{icon:"fa-solid fa-xmark"})])])}const SensorPopup=_export_sfc(_sfc_main$4,[["render",_sfc_render$4],["__scopeId","data-v-7f5b2702"]]);function asUint8Array(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function alloc(e=0){return globalThis.Buffer?.alloc!=null?asUint8Array(globalThis.Buffer.alloc(e)):new Uint8Array(e)}function allocUnsafe$2(e=0){return globalThis.Buffer?.allocUnsafe!=null?asUint8Array(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}const N1$2=Math.pow(2,7),N2$2=Math.pow(2,14),N3$2=Math.pow(2,21),N4$2=Math.pow(2,28),N5$2=Math.pow(2,35),N6$2=Math.pow(2,42),N7$2=Math.pow(2,49),MSB$4=128,REST$4=127;function encodingLength$2(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function encodeUint8Array(e,t,r=0){switch(encodingLength$2(e)){case 8:t[r++]=e&255|MSB$4,e/=128;case 7:t[r++]=e&255|MSB$4,e/=128;case 6:t[r++]=e&255|MSB$4,e/=128;case 5:t[r++]=e&255|MSB$4,e/=128;case 4:t[r++]=e&255|MSB$4,e>>>=7;case 3:t[r++]=e&255|MSB$4,e>>>=7;case 2:t[r++]=e&255|MSB$4,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function encodeUint8ArrayList(e,t,r=0){switch(encodingLength$2(e)){case 8:t.set(r++,e&255|MSB$4),e/=128;case 7:t.set(r++,e&255|MSB$4),e/=128;case 6:t.set(r++,e&255|MSB$4),e/=128;case 5:t.set(r++,e&255|MSB$4),e/=128;case 4:t.set(r++,e&255|MSB$4),e>>>=7;case 3:t.set(r++,e&255|MSB$4),e>>>=7;case 2:t.set(r++,e&255|MSB$4),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function decodeUint8Array(e,t){let r=e[t],n=0;if(n+=r&REST$4,ro+a.length,0));const r=allocUnsafe$2(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return asUint8Array(r)}function equals$2(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(const n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(isUint8ArrayList(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(const n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(isUint8ArrayList(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){const r=findBufAndOffset(this.bufs,t);return r.buf[r.index]}set(t,r){const n=findBufAndOffset(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){const{bufs:n,length:o}=this._subList(t,r);return concat$1(n,o)}subarray(t,r){const{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:concat$1(n,o)}sublist(t,r){const{bufs:n,length:o}=this._subList(t,r),a=new Uint8ArrayList;return a.length=o,a.bufs=n,a}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];let o=0;for(let a=0;a=u)continue;const _=t>=c&&tc&&r<=u;if(_&&b){if(t===c&&r===u){n.push(l);break}const x=t-c;n.push(l.subarray(x,x+(r-t)));break}if(_){if(t===0){n.push(l);continue}n.push(l.subarray(t-c));continue}if(b){if(r===u){n.push(l);break}n.push(l.subarray(0,r-c));break}n.push(l)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!isUint8ArrayList(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;const o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const a=256,l=new Int32Array(a);for(let x=0;x=0;E--){const I=this.get(x+E);if(n[E]!==I){b=Math.max(1,E-c[I]);break}}if(b===0)return x}return-1}getInt8(t){const r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){const n=allocUnsafe$2(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){const o=alloc(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){const r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){const n=allocUnsafe$2(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){const o=alloc(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){const o=alloc(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){const o=alloc(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof Uint8ArrayList)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;ro+a.byteLength,0)),n.length=r,n}}function isAsyncIterable$a(e){return e[Symbol.asyncIterator]!=null}const defaultEncoder=e=>{const t=encodingLength$2(e),r=allocUnsafe$2(t);return encode$d(e,r),defaultEncoder.bytes=t,r};defaultEncoder.bytes=0;function encode$c(e,t){t=t??{};const r=t.lengthEncoder??defaultEncoder;function*n(o){const a=r(o.byteLength);a instanceof Uint8Array?yield a:yield*a,o instanceof Uint8Array?yield o:yield*o}return isAsyncIterable$a(e)?async function*(){for await(const o of e)yield*n(o)}():function*(){for(const o of e)yield*n(o)}()}encode$c.single=(e,t)=>{t=t??{};const r=t.lengthEncoder??defaultEncoder;return new Uint8ArrayList(r(e.byteLength),e)};function assign$1(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}function createError(e,t,r){if(!e||typeof e=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof t=="object"&&(r=t,t=""),t&&(r.code=t);try{return assign$1(e,r)}catch{r.message=e.message,r.stack=e.stack;const o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(e)),assign$1(new o,r)}}var errCode=createError;const MAX_LENGTH_LENGTH=8,MAX_DATA_LENGTH=1024*1024*4;var ReadMode;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(ReadMode||(ReadMode={}));const defaultDecoder=e=>{const t=decode$b(e);return defaultDecoder.bytes=encodingLength$2(t),t};defaultDecoder.bytes=0;function decode$a(e,t){const r=new Uint8ArrayList;let n=ReadMode.LENGTH,o=-1;const a=t?.lengthDecoder??defaultDecoder,l=t?.maxLengthLength??MAX_LENGTH_LENGTH,c=t?.maxDataLength??MAX_DATA_LENGTH;function*u(){for(;r.byteLength>0;){if(n===ReadMode.LENGTH)try{if(o=a(r),o<0)throw errCode(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>c)throw errCode(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");const _=a.bytes;r.consume(_),t?.onLength!=null&&t.onLength(o),n=ReadMode.DATA}catch(_){if(_ instanceof RangeError){if(r.byteLength>l)throw errCode(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw _}if(n===ReadMode.DATA){if(r.byteLength0)throw errCode(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(const _ of e)r.append(_),yield*u();if(r.byteLength>0)throw errCode(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}decode$a.fromReader=(e,t)=>{let r=1;const n=async function*(){for(;;)try{const{done:a,value:l}=await e.next(r);if(a===!0)return;l!=null&&(yield l)}catch(a){if(a.code==="ERR_UNDER_READ")return{done:!0,value:null};throw a}finally{r=1}}();return decode$a(n,{...t??{},onLength:a=>{r=a}})};function pDefer(){const e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}class FixedFIFO{constructor(t){Ke(this,"buffer");Ke(this,"mask");Ke(this,"top");Ke(this,"btm");Ke(this,"next");if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}}class FIFO{constructor(t={}){Ke(this,"size");Ke(this,"hwm");Ke(this,"head");Ke(this,"tail");this.hwm=t.splitLimit??16,this.head=new FixedFIFO(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const r=this.head;this.head=r.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class AbortError$6 extends Error{constructor(r,n){super(r??"The operation was aborted");Ke(this,"type");Ke(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}}function pushable(e={}){return _pushable(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function pushableV(e={}){return _pushable(r=>{let n;const o=[];for(;!r.isEmpty()&&(n=r.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&o.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:o}},e)}function _pushable(e,t){t=t??{};let r=t.onEnd,n=new FIFO,o,a,l,c=pDefer();const u=async()=>{try{return n.isEmpty()?l?{done:!0}:await new Promise((O,$)=>{a=D=>{a=null,n.push(D);try{O(e(n))}catch(N){$(N)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=pDefer()})}},_=O=>a!=null?a(O):(n.push(O),o),b=O=>(n=new FIFO,a!=null?a({error:O}):(n.push({error:O}),o)),x=O=>{if(l)return o;if(t?.objectMode!==!0&&O?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return _({done:!1,value:O})},E=O=>l?o:(l=!0,O!=null?b(O):_({done:!0})),I=()=>(n=new FIFO,E(),{done:!0}),k=O=>(E(O),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:u,return:I,throw:k,push:x,end:E,get readableLength(){return n.size},onEmpty:async O=>{const $=O?.signal;if($?.throwIfAborted(),n.isEmpty())return;let D,N;$!=null&&(D=new Promise((H,ie)=>{N=()=>{ie(new AbortError$6)},$.addEventListener("abort",N)}));try{await Promise.race([c.promise,D])}finally{N!=null&&$!=null&&$?.removeEventListener("abort",N)}}},r==null)return o;const T=o;return o={[Symbol.asyncIterator](){return this},next(){return T.next()},throw(O){return T.throw(O),r!=null&&(r(O),r=void 0),{done:!0}},return(){return T.return(),r!=null&&(r(),r=void 0),{done:!0}},push:x,end(O){return T.end(O),r!=null&&(r(O),r=void 0),o},get readableLength(){return T.readableLength}},o}class CodeError$2 extends Error{constructor(r,n){super(r);Ke(this,"code");this.code=n}}class AbortError$5 extends CodeError$2{constructor(r){super(r,"ABORT_ERR");Ke(this,"type");this.type="aborted"}}function byteStream(e){const t=pushable();e.sink(t).catch(a=>{t.end(a)}),e.sink=async a=>{for await(const l of a)t.push(l);t.end()};let r=e.source;e.source[Symbol.iterator]!=null?r=e.source[Symbol.iterator]():e.source[Symbol.asyncIterator]!=null&&(r=e.source[Symbol.asyncIterator]());const n=new Uint8ArrayList;return{read:async(a,l)=>{l?.signal?.throwIfAborted();let c;const u=new Promise((_,b)=>{c=()=>{b(new AbortError$5("Read aborted"))},l?.signal?.addEventListener("abort",c)});try{if(a==null){const{done:b,value:x}=await Promise.race([r.next(),u]);return b===!0?new Uint8ArrayList:x}for(;n.byteLength{l?.signal?.throwIfAborted(),a instanceof Uint8Array?t.push(a):t.push(a.subarray()),await t.onEmpty(l)},unwrap:()=>{const a=e.source;return e.source=async function*(){yield*n,yield*a}(),e}}}class CodeError$1 extends Error{constructor(r,n){super(r);Ke(this,"code");this.code=n}}const defaultLengthDecoder=e=>decode$b(e);defaultLengthDecoder.bytes=0;function lpStream(e,t){const r=byteStream(e);return{read:async o=>{let a=-1;const l=new Uint8ArrayList,c=t?.lengthDecoder??defaultLengthDecoder;for(;;){l.append(await r.read(1,o));try{a=c(l)}catch(u){if(u instanceof RangeError)continue;throw u}if(a>-1)break;if(t?.maxLengthLength!=null&&l.byteLength>t.maxLengthLength)throw new CodeError$1("message length length too long","ERR_MSG_LENGTH_TOO_LONG")}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new CodeError$1("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(a,o)},write:async(o,a)=>{await r.write(encode$c.single(o,t),a)},unwrap:()=>r.unwrap()}}function pair(){const e=pDefer();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){yield*await e.promise}()}}function duplexPair(){const e=pair(),t=pair();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}function isAsyncIterable$9(e){return e[Symbol.asyncIterator]!=null}function merge$1(...e){const t=[];for(const r of e)isAsyncIterable$9(r)||t.push(r);return t.length===e.length?function*(){for(const r of t)yield*r}():async function*(){const r=pushable({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(const o of n)r.push(o)})),r.end()}catch(n){r.end(n)}}),yield*r}()}function pipe(e,...t){if(e==null)throw new Error("Empty pipeline");if(isDuplex(e)){const n=e;e=()=>n.source}else if(isIterable(e)||isAsyncIterable$8(e)){const n=e;e=()=>n}const r=[e,...t];if(r.length>1&&isDuplex(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n{let t;for(;e.length>0;)t=e.shift()(t);return t},isAsyncIterable$8=e=>e?.[Symbol.asyncIterator]!=null,isIterable=e=>e?.[Symbol.iterator]!=null,isDuplex=e=>e==null?!1:e.sink!=null&&e.source!=null,duplexPipelineFn=e=>t=>{const r=e.sink(t);if(r?.then!=null){const n=pushable({objectMode:!0});r.then(()=>{n.end()},l=>{n.end(l)});let o;const a=e.source;if(isAsyncIterable$8(a))o=async function*(){yield*a,n.end()};else if(isIterable(a))o=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return merge$1(n,o())}return e.source},NOISE_MSG_MAX_LENGTH_BYTES=65535,NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG=NOISE_MSG_MAX_LENGTH_BYTES-16,DUMP_SESSION_KEYS=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u8a$2=e=>e instanceof Uint8Array,u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView$1=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$1)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$2(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes$2(e){if(typeof e=="string"&&(e=utf8ToBytes$2(e)),!u8a$2(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}const isPlainObject$1=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function checkOpts(e,t){if(t!==void 0&&(typeof t!="object"||!isPlainObject$1(t)))throw new Error("options must be object or undefined");return Object.assign(e,t)}function ensureBytes$1(e,t){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");if(typeof t=="number"&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}function equalBytes$1(e,t){if(e.length!==t.length)throw new Error("equalBytes: Different size of Uint8Arrays");let r=!0;for(let n=0;n>o&a),c=Number(r&a),u=n?4:0,_=n?0:4;e.setUint32(t+u,l,n),e.setUint32(t+_,c,n)}function number$3(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function bytes$1(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash$2(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("hash must be wrapped by utils.wrapConstructor");number$3(e.outputLen),number$3(e.blockLen)}function exists$1(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output$1(e,t){bytes$1(e);const r=t.outputLen;if(e.lengthe[t++]&255|(e[t++]&255)<<8;class Poly1305{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=toBytes$2(t),ensureBytes$1(t,32);const r=u8to16(t,0),n=u8to16(t,2),o=u8to16(t,4),a=u8to16(t,6),l=u8to16(t,8),c=u8to16(t,10),u=u8to16(t,12),_=u8to16(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|a<<9)&8191,this.r[4]=(a>>>4|l<<12)&255,this.r[5]=l>>>1&8190,this.r[6]=(l>>>14|c<<2)&8191,this.r[7]=(c>>>11|u<<5)&8065,this.r[8]=(u>>>8|_<<8)&8191,this.r[9]=_>>>5&127;for(let b=0;b<8;b++)this.pad[b]=u8to16(t,16+2*b)}process(t,r,n=!1){const o=n?0:2048,{h:a,r:l}=this,c=l[0],u=l[1],_=l[2],b=l[3],x=l[4],E=l[5],I=l[6],k=l[7],T=l[8],O=l[9],$=u8to16(t,r+0),D=u8to16(t,r+2),N=u8to16(t,r+4),H=u8to16(t,r+6),ie=u8to16(t,r+8),ue=u8to16(t,r+10),de=u8to16(t,r+12),le=u8to16(t,r+14);let ce=a[0]+($&8191),ve=a[1]+(($>>>13|D<<3)&8191),ee=a[2]+((D>>>10|N<<6)&8191),he=a[3]+((N>>>7|H<<9)&8191),ne=a[4]+((H>>>4|ie<<12)&8191),xe=a[5]+(ie>>>1&8191),te=a[6]+((ie>>>14|ue<<2)&8191),ae=a[7]+((ue>>>11|de<<5)&8191),ge=a[8]+((de>>>8|le<<8)&8191),se=a[9]+(le>>>5|o),Se=0,Pe=Se+ce*c+ve*(5*O)+ee*(5*T)+he*(5*k)+ne*(5*I);Se=Pe>>>13,Pe&=8191,Pe+=xe*(5*E)+te*(5*x)+ae*(5*b)+ge*(5*_)+se*(5*u),Se+=Pe>>>13,Pe&=8191;let Ue=Se+ce*u+ve*c+ee*(5*O)+he*(5*T)+ne*(5*k);Se=Ue>>>13,Ue&=8191,Ue+=xe*(5*I)+te*(5*E)+ae*(5*x)+ge*(5*b)+se*(5*_),Se+=Ue>>>13,Ue&=8191;let Be=Se+ce*_+ve*u+ee*c+he*(5*O)+ne*(5*T);Se=Be>>>13,Be&=8191,Be+=xe*(5*k)+te*(5*I)+ae*(5*E)+ge*(5*x)+se*(5*b),Se+=Be>>>13,Be&=8191;let fe=Se+ce*b+ve*_+ee*u+he*c+ne*(5*O);Se=fe>>>13,fe&=8191,fe+=xe*(5*T)+te*(5*k)+ae*(5*I)+ge*(5*E)+se*(5*x),Se+=fe>>>13,fe&=8191;let ye=Se+ce*x+ve*b+ee*_+he*u+ne*c;Se=ye>>>13,ye&=8191,ye+=xe*(5*O)+te*(5*T)+ae*(5*k)+ge*(5*I)+se*(5*E),Se+=ye>>>13,ye&=8191;let Ce=Se+ce*E+ve*x+ee*b+he*_+ne*u;Se=Ce>>>13,Ce&=8191,Ce+=xe*c+te*(5*O)+ae*(5*T)+ge*(5*k)+se*(5*I),Se+=Ce>>>13,Ce&=8191;let Le=Se+ce*I+ve*E+ee*x+he*b+ne*_;Se=Le>>>13,Le&=8191,Le+=xe*u+te*c+ae*(5*O)+ge*(5*T)+se*(5*k),Se+=Le>>>13,Le&=8191;let Fe=Se+ce*k+ve*I+ee*E+he*x+ne*b;Se=Fe>>>13,Fe&=8191,Fe+=xe*_+te*u+ae*c+ge*(5*O)+se*(5*T),Se+=Fe>>>13,Fe&=8191;let Oe=Se+ce*T+ve*k+ee*I+he*E+ne*x;Se=Oe>>>13,Oe&=8191,Oe+=xe*b+te*_+ae*u+ge*c+se*(5*O),Se+=Oe>>>13,Oe&=8191;let be=Se+ce*O+ve*T+ee*k+he*I+ne*E;Se=be>>>13,be&=8191,be+=xe*x+te*b+ae*_+ge*u+se*c,Se+=be>>>13,be&=8191,Se=(Se<<2)+Se|0,Se=Se+Pe|0,Pe=Se&8191,Se=Se>>>13,Ue+=Se,a[0]=Pe,a[1]=Ue,a[2]=Be,a[3]=fe,a[4]=ye,a[5]=Ce,a[6]=Le,a[7]=Fe,a[8]=Oe,a[9]=be}finalize(){const{h:t,pad:r}=this,n=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let c=2;c<10;c++)t[c]+=o,o=t[c]>>>13,t[c]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let c=1;c<10;c++)n[c]=t[c]+o,o=n[c]>>>13,n[c]&=8191;n[9]-=1<<13;let a=(o^1)-1;for(let c=0;c<10;c++)n[c]&=a;a=~a;for(let c=0;c<10;c++)t[c]=t[c]&a|n[c];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let l=t[0]+r[0];t[0]=l&65535;for(let c=1;c<8;c++)l=(t[c]+r[c]|0)+(l>>>16)|0,t[c]=l&65535}update(t){assert.exists(this);const{buffer:r,blockLen:n}=this;t=toBytes$2(t);const o=t.length;for(let a=0;a>>0,t[a++]=n[l]>>>8;return t}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}}function wrapConstructorWithKey(e){const t=(n,o)=>e(o).update(toBytes$2(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}const poly1305=wrapConstructorWithKey(e=>new Poly1305(e)),sigma16=utf8ToBytes$2("expand 16-byte k"),sigma32=utf8ToBytes$2("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32),isAligned32=e=>!(e.byteOffset%4),salsaBasic=e=>{const{core:t,rounds:r,counterRight:n,counterLen:o,allow128bitKeys:a,extendNonceFn:l,blockLen:c}=checkOpts({rounds:20,counterRight:!1,counterLen:8,allow128bitKeys:!0,blockLen:64},e);assert.number(o),assert.number(r),assert.number(c),assert.bool(n),assert.bool(a);const u=c/4;if(c%4!==0)throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes");return(_,b,x,E,I=0)=>{if(assert.bytes(_),assert.bytes(b),assert.bytes(x),E||(E=new Uint8Array(x.length)),assert.bytes(E),assert.number(I),I<0||I>=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");if(E.length=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");const ee=Math.min(c,le-ce);if(ee===c&&de&&ue){const he=ce/4;if(ce%4!==0)throw new Error("Salsa/ChaCha: invalid block position");for(let ne=0;nee<>>32-t;function chachaCore(e,t,r,n,o,a=20){let l=e[0],c=e[1],u=e[2],_=e[3],b=t[0],x=t[1],E=t[2],I=t[3],k=t[4],T=t[5],O=t[6],$=t[7],D=o,N=r[0],H=r[1],ie=r[2],ue=l,de=c,le=u,ce=_,ve=b,ee=x,he=E,ne=I,xe=k,te=T,ae=O,ge=$,se=D,Se=N,Pe=H,Ue=ie;for(let fe=0;fe{e.update(t);const r=t.length%16;r&&e.update(ZERO.subarray(r))},computeTag=(e,t,r,n,o)=>{const a=e(t,r,new Uint8Array(32)),l=poly1305.create(a);o&&updatePadded(l,o),updatePadded(l,n);const c=new Uint8Array(16),u=createView$1(c);setBigUint64$1(u,0,BigInt(o?o.length:0),!0),setBigUint64$1(u,8,BigInt(n.length),!0),l.update(c);const _=l.digest();return a.fill(0),_},_poly1305_aead=e=>(t,r,n)=>(ensureBytes$1(t,32),ensureBytes$1(r),{tagLength:16,encrypt:(a,l)=>{const c=a.length,u=c+16;l?ensureBytes$1(l,u):l=new Uint8Array(u),e(t,r,a,l,1);const _=computeTag(e,t,r,l.subarray(0,-16),n);return l.set(_,c),l},decrypt:(a,l)=>{const c=a.length,u=c-16;if(c<16)throw new Error(`encrypted data must be at least ${16} bytes`);l?ensureBytes$1(l,u):l=new Uint8Array(u);const _=a.subarray(0,-16),b=a.subarray(-16),x=computeTag(e,t,r,_,n);if(!equalBytes$1(b,x))throw new Error("invalid tag");return e(t,r,_,l,1),l}}),chacha20poly1305=_poly1305_aead(chacha20);function number$2(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bytes(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash$1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(e.outputLen),number$2(e.blockLen)}function exists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output(e,t){bytes(e);const r=t.outputLen;if(e.lengthe instanceof Uint8Array,createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr=(e,t)=>e<<32-t|e>>>t,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$1(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes$1(e){if(typeof e=="string"&&(e=utf8ToBytes$1(e)),!u8a$1(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function concatBytes$1(...e){const t=new Uint8Array(e.reduce((n,o)=>n+o.length,0));let r=0;return e.forEach(n=>{if(!u8a$1(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(e){const t=n=>e().update(toBytes$1(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function randomBytes$1(e=32){if(crypto$3&&typeof crypto$3.getRandomValues=="function")return crypto$3.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const o=BigInt(32),a=BigInt(4294967295),l=Number(r>>o&a),c=Number(r&a),u=n?4:0,_=n?0:4;e.setUint32(t+u,l,n),e.setUint32(t+_,c,n)}class SHA2 extends Hash{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=createView(this.buffer)}update(t){exists(this);const{view:r,buffer:n,blockLen:o}=this;t=toBytes$1(t);const a=t.length;for(let l=0;lo-l&&(this.process(n,0),l=0);for(let x=l;xb.length)throw new Error("_sha2: outputLen bigger than state");for(let x=0;x<_;x++)c.setUint32(4*x,b[x],a)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:a,destroyed:l,pos:c}=this;return t.length=o,t.pos=c,t.finished=a,t.destroyed=l,o%r&&t.buffer.set(n),t}}const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(e,t=!1){return t?{h:Number(e&U32_MASK64),l:Number(e>>_32n&U32_MASK64)}:{h:Number(e>>_32n&U32_MASK64)|0,l:Number(e&U32_MASK64)|0}}function split(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;oBigInt(e>>>0)<<_32n|BigInt(t>>>0),shrSH=(e,t,r)=>e>>>r,shrSL=(e,t,r)=>e<<32-r|t>>>r,rotrSH=(e,t,r)=>e>>>r|t<<32-r,rotrSL=(e,t,r)=>e<<32-r|t>>>r,rotrBH=(e,t,r)=>e<<64-r|t>>>r-32,rotrBL=(e,t,r)=>e>>>r-32|t<<64-r,rotr32H=(e,t)=>t,rotr32L=(e,t)=>e,rotlSH=(e,t,r)=>e<>>32-r,rotlSL=(e,t,r)=>t<>>32-r,rotlBH=(e,t,r)=>t<>>64-r,rotlBL=(e,t,r)=>e<>>64-r;function add(e,t,r,n){const o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}const add3L=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,add5L=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),add5H=(e,t,r,n,o,a)=>t+r+n+o+a+(e/2**32|0)|0,u64={fromBig,split,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L},u64$1=u64,[SHA512_Kh,SHA512_Kl]=(()=>u64$1.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:r,Bh:n,Bl:o,Ch:a,Cl:l,Dh:c,Dl:u,Eh:_,El:b,Fh:x,Fl:E,Gh:I,Gl:k,Hh:T,Hl:O}=this;return[t,r,n,o,a,l,c,u,_,b,x,E,I,k,T,O]}set(t,r,n,o,a,l,c,u,_,b,x,E,I,k,T,O){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=a|0,this.Cl=l|0,this.Dh=c|0,this.Dl=u|0,this.Eh=_|0,this.El=b|0,this.Fh=x|0,this.Fl=E|0,this.Gh=I|0,this.Gl=k|0,this.Hh=T|0,this.Hl=O|0}process(t,r){for(let N=0;N<16;N++,r+=4)SHA512_W_H[N]=t.getUint32(r),SHA512_W_L[N]=t.getUint32(r+=4);for(let N=16;N<80;N++){const H=SHA512_W_H[N-15]|0,ie=SHA512_W_L[N-15]|0,ue=u64$1.rotrSH(H,ie,1)^u64$1.rotrSH(H,ie,8)^u64$1.shrSH(H,ie,7),de=u64$1.rotrSL(H,ie,1)^u64$1.rotrSL(H,ie,8)^u64$1.shrSL(H,ie,7),le=SHA512_W_H[N-2]|0,ce=SHA512_W_L[N-2]|0,ve=u64$1.rotrSH(le,ce,19)^u64$1.rotrBH(le,ce,61)^u64$1.shrSH(le,ce,6),ee=u64$1.rotrSL(le,ce,19)^u64$1.rotrBL(le,ce,61)^u64$1.shrSL(le,ce,6),he=u64$1.add4L(de,ee,SHA512_W_L[N-7],SHA512_W_L[N-16]),ne=u64$1.add4H(he,ue,ve,SHA512_W_H[N-7],SHA512_W_H[N-16]);SHA512_W_H[N]=ne|0,SHA512_W_L[N]=he|0}let{Ah:n,Al:o,Bh:a,Bl:l,Ch:c,Cl:u,Dh:_,Dl:b,Eh:x,El:E,Fh:I,Fl:k,Gh:T,Gl:O,Hh:$,Hl:D}=this;for(let N=0;N<80;N++){const H=u64$1.rotrSH(x,E,14)^u64$1.rotrSH(x,E,18)^u64$1.rotrBH(x,E,41),ie=u64$1.rotrSL(x,E,14)^u64$1.rotrSL(x,E,18)^u64$1.rotrBL(x,E,41),ue=x&I^~x&T,de=E&k^~E&O,le=u64$1.add5L(D,ie,de,SHA512_Kl[N],SHA512_W_L[N]),ce=u64$1.add5H(le,$,H,ue,SHA512_Kh[N],SHA512_W_H[N]),ve=le|0,ee=u64$1.rotrSH(n,o,28)^u64$1.rotrBH(n,o,34)^u64$1.rotrBH(n,o,39),he=u64$1.rotrSL(n,o,28)^u64$1.rotrBL(n,o,34)^u64$1.rotrBL(n,o,39),ne=n&a^n&c^a&c,xe=o&l^o&u^l&u;$=T|0,D=O|0,T=I|0,O=k|0,I=x|0,k=E|0,{h:x,l:E}=u64$1.add(_|0,b|0,ce|0,ve|0),_=c|0,b=u|0,c=a|0,u=l|0,a=n|0,l=o|0;const te=u64$1.add3L(ve,he,xe);n=u64$1.add3H(te,ce,ee,ne),o=te|0}({h:n,l:o}=u64$1.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:a,l}=u64$1.add(this.Bh|0,this.Bl|0,a|0,l|0),{h:c,l:u}=u64$1.add(this.Ch|0,this.Cl|0,c|0,u|0),{h:_,l:b}=u64$1.add(this.Dh|0,this.Dl|0,_|0,b|0),{h:x,l:E}=u64$1.add(this.Eh|0,this.El|0,x|0,E|0),{h:I,l:k}=u64$1.add(this.Fh|0,this.Fl|0,I|0,k|0),{h:T,l:O}=u64$1.add(this.Gh|0,this.Gl|0,T|0,O|0),{h:$,l:D}=u64$1.add(this.Hh|0,this.Hl|0,$|0,D|0),this.set(n,o,a,l,c,u,_,b,x,E,I,k,T,O,$,D)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512$3=wrapConstructor(()=>new SHA512);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$5=BigInt(0),_1n$7=BigInt(1),_2n$4=BigInt(2),u8a=e=>e instanceof Uint8Array,hexes=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(e){if(!u8a(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!u8a(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function equalBytes(e,t){if(e.length!==t.length)return!1;for(let r=0;r_0n$5;e>>=_1n$7,t+=1);return t}function bitGet(e,t){return e>>BigInt(t)&_1n$7}const bitSet=(e,t,r)=>e|(r?_1n$7:_0n$5)<(_2n$4<new Uint8Array(e),u8fr=e=>Uint8Array.from(e);function createHmacDrbg(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=u8n(e),o=u8n(e),a=0;const l=()=>{n.fill(1),o.fill(0),a=0},c=(...x)=>r(o,n,...x),u=(x=u8n())=>{o=c(u8fr([0]),x),n=c(),x.length!==0&&(o=c(u8fr([1]),x),n=c())},_=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let x=0;const E=[];for(;x{l(),u(x);let I;for(;!(I=E(_()));)u();return l(),I}}const validatorFns={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function validateObject(e,t,r={}){const n=(o,a,l)=>{const c=validatorFns[a];if(typeof c!="function")throw new Error(`Invalid validator "${a}", expected function`);const u=e[o];if(!(l&&u===void 0)&&!c(u,e))throw new Error(`Invalid param ${String(o)}=${u} (${typeof u}), expected ${a}`)};for(const[o,a]of Object.entries(t))n(o,a,!1);for(const[o,a]of Object.entries(r))n(o,a,!0);return e}const ut=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex,numberToHexUnpadded,hexToNumber,hexToBytes,bytesToNumberBE,bytesToNumberLE,numberToBytesBE,numberToBytesLE,numberToVarBytesBE,ensureBytes,concatBytes,equalBytes,utf8ToBytes,bitLen,bitGet,bitSet,bitMask,createHmacDrbg,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$6=BigInt(1),_2n$3=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n$1=BigInt(5),_8n$1=BigInt(8);BigInt(9);BigInt(16);function mod(e,t){const r=e%t;return r>=_0n$4?r:t+r}function pow(e,t,r){if(r<=_0n$4||t<_0n$4)throw new Error("Expected power/modulo > 0");if(r===_1n$6)return _0n$4;let n=_1n$6;for(;t>_0n$4;)t&_1n$6&&(n=n*e%r),e=e*e%r,t>>=_1n$6;return n}function pow2(e,t,r){let n=e;for(;t-- >_0n$4;)n*=n,n%=r;return n}function invert(e,t){if(e===_0n$4||t<=_0n$4)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=mod(e,t),n=t,o=_0n$4,a=_1n$6;for(;r!==_0n$4;){const c=n/r,u=n%r,_=o-a*c;n=r,r=u,o=a,a=_}if(n!==_1n$6)throw new Error("invert: does not exist");return mod(o,t)}function tonelliShanks(e){const t=(e-_1n$6)/_2n$3;let r,n,o;for(r=e-_1n$6,n=0;r%_2n$3===_0n$4;r/=_2n$3,n++);for(o=_2n$3;o(mod(e,t)&_1n$6)===_1n$6,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=FIELD_FIELDS.reduce((n,o)=>(n[o]="function",n),t);return validateObject(e,r)}function FpPow(e,t,r){if(r<_0n$4)throw new Error("Expected power > 0");if(r===_0n$4)return e.ONE;if(r===_1n$6)return t;let n=e.ONE,o=t;for(;r>_0n$4;)r&_1n$6&&(n=e.mul(n,o)),o=e.sqr(o),r>>=_1n$6;return n}function FpInvertBatch(e,t){const r=new Array(t.length),n=t.reduce((a,l,c)=>e.is0(l)?a:(r[c]=a,e.mul(a,l)),e.ONE),o=e.inv(n);return t.reduceRight((a,l,c)=>e.is0(l)?a:(r[c]=e.mul(a,r[c]),e.mul(a,l)),o),r}function nLength(e,t){const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Field(e,t,r=!1,n={}){if(e<=_0n$4)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:o,nByteLength:a}=nLength(e,t);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");const l=FpSqrt(e),c=Object.freeze({ORDER:e,BITS:o,BYTES:a,MASK:bitMask(o),ZERO:_0n$4,ONE:_1n$6,create:u=>mod(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof u}`);return _0n$4<=u&&uu===_0n$4,isOdd:u=>(u&_1n$6)===_1n$6,neg:u=>mod(-u,e),eql:(u,_)=>u===_,sqr:u=>mod(u*u,e),add:(u,_)=>mod(u+_,e),sub:(u,_)=>mod(u-_,e),mul:(u,_)=>mod(u*_,e),pow:(u,_)=>FpPow(c,u,_),div:(u,_)=>mod(u*invert(_,e),e),sqrN:u=>u*u,addN:(u,_)=>u+_,subN:(u,_)=>u-_,mulN:(u,_)=>u*_,inv:u=>invert(u,e),sqrt:n.sqrt||(u=>l(c,u)),invertBatch:u=>FpInvertBatch(c,u),cmov:(u,_,b)=>b?_:u,toBytes:u=>r?numberToBytesLE(u,a):numberToBytesBE(u,a),fromBytes:u=>{if(u.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${u.length}`);return r?bytesToNumberLE(u):bytesToNumberBE(u)}});return Object.freeze(c)}function FpSqrtEven(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");const r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function getFieldBytesLength(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(e){const t=getFieldBytesLength(e);return t+Math.ceil(t/2)}function mapHashToField(e,t,r=!1){const n=e.length,o=getFieldBytesLength(t),a=getMinHashLength(t);if(n<16||n1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);const l=r?bytesToNumberBE(e):bytesToNumberLE(e),c=mod(l,t-_1n$6)+_1n$6;return r?numberToBytesLE(c,o):numberToBytesBE(c,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$5=BigInt(1);function wNAF(e,t){const r=(o,a)=>{const l=a.negate();return o?l:a},n=o=>{const a=Math.ceil(t/o)+1,l=2**(o-1);return{windows:a,windowSize:l}};return{constTimeNegate:r,unsafeLadder(o,a){let l=e.ZERO,c=o;for(;a>_0n$3;)a&_1n$5&&(l=l.add(c)),c=c.double(),a>>=_1n$5;return l},precomputeWindow(o,a){const{windows:l,windowSize:c}=n(a),u=[];let _=o,b=_;for(let x=0;x>=I,O>u&&(O-=E,l+=_1n$5);const $=T,D=T+Math.abs(O)-1,N=k%2!==0,H=O<0;O===0?b=b.add(r(N,a[$])):_=_.add(r(H,a[D]))}return{p:_,f:b}},wNAFCached(o,a,l,c){const u=o._WINDOW_SIZE||1;let _=a.get(o);return _||(_=this.precomputeWindow(o,u),u!==1&&a.set(o,c(_))),this.wNAF(u,_,l)}}}function validateBasic(e){return validateField(e.Fp),validateObject(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),_8n=BigInt(8),VERIFY_DEFAULT={zip215:!0};function validateOpts$2(e){const t=validateBasic(e);return validateObject(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function twistedEdwards(e){const t=validateOpts$2(e),{Fp:r,n,prehash:o,hash:a,randomBytes:l,nByteLength:c,h:u}=t,_=_2n$2<{try{return{isValid:!0,value:r.sqrt(se*r.inv(Se))}}catch{return{isValid:!1,value:_0n$2}}}),E=t.adjustScalarBytes||(se=>se),I=t.domain||((se,Se,Pe)=>{if(Se.length||Pe)throw new Error("Contexts/pre-hash are not supported");return se}),k=se=>typeof se=="bigint"&&_0n$2k(se)&&k(Se)&&sese===_0n$2||T(se,_);function $(se,Se){if(T(se,Se))return se;throw new Error(`Expected valid scalar < ${Se}, got ${typeof se} ${se}`)}function D(se){return se===_0n$2?se:$(se,n)}const N=new Map;function H(se){if(!(se instanceof ie))throw new Error("ExtendedPoint expected")}class ie{constructor(Se,Pe,Ue,Be){if(this.ex=Se,this.ey=Pe,this.ez=Ue,this.et=Be,!O(Se))throw new Error("x required");if(!O(Pe))throw new Error("y required");if(!O(Ue))throw new Error("z required");if(!O(Be))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(Se){if(Se instanceof ie)throw new Error("extended point not allowed");const{x:Pe,y:Ue}=Se||{};if(!O(Pe)||!O(Ue))throw new Error("invalid affine point");return new ie(Pe,Ue,_1n$4,b(Pe*Ue))}static normalizeZ(Se){const Pe=r.invertBatch(Se.map(Ue=>Ue.ez));return Se.map((Ue,Be)=>Ue.toAffine(Pe[Be])).map(ie.fromAffine)}_setWindowSize(Se){this._WINDOW_SIZE=Se,N.delete(this)}assertValidity(){const{a:Se,d:Pe}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:Ue,ey:Be,ez:fe,et:ye}=this,Ce=b(Ue*Ue),Le=b(Be*Be),Fe=b(fe*fe),Oe=b(Fe*Fe),be=b(Ce*Se),Re=b(Fe*b(be+Le)),Ie=b(Oe+b(Pe*b(Ce*Le)));if(Re!==Ie)throw new Error("bad point: equation left != right (1)");const we=b(Ue*Be),oe=b(fe*ye);if(we!==oe)throw new Error("bad point: equation left != right (2)")}equals(Se){H(Se);const{ex:Pe,ey:Ue,ez:Be}=this,{ex:fe,ey:ye,ez:Ce}=Se,Le=b(Pe*Ce),Fe=b(fe*Be),Oe=b(Ue*Ce),be=b(ye*Be);return Le===Fe&&Oe===be}is0(){return this.equals(ie.ZERO)}negate(){return new ie(b(-this.ex),this.ey,this.ez,b(-this.et))}double(){const{a:Se}=t,{ex:Pe,ey:Ue,ez:Be}=this,fe=b(Pe*Pe),ye=b(Ue*Ue),Ce=b(_2n$2*b(Be*Be)),Le=b(Se*fe),Fe=Pe+Ue,Oe=b(b(Fe*Fe)-fe-ye),be=Le+ye,Re=be-Ce,Ie=Le-ye,we=b(Oe*Re),oe=b(be*Ie),pe=b(Oe*Ie),ke=b(Re*be);return new ie(we,oe,ke,pe)}add(Se){H(Se);const{a:Pe,d:Ue}=t,{ex:Be,ey:fe,ez:ye,et:Ce}=this,{ex:Le,ey:Fe,ez:Oe,et:be}=Se;if(Pe===BigInt(-1)){const Ve=b((fe-Be)*(Fe+Le)),Ae=b((fe+Be)*(Fe-Le)),He=b(Ae-Ve);if(He===_0n$2)return this.double();const Ge=b(ye*_2n$2*be),Ze=b(Ce*_2n$2*Oe),$e=Ze+Ge,me=Ae+Ve,Ee=Ze-Ge,je=b($e*He),nt=b(me*Ee),ot=b($e*Ee),dt=b(He*me);return new ie(je,nt,dt,ot)}const Re=b(Be*Le),Ie=b(fe*Fe),we=b(Ce*Ue*be),oe=b(ye*Oe),pe=b((Be+fe)*(Le+Fe)-Re-Ie),ke=oe-we,Ne=oe+we,ze=b(Ie-Pe*Re),Xe=b(pe*ke),Je=b(Ne*ze),rt=b(pe*ze),qe=b(ke*Ne);return new ie(Xe,Je,qe,rt)}subtract(Se){return this.add(Se.negate())}wNAF(Se){return le.wNAFCached(this,N,Se,ie.normalizeZ)}multiply(Se){const{p:Pe,f:Ue}=this.wNAF($(Se,n));return ie.normalizeZ([Pe,Ue])[0]}multiplyUnsafe(Se){let Pe=D(Se);return Pe===_0n$2?de:this.equals(de)||Pe===_1n$4?this:this.equals(ue)?this.wNAF(Pe).p:le.unsafeLadder(this,Pe)}isSmallOrder(){return this.multiplyUnsafe(u).is0()}isTorsionFree(){return le.unsafeLadder(this,n).is0()}toAffine(Se){const{ex:Pe,ey:Ue,ez:Be}=this,fe=this.is0();Se==null&&(Se=fe?_8n:r.inv(Be));const ye=b(Pe*Se),Ce=b(Ue*Se),Le=b(Be*Se);if(fe)return{x:_0n$2,y:_1n$4};if(Le!==_1n$4)throw new Error("invZ was invalid");return{x:ye,y:Ce}}clearCofactor(){const{h:Se}=t;return Se===_1n$4?this:this.multiplyUnsafe(Se)}static fromHex(Se,Pe=!1){const{d:Ue,a:Be}=t,fe=r.BYTES;Se=ensureBytes("pointHex",Se,fe);const ye=Se.slice(),Ce=Se[fe-1];ye[fe-1]=Ce&-129;const Le=bytesToNumberLE(ye);Le===_0n$2||(Pe?$(Le,_):$(Le,r.ORDER));const Fe=b(Le*Le),Oe=b(Fe-_1n$4),be=b(Ue*Fe-Be);let{isValid:Re,value:Ie}=x(Oe,be);if(!Re)throw new Error("Point.fromHex: invalid y coordinate");const we=(Ie&_1n$4)===_1n$4,oe=(Ce&128)!==0;if(!Pe&&Ie===_0n$2&&oe)throw new Error("Point.fromHex: x=0 and x_0=1");return oe!==we&&(Ie=b(-Ie)),ie.fromAffine({x:Ie,y:Le})}static fromPrivateKey(Se){return ee(Se).point}toRawBytes(){const{x:Se,y:Pe}=this.toAffine(),Ue=numberToBytesLE(Pe,r.BYTES);return Ue[Ue.length-1]|=Se&_1n$4?128:0,Ue}toHex(){return bytesToHex(this.toRawBytes())}}ie.BASE=new ie(t.Gx,t.Gy,_1n$4,b(t.Gx*t.Gy)),ie.ZERO=new ie(_0n$2,_1n$4,_1n$4,_0n$2);const{BASE:ue,ZERO:de}=ie,le=wNAF(ie,c*8);function ce(se){return mod(se,n)}function ve(se){return ce(bytesToNumberLE(se))}function ee(se){const Se=c;se=ensureBytes("private key",se,Se);const Pe=ensureBytes("hashed private key",a(se),2*Se),Ue=E(Pe.slice(0,Se)),Be=Pe.slice(Se,2*Se),fe=ve(Ue),ye=ue.multiply(fe),Ce=ye.toRawBytes();return{head:Ue,prefix:Be,scalar:fe,point:ye,pointBytes:Ce}}function he(se){return ee(se).pointBytes}function ne(se=new Uint8Array,...Se){const Pe=concatBytes(...Se);return ve(a(I(Pe,ensureBytes("context",se),!!o)))}function xe(se,Se,Pe={}){se=ensureBytes("message",se),o&&(se=o(se));const{prefix:Ue,scalar:Be,pointBytes:fe}=ee(Se),ye=ne(Pe.context,Ue,se),Ce=ue.multiply(ye).toRawBytes(),Le=ne(Pe.context,Ce,fe,se),Fe=ce(ye+Le*Be);D(Fe);const Oe=concatBytes(Ce,numberToBytesLE(Fe,r.BYTES));return ensureBytes("result",Oe,c*2)}const te=VERIFY_DEFAULT;function ae(se,Se,Pe,Ue=te){const{context:Be,zip215:fe}=Ue,ye=r.BYTES;se=ensureBytes("signature",se,2*ye),Se=ensureBytes("message",Se),o&&(Se=o(Se));const Ce=bytesToNumberLE(se.slice(ye,2*ye));let Le,Fe,Oe;try{Le=ie.fromHex(Pe,fe),Fe=ie.fromHex(se.slice(0,ye),fe),Oe=ue.multiplyUnsafe(Ce)}catch{return!1}if(!fe&&Le.isSmallOrder())return!1;const be=ne(Be,Fe.toRawBytes(),Le.toRawBytes(),Se);return Fe.add(Le.multiplyUnsafe(be)).subtract(Oe).clearCofactor().equals(ie.ZERO)}return ue._setWindowSize(8),{CURVE:t,getPublicKey:he,sign:xe,verify:ae,ExtendedPoint:ie,utils:{getExtendedPublicKey:ee,randomPrivateKey:()=>l(r.BYTES),precompute(se=8,Se=ie.BASE){return Se._setWindowSize(se),Se.multiply(BigInt(3)),Se}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$3=BigInt(1);function validateOpts$1(e){return validateObject(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}function montgomery(e){const t=validateOpts$1(e),{P:r}=t,n=N=>mod(N,r),o=t.montgomeryBits,a=Math.ceil(o/8),l=t.nByteLength,c=t.adjustScalarBytes||(N=>N),u=t.powPminus2||(N=>pow(N,r-BigInt(2),r));function _(N,H,ie){const ue=n(N*(H-ie));return H=n(H-ue),ie=n(ie+ue),[H,ie]}function b(N){if(typeof N=="bigint"&&_0n$1<=N&&N=_0n$1;te--){const ae=ue>>te&_1n$3;he^=ae,ne=_(he,le,ve),le=ne[0],ve=ne[1],ne=_(he,ce,ee),ce=ne[0],ee=ne[1],he=ae;const ge=le+ce,se=n(ge*ge),Se=le-ce,Pe=n(Se*Se),Ue=se-Pe,Be=ve+ee,fe=ve-ee,ye=n(fe*ge),Ce=n(Be*Se),Le=ye+Ce,Fe=ye-Ce;ve=n(Le*Le),ee=n(de*n(Fe*Fe)),le=n(se*Pe),ce=n(Ue*(se+n(x*Ue)))}ne=_(he,le,ve),le=ne[0],ve=ne[1],ne=_(he,ce,ee),ce=ne[0],ee=ne[1];const xe=u(ce);return n(le*xe)}function I(N){return numberToBytesLE(n(N),a)}function k(N){const H=ensureBytes("u coordinate",N,a);return l===a&&(H[l-1]&=127),bytesToNumberLE(H)}function T(N){const H=ensureBytes("scalar",N);if(H.length!==a&&H.length!==l)throw new Error(`Expected ${a} or ${l} bytes, got ${H.length}`);return bytesToNumberLE(c(H))}function O(N,H){const ie=k(H),ue=T(N),de=E(ie,ue);if(de===_0n$1)throw new Error("Invalid private or public key received");return I(de)}const $=I(t.Gu);function D(N){return O(N,$)}return{scalarMult:O,scalarMultBase:D,getSharedSecret:(N,H)=>O(N,H),getPublicKey:N=>D(N),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:$}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n$2=BigInt(1),_2n$1=BigInt(2),_5n=BigInt(5),_10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80);function ed25519_pow_2_252_3(e){const t=ED25519_P,n=e*e%t*e%t,o=pow2(n,_2n$1,t)*n%t,a=pow2(o,_1n$2,t)*e%t,l=pow2(a,_5n,t)*a%t,c=pow2(l,_10n,t)*l%t,u=pow2(c,_20n,t)*c%t,_=pow2(u,_40n,t)*u%t,b=pow2(_,_80n,t)*_%t,x=pow2(b,_80n,t)*_%t,E=pow2(x,_10n,t)*l%t;return{pow_p_5_8:pow2(E,_2n$1,t)*e%t,b2:n}}function adjustScalarBytes(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function uvRatio(e,t){const r=ED25519_P,n=mod(t*t*t,r),o=mod(n*n*t,r),a=ed25519_pow_2_252_3(e*o).pow_p_5_8;let l=mod(e*n*a,r);const c=mod(t*l*l,r),u=l,_=mod(l*ED25519_SQRT_M1,r),b=c===e,x=c===mod(-e,r),E=c===mod(-e*ED25519_SQRT_M1,r);return b&&(l=u),(x||E)&&(l=_),isNegativeLE(l,r)&&(l=mod(-l,r)),{isValid:b||x,value:l}}const Fp$1=Field(ED25519_P,void 0,!0),ed25519Defaults={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Fp$1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512$3,randomBytes:randomBytes$1,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults);function ed25519_domain(e,t,r){if(t.length>255)throw new Error("Context is too big");return concatBytes$1(utf8ToBytes$1("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}({...ed25519Defaults});({...ed25519Defaults});const x25519=(()=>montgomery({P:ED25519_P,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=ED25519_P,{pow_p_5_8:r,b2:n}=ed25519_pow_2_252_3(e);return mod(pow2(r,BigInt(3),t)*n,t)},adjustScalarBytes,randomBytes:randomBytes$1}))(),ELL2_C1=(Fp$1.ORDER+BigInt(3))/BigInt(8);Fp$1.pow(_2n$1,ELL2_C1);Fp$1.sqrt(Fp$1.neg(Fp$1.ONE));(Fp$1.ORDER-BigInt(5))/BigInt(8);BigInt(486662);FpSqrtEven(Fp$1,Fp$1.neg(BigInt(486664)));BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class HMAC extends Hash{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,hash$1(t);const n=toBytes$1(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,a=new Uint8Array(o);a.set(n.length>o?t.create().update(n).digest():n);for(let l=0;lnew HMAC(e,t).update(r).digest();hmac$1.create=(e,t)=>new HMAC(e,t);function extract(e,t,r){return hash$1(e),r===void 0&&(r=new Uint8Array(e.outputLen)),hmac$1(e,toBytes$1(r),toBytes$1(t))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,r,n=32){if(hash$1(e),number$2(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(n/e.outputLen);r===void 0&&(r=EMPTY_BUFFER);const a=new Uint8Array(o*e.outputLen),l=hmac$1.create(e,t),c=l._cloneInto(),u=new Uint8Array(l.outputLen);for(let _=0;_e&t^~e&r,Maj=(e,t,r)=>e&t^e&r^t&r,SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:t,B:r,C:n,D:o,E:a,F:l,G:c,H:u}=this;return[t,r,n,o,a,l,c,u]}set(t,r,n,o,a,l,c,u){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=a|0,this.F=l|0,this.G=c|0,this.H=u|0}process(t,r){for(let x=0;x<16;x++,r+=4)SHA256_W[x]=t.getUint32(r,!1);for(let x=16;x<64;x++){const E=SHA256_W[x-15],I=SHA256_W[x-2],k=rotr(E,7)^rotr(E,18)^E>>>3,T=rotr(I,17)^rotr(I,19)^I>>>10;SHA256_W[x]=T+SHA256_W[x-7]+k+SHA256_W[x-16]|0}let{A:n,B:o,C:a,D:l,E:c,F:u,G:_,H:b}=this;for(let x=0;x<64;x++){const E=rotr(c,6)^rotr(c,11)^rotr(c,25),I=b+E+Chi(c,u,_)+SHA256_K[x]+SHA256_W[x]|0,T=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,o,a)|0;b=_,_=u,u=c,c=l+I|0,l=a,a=o,o=n,n=I+T|0}n=n+this.A|0,o=o+this.B|0,a=a+this.C|0,l=l+this.D|0,c=c+this.E|0,u=u+this.F|0,_=_+this.G|0,b=b+this.H|0,this.set(n,o,a,l,c,u,_,b)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256$3=wrapConstructor(()=>new SHA256),pureJsCrypto={hashSHA256(e){return sha256$3(e)},getHKDF(e,t){const r=extract(sha256$3,t,e),o=expand(sha256$3,r,void 0,96),a=o.subarray(0,32),l=o.subarray(32,64),c=o.subarray(64,96);return[a,l,c]},generateX25519KeyPair(){const e=x25519.utils.randomPrivateKey();return{publicKey:x25519.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:x25519.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return x25519.getSharedSecret(e,t)},chaCha20Poly1305Encrypt(e,t,r,n){return chacha20poly1305(n,t,r).encrypt(e)},chaCha20Poly1305Decrypt(e,t,r,n,o){return chacha20poly1305(n,t,r).decrypt(e,o)}},allocUnsafe$1=e=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e),uint16BEEncode=e=>{const t=allocUnsafe$1(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};uint16BEEncode.bytes=2;const uint16BEDecode=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};uint16BEDecode.bytes=2;function encode0(e){return concat$1([e.ne,e.ciphertext],e.ne.length+e.ciphertext.length)}function encode1(e){return concat$1([e.ne,e.ns,e.ciphertext],e.ne.length+e.ns.length+e.ciphertext.length)}function encode2(e){return concat$1([e.ns,e.ciphertext],e.ns.length+e.ciphertext.length)}function decode0(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:new Uint8Array(0)}}function decode1(e){if(e.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}function decode2(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}const CHACHA_TAG_LENGTH=16;function encryptStream(e,t){return async function*(r){for await(const n of r)for(let o=0;on.length&&(a=n.length);const l=e.encrypt(n.subarray(o,a),e.session);t?.encryptedPackets.increment(),yield uint16BEEncode(l.byteLength),yield l}}}function decryptStream(e,t){return async function*(r){for await(const n of r)for(let o=0;on.length&&(a=n.length),a-CHACHA_TAG_LENGTH0;)c.push(_%a),_=_/a|0}for(o=0;e[o]===0&&o=0;--o)n+=t[c[o]]}if(r){var b=new RegExp(".{1,"+r+"}","g");n=n.match(b).join(`\r `)}return n};api$2.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var r=_reverseAlphabets[t];if(!r){r=_reverseAlphabets[t]=[];for(var n=0;n>=8;for(;_>0;)l.push(_&255),_>>=8}for(var b=0;e[b]===a&&b0;)a.push(c%n),c=c/n|0}var u="";for(r=0;e.at(r)===0&&r=0;--r)u+=t[a[r]];return u}var forge$l=forge$m,baseN=baseN$1,util$6=util$7.exports=forge$l.util=forge$l.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){util$6.nextTick=process.nextTick,typeof setImmediate=="function"?util$6.setImmediate=setImmediate:util$6.setImmediate=util$6.nextTick;return}if(typeof setImmediate=="function"){util$6.setImmediate=function(){return setImmediate.apply(void 0,arguments)},util$6.nextTick=function(c){return setImmediate(c)};return}if(util$6.setImmediate=function(c){setTimeout(c,0)},typeof window<"u"&&typeof window.postMessage=="function"){let c=function(u){if(u.source===window&&u.data===e){u.stopPropagation();var _=t.slice();t.length=0,_.forEach(function(b){b()})}};var l=c,e="forge.setImmediate",t=[];util$6.setImmediate=function(u){t.push(u),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",c,!0)}if(typeof MutationObserver<"u"){var r=Date.now(),n=!0,o=document.createElement("div"),t=[];new MutationObserver(function(){var u=t.slice();t.length=0,u.forEach(function(_){_()})}).observe(o,{attributes:!0});var a=util$6.setImmediate;util$6.setImmediate=function(u){Date.now()-r>15?(r=Date.now(),a(u)):(t.push(u),t.length===1&&o.setAttribute("a",n=!n))}}util$6.nextTick=util$6.setImmediate})();util$6.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;util$6.globalScope=function(){return util$6.isNodejs?commonjsGlobal$2:typeof self>"u"?window:self}();util$6.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};util$6.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};util$6.isArrayBufferView=function(e){return e&&util$6.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function _checkBitsParam(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}util$6.ByteBuffer=ByteStringBuffer;function ByteStringBuffer(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(util$6.isArrayBuffer(e)||util$6.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var r=0;r_MAX_CONSTRUCTED_STRING_LENGTH&&(this.data.substr(0,1),this._constructedStringLength=0)};util$6.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};util$6.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};util$6.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};util$6.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this};util$6.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};util$6.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(util$6.encodeUtf8(e))};util$6.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};util$6.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};util$6.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};util$6.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};util$6.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};util$6.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};util$6.ByteStringBuffer.prototype.putInt=function(e,t){_checkBitsParam(t);var r="";do t-=8,r+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(r)};util$6.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t};util$6.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t};util$6.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};util$6.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};util$6.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};util$6.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};util$6.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};util$6.ByteStringBuffer.prototype.copy=function(){var e=util$6.createBuffer(this.data);return e.read=this.read,e};util$6.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};util$6.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};util$6.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};util$6.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this};util$6.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};util$6.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};util$6.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};util$6.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};util$6.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};util$6.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};util$6.DataBuffer.prototype.putInt=function(e,t){_checkBitsParam(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};util$6.DataBuffer.prototype.putSignedInt=function(e,t){return _checkBitsParam(t),this.accommodate(t/8),e<0&&(e+=2<0);return t};util$6.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t};util$6.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};util$6.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};util$6.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};util$6.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};util$6.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};util$6.DataBuffer.prototype.copy=function(){return new util$6.DataBuffer(this)};util$6.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};util$6.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};util$6.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};util$6.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return r};util$6.xorBytes=function(e,t,r){for(var n="",o="",a="",l=0,c=0;r>0;--r,++l)o=e.charCodeAt(l)^t.charCodeAt(l),c>=10&&(n+=a,a="",c=0),a+=String.fromCharCode(o),++c;return n+=a,n};util$6.hexToBytes=function(e){var t="",r=0;for(e.length&!0&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_base64Idx=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],_base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util$6.encode64=function(e,t){for(var r="",n="",o,a,l,c=0;c>2),r+=_base64.charAt((o&3)<<4|a>>4),isNaN(a)?r+="==":(r+=_base64.charAt((a&15)<<2|l>>6),r+=isNaN(l)?"=":_base64.charAt(l&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r `,r=r.substr(t));return n+=r,n};util$6.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",r,n,o,a,l=0;l>4),o!==64&&(t+=String.fromCharCode((n&15)<<4|o>>2),a!==64&&(t+=String.fromCharCode((o&3)<<6|a)));return t};util$6.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};util$6.decodeUtf8=function(e){return decodeURIComponent(escape(e))};util$6.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}};util$6.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};util$6.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var o=r,a=0;a>2),r+=_base64.charAt((o&3)<<4|a>>4),isNaN(a)?r+="==":(r+=_base64.charAt((a&15)<<2|l>>6),r+=isNaN(l)?"=":_base64.charAt(l&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r `,r=r.substr(t));return n+=r,n};util$6.binary.base64.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var o,a,l,c,u=0,_=r;u>4,l!==64&&(n[_++]=(a&15)<<4|l>>2,c!==64&&(n[_++]=(l&3)<<6|c));return t?_-r:n.subarray(0,_)};util$6.binary.base58.encode=function(e,t){return util$6.binary.baseN.encode(e,_base58,t)};util$6.binary.base58.decode=function(e,t){return util$6.binary.baseN.decode(e,_base58,t)};util$6.text={utf8:{},utf16:{}};util$6.text.utf8.encode=function(e,t,r){e=util$6.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var o=r,a=0;a"u"&&(r=["web","flash"]);var o,a=!1,l=null;for(var c in r){o=r[c];try{if(o==="flash"||o==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");n=e.apply(this,t),a=o==="flash"}(o==="web"||o==="both")&&(t[0]=localStorage,n=e.apply(this,t),a=!0)}catch(u){l=u}if(a)break}if(!a)throw l;return n};util$6.setItem=function(e,t,r,n,o){_callStorageFunction(_setItem,arguments,o)};util$6.getItem=function(e,t,r,n){return _callStorageFunction(_getItem,arguments,n)};util$6.removeItem=function(e,t,r,n){_callStorageFunction(_removeItem,arguments,n)};util$6.clearItems=function(e,t,r){_callStorageFunction(_clearItems,arguments,r)};util$6.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};util$6.format=function(e){for(var t=/%./g,r,n,o=0,a=[],l=0;r=t.exec(e);){n=e.substring(l,t.lastIndex-2),n.length>0&&a.push(n),l=t.lastIndex;var c=r[0][1];switch(c){case"s":case"o":o");break;case"%":a.push("%");break;default:a.push("<%"+c+"?>")}}return a.push(e.substring(l)),a.join("")};util$6.formatNumber=function(e,t,r,n){var o=e,a=isNaN(t=Math.abs(t))?2:t,l=r===void 0?",":r,c=n===void 0?".":n,u=o<0?"-":"",_=parseInt(o=Math.abs(+o||0).toFixed(a),10)+"",b=_.length>3?_.length%3:0;return u+(b?_.substr(0,b)+c:"")+_.substr(b).replace(/(\d{3})(?=\d)/g,"$1"+c)+(a?l+Math.abs(o-_).toFixed(a).slice(2):"")};util$6.formatSize=function(e){return e>=1073741824?e=util$6.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=util$6.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=util$6.formatNumber(e/1024,0)+" KiB":e=util$6.formatNumber(e,0)+" bytes",e};util$6.bytesFromIP=function(e){return e.indexOf(".")!==-1?util$6.bytesFromIPv4(e):e.indexOf(":")!==-1?util$6.bytesFromIPv6(e):null};util$6.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=util$6.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1))}t.push(a)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),u.start===0&&t.unshift(""),u.end===7&&t.push(""))}return t.join(":")};util$6.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in util$6&&!e.update)return t(null,util$6.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return util$6.cores=navigator.hardwareConcurrency,t(null,util$6.cores);if(typeof Worker>"u")return util$6.cores=1,t(null,util$6.cores);if(typeof Blob>"u")return util$6.cores=2,t(null,util$6.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(l){var c=Date.now(),u=c+4;self.postMessage({st:c,et:u})})}.toString(),")()"],{type:"application/javascript"}));n([],5,16);function n(l,c,u){if(c===0){var _=Math.floor(l.reduce(function(b,x){return b+x},0)/l.length);return util$6.cores=Math.max(1,_),URL.revokeObjectURL(r),t(null,util$6.cores)}o(u,function(b,x){l.push(a(u,x)),n(l,c-1,u)})}function o(l,c){for(var u=[],_=[],b=0;bI.st&&b.stb.st&&I.stt){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}var _getValueLength=function(e,t){var r=e.getByte();if(t--,r!==128){var n,o=r&128;if(!o)n=r;else{var a=r&127;_checkBufferLength(e,t,a),n=e.getInt(a<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};asn1$2.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),typeof e=="string"&&(e=forge$j.util.createBuffer(e));var r=e.length(),n=_fromDer(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return n};function _fromDer(e,t,r,n){var o;_checkBufferLength(e,t,2);var a=e.getByte();t--;var l=a&192,c=a&31;o=e.length();var u=_getValueLength(e,t);if(t-=o-e.length(),u!==void 0&&u>t){if(n.strict){var _=new Error("Too few bytes to read ASN.1 value.");throw _.available=e.length(),_.remaining=t,_.requested=u,_}u=t}var b,x,E=(a&32)===32;if(E)if(b=[],u===void 0)for(;;){if(_checkBufferLength(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}o=e.length(),b.push(_fromDer(e,t,r+1,n)),t-=o-e.length()}else for(;u>0;)o=e.length(),b.push(_fromDer(e,u,r+1,n)),t-=o-e.length(),u-=o-e.length();if(b===void 0&&l===asn1$2.Class.UNIVERSAL&&c===asn1$2.Type.BITSTRING&&(x=e.bytes(u)),b===void 0&&n.decodeBitStrings&&l===asn1$2.Class.UNIVERSAL&&c===asn1$2.Type.BITSTRING&&u>1){var I=e.read,k=t,T=0;if(c===asn1$2.Type.BITSTRING&&(_checkBufferLength(e,t,1),T=e.getByte(),t--),T===0)try{o=e.length();var O={strict:!0,decodeBitStrings:!0},$=_fromDer(e,t,r+1,O),D=o-e.length();t-=D,c==asn1$2.Type.BITSTRING&&D++;var N=$.tagClass;D===u&&(N===asn1$2.Class.UNIVERSAL||N===asn1$2.Class.CONTEXT_SPECIFIC)&&(b=[$])}catch{}b===void 0&&(e.read=I,t=k)}if(b===void 0){if(u===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");u=t}if(c===asn1$2.Type.BMPSTRING)for(b="";u>0;u-=2)_checkBufferLength(e,t,2),b+=String.fromCharCode(e.getInt16()),t-=2;else b=e.getBytes(u),t-=u}var H=x===void 0?null:{bitStringContents:x};return asn1$2.create(l,c,E,b,H)}asn1$2.toDer=function(e){var t=forge$j.util.createBuffer(),r=e.tagClass|e.type,n=forge$j.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=asn1$2.equals(e,e.original))),o)n.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:n.putByte(0);for(var a=0;a1&&(e.value.charCodeAt(0)===0&&(e.value.charCodeAt(1)&128)===0||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?n.putBytes(e.value.substr(1)):n.putBytes(e.value);if(t.putByte(r),n.length()<=127)t.putByte(n.length()&127);else{var l=n.length(),c="";do c+=String.fromCharCode(l&255),l=l>>>8;while(l>0);t.putByte(c.length|128);for(var a=c.length-1;a>=0;--a)t.putByte(c.charCodeAt(a))}return t.putBuffer(n),t};asn1$2.oidToDer=function(e){var t=e.split("."),r=forge$j.util.createBuffer();r.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var n,o,a,l,c=2;c>>7,n||(l|=128),o.push(l),n=!1;while(a>0);for(var u=o.length-1;u>=0;--u)r.putByte(o[u])}return r};asn1$2.derToOid=function(e){var t;typeof e=="string"&&(e=forge$j.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;)r=e.getByte(),n=n<<7,r&128?n+=r&127:(t+="."+(n+r),n=0);return t};asn1$2.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,o=parseInt(e.substr(4,2),10),a=parseInt(e.substr(6,2),10),l=parseInt(e.substr(8,2),10),c=0;if(e.length>11){var u=e.charAt(10),_=10;u!=="+"&&u!=="-"&&(c=parseInt(e.substr(10,2),10),_+=2)}if(t.setUTCFullYear(r,n,o),t.setUTCHours(a,l,c,0),_&&(u=e.charAt(_),u==="+"||u==="-")){var b=parseInt(e.substr(_+1,2),10),x=parseInt(e.substr(_+4,2),10),E=b*60+x;E*=6e4,u==="+"?t.setTime(+t-E):t.setTime(+t+E)}return t};asn1$2.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,o=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),l=parseInt(e.substr(10,2),10),c=parseInt(e.substr(12,2),10),u=0,_=0,b=!1;e.charAt(e.length-1)==="Z"&&(b=!0);var x=e.length-5,E=e.charAt(x);if(E==="+"||E==="-"){var I=parseInt(e.substr(x+1,2),10),k=parseInt(e.substr(x+4,2),10);_=I*60+k,_*=6e4,E==="+"&&(_*=-1),b=!0}return e.charAt(14)==="."&&(u=parseFloat(e.substr(14),10)*1e3),b?(t.setUTCFullYear(r,n,o),t.setUTCHours(a,l,c,u),t.setTime(+t+_)):(t.setFullYear(r,n,o),t.setHours(a,l,c,u)),t};asn1$2.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r};asn1$2.derToInteger=function(e){typeof e=="string"&&(e=forge$j.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};asn1$2.validate=function(e,t,r,n){var o=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(o=!0,t.value&&forge$j.util.isArray(t.value))for(var a=0,l=0;o&&l0&&(n+=` @@ -103,7 +103,7 @@ hooks.version="2.29.4";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min `,r};pem.decode=function(e){for(var t=[],r=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,n=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,o=/\r?\n/,a;a=r.exec(e),!!a;){var l=a[1];l==="NEW CERTIFICATE REQUEST"&&(l="CERTIFICATE REQUEST");var c={type:l,procType:null,contentDomain:null,dekInfo:null,headers:[],body:forge$b.util.decode64(a[3])};if(t.push(c),!!a[2]){for(var u=a[2].split(o),_=0;a&&_65&&l!==-1){var c=t[l];c===","?(++l,t=t.substr(0,l)+`\r `+t.substr(l)):t=t.substr(0,l)+`\r -`+c+t.substr(l+1),a=o-l-1,l=-1,++o}else(t[o]===" "||t[o]===" "||t[o]===",")&&(l=o);return t}function ltrim(e){return e.replace(/^\s+/,"")}var forge$a=forge$m,sha256$2=forge$a.sha256=forge$a.sha256||{};forge$a.md.sha256=forge$a.md.algorithms.sha256=sha256$2;sha256$2.create=function(){_initialized$2||_init$2();var e=null,t=forge$a.util.createBuffer(),r=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var o=n.messageLengthSize/4,a=0;a>>0,l>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=l[1],l[1]=l[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(o),_update$2(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var o=forge$a.util.createBuffer();o.putBytes(t.bytes());var a=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,l=a&n.blockLength-1;o.putBytes(_padding$2.substr(0,n.blockLength-l));for(var c,u,_=n.fullMessageLength[0]*8,b=0;b>>0,_+=u,o.putInt32(_>>>0),_=c>>>0;o.putInt32(_);var x={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};_update$2(x,r,o);var E=forge$a.util.createBuffer();return E.putInt32(x.h0),E.putInt32(x.h1),E.putInt32(x.h2),E.putInt32(x.h3),E.putInt32(x.h4),E.putInt32(x.h5),E.putInt32(x.h6),E.putInt32(x.h7),E},n};var _padding$2=null,_initialized$2=!1,_k$1=null;function _init$2(){_padding$2=String.fromCharCode(128),_padding$2+=forge$a.util.fillString(String.fromCharCode(0),64),_k$1=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],_initialized$2=!0}function _update$2(e,t,r){for(var n,o,a,l,c,u,_,b,x,E,I,k,T,O,$,D=r.length();D>=64;){for(_=0;_<16;++_)t[_]=r.getInt32();for(;_<64;++_)n=t[_-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,o=t[_-15],o=(o>>>7|o<<25)^(o>>>18|o<<14)^o>>>3,t[_]=n+t[_-7]+o+t[_-16]|0;for(b=e.h0,x=e.h1,E=e.h2,I=e.h3,k=e.h4,T=e.h5,O=e.h6,$=e.h7,_=0;_<64;++_)l=(k>>>6|k<<26)^(k>>>11|k<<21)^(k>>>25|k<<7),c=O^k&(T^O),a=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),u=b&x|E&(b^x),n=$+l+c+_k$1[_]+t[_],o=a+u,$=O,O=T,T=k,k=I+n>>>0,I=E,E=x,x=b,b=n+o>>>0;e.h0=e.h0+b|0,e.h1=e.h1+x|0,e.h2=e.h2+E|0,e.h3=e.h3+I|0,e.h4=e.h4+k|0,e.h5=e.h5+T|0,e.h6=e.h6+O|0,e.h7=e.h7+$|0,D-=64}}var forge$9=forge$m,_crypto$1=null;forge$9.util.isNodejs&&!forge$9.options.usePureJavaScript&&!process.versions["node-webkit"]&&(_crypto$1=require$$6);var prng=forge$9.prng=forge$9.prng||{};prng.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=new Array(32),o=0;o<32;++o)n[o]=r.create();t.pools=n,t.pool=0,t.generate=function(_,b){if(!b)return t.generateSync(_);var x=t.plugin.cipher,E=t.plugin.increment,I=t.plugin.formatKey,k=t.plugin.formatSeed,T=forge$9.util.createBuffer();t.key=null,O();function O($){if($)return b($);if(T.length()>=_)return b(null,T.getBytes(_));if(t.generated>1048575&&(t.key=null),t.key===null)return forge$9.util.nextTick(function(){a(O)});var D=x(t.key,t.seed);t.generated+=D.length,T.putBytes(D),t.key=I(x(t.key,E(t.seed))),t.seed=k(x(t.key,t.seed)),forge$9.util.setImmediate(O)}},t.generateSync=function(_){var b=t.plugin.cipher,x=t.plugin.increment,E=t.plugin.formatKey,I=t.plugin.formatSeed;t.key=null;for(var k=forge$9.util.createBuffer();k.length()<_;){t.generated>1048575&&(t.key=null),t.key===null&&l();var T=b(t.key,t.seed);t.generated+=T.length,k.putBytes(T),t.key=E(b(t.key,x(t.seed))),t.seed=I(b(t.key,t.seed))}return k.getBytes(_)};function a(_){if(t.pools[0].messageLength>=32)return c(),_();var b=32-t.pools[0].messageLength<<5;t.seedFile(b,function(x,E){if(x)return _(x);t.collect(E),c(),_()})}function l(){if(t.pools[0].messageLength>=32)return c();var _=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(_)),c()}function c(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var _=t.plugin.md.create();_.update(t.keyBytes);for(var b=1,x=0;x<32;++x)t.reseeds%b===0&&(_.update(t.pools[x].digest().getBytes()),t.pools[x].start()),b=b<<1;t.keyBytes=_.digest().getBytes(),_.start(),_.update(t.keyBytes);var E=_.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(E),t.generated=0}function u(_){var b=null,x=forge$9.util.globalScope,E=x.crypto||x.msCrypto;E&&E.getRandomValues&&(b=function(ie){return E.getRandomValues(ie)});var I=forge$9.util.createBuffer();if(b)for(;I.length()<_;){var k=Math.max(1,Math.min(_-I.length(),65536)/4),T=new Uint32Array(Math.floor(k));try{b(T);for(var O=0;O>16),D+=($&32767)<<16,D+=$>>15,D=(D&2147483647)+(D>>31),H=D&4294967295;for(var O=0;O<3;++O)N=H>>>(O<<3),N^=Math.floor(Math.random()*256),I.putByte(N&255)}return I.getBytes(_)}return _crypto$1?(t.seedFile=function(_,b){_crypto$1.randomBytes(_,function(x,E){if(x)return b(x);b(null,E.toString())})},t.seedFileSync=function(_){return _crypto$1.randomBytes(_).toString()}):(t.seedFile=function(_,b){try{b(null,u(_))}catch(x){b(x)}},t.seedFileSync=u),t.collect=function(_){for(var b=_.length,x=0;x>E&255);t.collect(x)},t.registerWorker=function(_){if(_===self)t.seedFile=function(x,E){function I(k){var T=k.data;T.forge&&T.forge.prng&&(self.removeEventListener("message",I),E(T.forge.prng.err,T.forge.prng.bytes))}self.addEventListener("message",I),self.postMessage({forge:{prng:{needed:x}}})};else{var b=function(x){var E=x.data;E.forge&&E.forge.prng&&t.seedFile(E.forge.prng.needed,function(I,k){_.postMessage({forge:{prng:{err:I,bytes:k}}})})};_.addEventListener("message",b)}},t};var forge$8=forge$m;(function(){forge$8.random&&forge$8.random.getBytes||function(e){var t={},r=new Array(4),n=forge$8.util.createBuffer();t.formatKey=function(x){var E=forge$8.util.createBuffer(x);return x=new Array(4),x[0]=E.getInt32(),x[1]=E.getInt32(),x[2]=E.getInt32(),x[3]=E.getInt32(),forge$8.aes._expandKey(x,!1)},t.formatSeed=function(x){var E=forge$8.util.createBuffer(x);return x=new Array(4),x[0]=E.getInt32(),x[1]=E.getInt32(),x[2]=E.getInt32(),x[3]=E.getInt32(),x},t.cipher=function(x,E){return forge$8.aes._updateBlock(x,E,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},t.increment=function(x){return++x[3],x},t.md=forge$8.md.sha256;function o(){var x=forge$8.prng.create(t);return x.getBytes=function(E,I){return x.generate(E,I)},x.getBytesSync=function(E){return x.generate(E)},x}var a=o(),l=null,c=forge$8.util.globalScope,u=c.crypto||c.msCrypto;if(u&&u.getRandomValues&&(l=function(x){return u.getRandomValues(x)}),!forge$8.util.isNodejs&&!l){if(a.collectInt(+new Date,32),typeof navigator<"u"){var _="";for(var b in navigator)try{typeof navigator[b]=="string"&&(_+=navigator[b])}catch{}a.collect(_),_=null}e&&(e().mousemove(function(x){a.collectInt(x.clientX,16),a.collectInt(x.clientY,16)}),e().keypress(function(x){a.collectInt(x.charCode,8)}))}if(!forge$8.random)forge$8.random=a;else for(var b in a)forge$8.random[b]=a[b];forge$8.random.createInstance=o}(typeof jQuery<"u"?jQuery:null)})();var forge$7=forge$m,piTable=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s$4=[1,2,3,5],rol=function(e,t){return e<>16-t},ror=function(e,t){return(e&65535)>>t|e<<16-t&65535};forge$7.rc2=forge$7.rc2||{};forge$7.rc2.expandKey=function(e,t){typeof e=="string"&&(e=forge$7.util.createBuffer(e)),t=t||128;var r=e,n=e.length(),o=t,a=Math.ceil(o/8),l=255>>(o&7),c;for(c=n;c<128;c++)r.putByte(piTable[r.at(c-1)+r.at(c-n)&255]);for(r.setAt(128-a,piTable[r.at(128-a)&l]),c=127-a;c>=0;c--)r.setAt(c,piTable[r.at(c+1)^r.at(c+a)]);return r};var createCipher=function(e,t,r){var n=!1,o=null,a=null,l=null,c,u,_,b,x=[];for(e=forge$7.rc2.expandKey(e,t),_=0;_<64;_++)x.push(e.getInt16Le());r?(c=function(k){for(_=0;_<4;_++)k[_]+=x[b]+(k[(_+3)%4]&k[(_+2)%4])+(~k[(_+3)%4]&k[(_+1)%4]),k[_]=rol(k[_],s$4[_]),b++},u=function(k){for(_=0;_<4;_++)k[_]+=x[k[(_+3)%4]&63]}):(c=function(k){for(_=3;_>=0;_--)k[_]=ror(k[_],s$4[_]),k[_]-=x[b]+(k[(_+3)%4]&k[(_+2)%4])+(~k[(_+3)%4]&k[(_+1)%4]),b--},u=function(k){for(_=3;_>=0;_--)k[_]-=x[k[(_+3)%4]&63]});var E=function(k){var T=[];for(_=0;_<4;_++){var O=o.getInt16Le();l!==null&&(r?O^=l.getInt16Le():l.putInt16Le(O)),T.push(O&65535)}b=r?0:63;for(var $=0;$=8;)E([[5,c],[1,u],[6,c],[1,u],[5,c]])},finish:function(k){var T=!0;if(r)if(k)T=k(8,o,!r);else{var O=o.length()===8?8:8-o.length();o.fillWithByte(O,O)}if(T&&(n=!0,I.update()),!r&&(T=o.length()===0,T))if(k)T=k(8,a,!r);else{var $=a.length(),D=a.at($-1);D>$?T=!1:a.truncate(D)}return T}},I};forge$7.rc2.startEncrypting=function(e,t,r){var n=forge$7.rc2.createEncryptionCipher(e,128);return n.start(t,r),n};forge$7.rc2.createEncryptionCipher=function(e,t){return createCipher(e,t,!0)};forge$7.rc2.startDecrypting=function(e,t,r){var n=forge$7.rc2.createDecryptionCipher(e,128);return n.start(t,r),n};forge$7.rc2.createDecryptionCipher=function(e,t){return createCipher(e,t,!1)};var forge$6=forge$m;forge$6.jsbn=forge$6.jsbn||{};var dbits;function BigInteger$2(e,t,r){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,r):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}forge$6.jsbn.BigInteger=BigInteger$2;function nbi(){return new BigInteger$2(null)}function am1(e,t,r,n,o,a){for(;--a>=0;){var l=t*this.data[e++]+r.data[n]+o;o=Math.floor(l/67108864),r.data[n++]=l&67108863}return o}function am2(e,t,r,n,o,a){for(var l=t&32767,c=t>>15;--a>=0;){var u=this.data[e]&32767,_=this.data[e++]>>15,b=c*u+_*l;u=l*u+((b&32767)<<15)+r.data[n]+(o&1073741823),o=(u>>>30)+(b>>>15)+c*_+(o>>>30),r.data[n++]=u&1073741823}return o}function am3(e,t,r,n,o,a){for(var l=t&16383,c=t>>14;--a>=0;){var u=this.data[e]&16383,_=this.data[e++]>>14,b=c*u+_*l;u=l*u+((b&16383)<<14)+r.data[n]+o,o=(u>>28)+(b>>14)+c*_,r.data[n++]=u&268435455}return o}typeof navigator>"u"?(BigInteger$2.prototype.am=am3,dbits=28):navigator.appName=="Microsoft Internet Explorer"?(BigInteger$2.prototype.am=am2,dbits=30):navigator.appName!="Netscape"?(BigInteger$2.prototype.am=am1,dbits=26):(BigInteger$2.prototype.am=am3,dbits=28);BigInteger$2.prototype.DB=dbits;BigInteger$2.prototype.DM=(1<=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function bnpFromInt(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function nbv(e){var t=nbi();return t.fromInt(e),t}function bnpFromString(e,t){var r;if(t==16)r=4;else if(t==8)r=3;else if(t==256)r=8;else if(t==2)r=1;else if(t==32)r=5;else if(t==4)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var n=e.length,o=!1,a=0;--n>=0;){var l=r==8?e[n]&255:intAt(e,n);if(l<0){e.charAt(n)=="-"&&(o=!0);continue}o=!1,a==0?this.data[this.t++]=l:a+r>this.DB?(this.data[this.t-1]|=(l&(1<>this.DB-a):this.data[this.t-1]|=l<=this.DB&&(a-=this.DB)}r==8&&(e[0]&128)!=0&&(this.s=-1,a>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t}function bnToString(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var r=(1<0)for(c>c)>0&&(o=!0,a=int2char(n));l>=0;)c>(c+=this.DB-t)):(n=this.data[l]>>(c-=t)&r,c<=0&&(c+=this.DB,--l)),n>0&&(o=!0),o&&(a+=int2char(n));return o?a:"0"}function bnNegate(){var e=nbi();return BigInteger$2.ZERO.subTo(this,e),e}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(e){var t=this.s-e.s;if(t!=0)return t;var r=this.t;if(t=r-e.t,t!=0)return this.s<0?-t:t;for(;--r>=0;)if((t=this.data[r]-e.data[r])!=0)return t;return 0}function nbits(e){var t=1,r;return(r=e>>>16)!=0&&(e=r,t+=16),(r=e>>8)!=0&&(e=r,t+=8),(r=e>>4)!=0&&(e=r,t+=4),(r=e>>2)!=0&&(e=r,t+=2),(r=e>>1)!=0&&(e=r,t+=1),t}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function bnpDRShiftTo(e,t){for(var r=e;r=0;--c)t.data[c+a+1]=this.data[c]>>n|l,l=(this.data[c]&o)<=0;--c)t.data[c]=0;t.data[a]=l,t.t=this.t+a+1,t.s=this.s,t.clamp()}function bnpRShiftTo(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,o=this.DB-n,a=(1<>n;for(var l=r+1;l>n;n>0&&(t.data[this.t-r-1]|=(this.s&a)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()}function bnpMultiplyTo(e,t){var r=this.abs(),n=e.abs(),o=r.t;for(t.t=o+n.t;--o>=0;)t.data[o]=0;for(o=0;o=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function bnpDivRemTo(e,t,r){var n=e.abs();if(!(n.t<=0)){var o=this.abs();if(o.t0?(n.lShiftTo(u,a),o.lShiftTo(u,r)):(n.copyTo(a),o.copyTo(r));var _=a.t,b=a.data[_-1];if(b!=0){var x=b*(1<1?a.data[_-2]>>this.F2:0),E=this.FV/x,I=(1<=0&&(r.data[r.t++]=1,r.subTo($,r)),BigInteger$2.ONE.dlShiftTo(_,$),$.subTo(a,a);a.t<_;)a.data[a.t++]=0;for(;--O>=0;){var D=r.data[--T]==b?this.DM:Math.floor(r.data[T]*E+(r.data[T-1]+k)*I);if((r.data[T]+=a.am(0,D,r,O,0,_))0&&r.rShiftTo(u,r),l<0&&BigInteger$2.ZERO.subTo(r,r)}}}function bnMod(e){var t=nbi();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(BigInteger$2.ZERO)>0&&e.subTo(t,t),t}function Classic(e){this.m=e}function cConvert(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function cRevert(e){return e}function cReduce(e){e.divRemTo(this.m,null,e)}function cMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function cSqrTo(e,t){e.squareTo(t),this.reduce(t)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function Montgomery(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function montRevert(e){var t=nbi();return e.copyTo(t),this.reduce(t),t}function montReduce(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function montSqrTo(e,t){e.squareTo(t),this.reduce(t)}function montMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,t){if(e>4294967295||e<1)return BigInteger$2.ONE;var r=nbi(),n=nbi(),o=t.convert(this),a=nbits(e)-1;for(o.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,o,r);else{var l=r;r=n,n=l}return t.revert(r)}function bnModPowInt(e,t){var r;return e<256||t.isEven()?r=new Classic(t):r=new Montgomery(t),this.exp(e,r)}BigInteger$2.prototype.copyTo=bnpCopyTo;BigInteger$2.prototype.fromInt=bnpFromInt;BigInteger$2.prototype.fromString=bnpFromString;BigInteger$2.prototype.clamp=bnpClamp;BigInteger$2.prototype.dlShiftTo=bnpDLShiftTo;BigInteger$2.prototype.drShiftTo=bnpDRShiftTo;BigInteger$2.prototype.lShiftTo=bnpLShiftTo;BigInteger$2.prototype.rShiftTo=bnpRShiftTo;BigInteger$2.prototype.subTo=bnpSubTo;BigInteger$2.prototype.multiplyTo=bnpMultiplyTo;BigInteger$2.prototype.squareTo=bnpSquareTo;BigInteger$2.prototype.divRemTo=bnpDivRemTo;BigInteger$2.prototype.invDigit=bnpInvDigit;BigInteger$2.prototype.isEven=bnpIsEven;BigInteger$2.prototype.exp=bnpExp;BigInteger$2.prototype.toString=bnToString;BigInteger$2.prototype.negate=bnNegate;BigInteger$2.prototype.abs=bnAbs;BigInteger$2.prototype.compareTo=bnCompareTo;BigInteger$2.prototype.bitLength=bnBitLength;BigInteger$2.prototype.mod=bnMod;BigInteger$2.prototype.modPowInt=bnModPowInt;BigInteger$2.ZERO=nbv(0);BigInteger$2.ONE=nbv(1);function bnClone(){var e=nbi();return this.copyTo(e),e}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function bnSigNum(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function bnpToRadix(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=nbv(r),o=nbi(),a=nbi(),l="";for(this.divRemTo(n,o,a);o.signum()>0;)l=(r+a.intValue()).toString(e).substr(1)+l,o.divRemTo(n,o,a);return a.intValue().toString(e)+l}function bnpFromRadix(e,t){this.fromInt(0),t==null&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),o=!1,a=0,l=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(l,0),a=0,l=0)}a>0&&(this.dMultiply(Math.pow(t,a)),this.dAddOffset(l,0)),o&&BigInteger$2.ZERO.subTo(this,this)}function bnpFromNumber(e,t,r){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(BigInteger$2.ONE.shiftLeft(e-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(BigInteger$2.ONE.shiftLeft(e-1),this);else{var n=new Array,o=e&7;n.length=(e>>3)+1,t.nextBytes(n),o>0?n[0]&=(1<0)for(r>r)!=(this.s&this.DM)>>r&&(t[o++]=n|this.s<=0;)r<8?(n=(this.data[e]&(1<>(r+=this.DB-8)):(n=this.data[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),(n&128)!=0&&(n|=-256),o==0&&(this.s&128)!=(n&128)&&++o,(o>0||n!=this.s)&&(t[o++]=n);return t}function bnEquals(e){return this.compareTo(e)==0}function bnMin(e){return this.compareTo(e)<0?this:e}function bnMax(e){return this.compareTo(e)>0?this:e}function bnpBitwiseTo(e,t,r){var n,o,a=Math.min(e.t,this.t);for(n=0;n>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function bnGetLowestSetBit(){for(var e=0;e=this.t?this.s!=0:(this.data[t]&1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()}function bnAdd(e){var t=nbi();return this.addTo(e,t),t}function bnSubtract(e){var t=nbi();return this.subTo(e,t),t}function bnMultiply(e){var t=nbi();return this.multiplyTo(e,t),t}function bnDivide(e){var t=nbi();return this.divRemTo(e,t,null),t}function bnRemainder(e){var t=nbi();return this.divRemTo(e,null,t),t}function bnDivideAndRemainder(e){var t=nbi(),r=nbi();return this.divRemTo(e,t,r),new Array(t,r)}function bnpDMultiply(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function NullExp(){}function nNop(e){return e}function nMulTo(e,t,r){e.multiplyTo(t,r)}function nSqrTo(e,t){e.squareTo(t)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(e,t,r){var n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var o;for(o=r.t-this.t;n=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t}function barrettRevert(e){return e}function barrettReduce(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function barrettSqrTo(e,t){e.squareTo(t),this.reduce(t)}function barrettMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,t){var r=e.bitLength(),n,o=nbv(1),a;if(r<=0)return o;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?a=new Classic(t):t.isEven()?a=new Barrett(t):a=new Montgomery(t);var l=new Array,c=3,u=n-1,_=(1<1){var b=nbi();for(a.sqrTo(l[1],b);c<=_;)l[c]=nbi(),a.mulTo(b,l[c-2],l[c]),c+=2}var x=e.t-1,E,I=!0,k=nbi(),T;for(r=nbits(e.data[x])-1;x>=0;){for(r>=u?E=e.data[x]>>r-u&_:(E=(e.data[x]&(1<0&&(E|=e.data[x-1]>>this.DB+r-u)),c=n;(E&1)==0;)E>>=1,--c;if((r-=c)<0&&(r+=this.DB,--x),I)l[E].copyTo(o),I=!1;else{for(;c>1;)a.sqrTo(o,k),a.sqrTo(k,o),c-=2;c>0?a.sqrTo(o,k):(T=o,o=k,k=T),a.mulTo(k,l[E],o)}for(;x>=0&&(e.data[x]&1<0&&(t.rShiftTo(a,t),r.rShiftTo(a,r));t.signum()>0;)(o=t.getLowestSetBit())>0&&t.rShiftTo(o,t),(o=r.getLowestSetBit())>0&&r.rShiftTo(o,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return a>0&&r.lShiftTo(a,r),r}function bnpModInt(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(t==0)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r}function bnModInverse(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return BigInteger$2.ZERO;for(var r=e.clone(),n=this.clone(),o=nbv(1),a=nbv(0),l=nbv(0),c=nbv(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),t?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(e,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);for(;n.isEven();)n.rShiftTo(1,n),t?((!l.isEven()||!c.isEven())&&(l.addTo(this,l),c.subTo(e,c)),l.rShiftTo(1,l)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);r.compareTo(n)>=0?(r.subTo(n,r),t&&o.subTo(l,o),a.subTo(c,a)):(n.subTo(r,n),t&&l.subTo(o,l),c.subTo(a,c))}if(n.compareTo(BigInteger$2.ONE)!=0)return BigInteger$2.ZERO;if(c.compareTo(e)>=0)return c.subtract(e);if(c.signum()<0)c.addTo(e,c);else return c;return c.signum()<0?c.add(e):c}var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var t,r=this.abs();if(r.t==1&&r.data[0]<=lowprimes[lowprimes.length-1]){for(t=0;t=0);var c=a.modPow(n,this);if(c.compareTo(BigInteger$2.ONE)!=0&&c.compareTo(t)!=0){for(var u=1;u++>>0,l>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=l[1],l[1]=l[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(o),_update$1(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var o=forge$5.util.createBuffer();o.putBytes(t.bytes());var a=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,l=a&n.blockLength-1;o.putBytes(_padding$1.substr(0,n.blockLength-l));for(var c,u,_=n.fullMessageLength[0]*8,b=0;b>>0,_+=u,o.putInt32(_>>>0),_=c>>>0;o.putInt32(_);var x={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};_update$1(x,r,o);var E=forge$5.util.createBuffer();return E.putInt32(x.h0),E.putInt32(x.h1),E.putInt32(x.h2),E.putInt32(x.h3),E.putInt32(x.h4),E},n};var _padding$1=null,_initialized$1=!1;function _init$1(){_padding$1=String.fromCharCode(128),_padding$1+=forge$5.util.fillString(String.fromCharCode(0),64),_initialized$1=!0}function _update$1(e,t,r){for(var n,o,a,l,c,u,_,b,x=r.length();x>=64;){for(o=e.h0,a=e.h1,l=e.h2,c=e.h3,u=e.h4,b=0;b<16;++b)n=r.getInt32(),t[b]=n,_=c^a&(l^c),n=(o<<5|o>>>27)+_+u+1518500249+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<20;++b)n=t[b-3]^t[b-8]^t[b-14]^t[b-16],n=n<<1|n>>>31,t[b]=n,_=c^a&(l^c),n=(o<<5|o>>>27)+_+u+1518500249+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<32;++b)n=t[b-3]^t[b-8]^t[b-14]^t[b-16],n=n<<1|n>>>31,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+1859775393+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<40;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+1859775393+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<60;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a&l|c&(a^l),n=(o<<5|o>>>27)+_+u+2400959708+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<80;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+3395469782+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;e.h0=e.h0+o|0,e.h1=e.h1+a|0,e.h2=e.h2+l|0,e.h3=e.h3+c|0,e.h4=e.h4+u|0,x-=64}}var forge$4=forge$m,pkcs1=forge$4.pkcs1=forge$4.pkcs1||{};pkcs1.encode_rsa_oaep=function(e,t,r){var n,o,a,l;typeof r=="string"?(n=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(n=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(l=r.mgf1.md)),a?a.start():a=forge$4.md.sha1.create(),l||(l=a);var c=Math.ceil(e.n.bitLength()/8),u=c-2*a.digestLength-2;if(t.length>u){var _=new Error("RSAES-OAEP input message length is too long.");throw _.length=t.length,_.maxLength=u,_}n||(n=""),a.update(n,"raw");for(var b=a.digest(),x="",E=u-t.length,I=0;I>24&255,a>>16&255,a>>8&255,a&255);r.start(),r.update(e+l),n+=r.digest().getBytes()}return n.substring(0,t)}var forge$3=forge$m;(function(){if(forge$3.prime)return;var e=forge$3.prime=forge$3.prime||{},t=forge$3.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new t(null);n.fromInt(30);var o=function(x,E){return x|E};e.generateProbablePrime=function(x,E,I){typeof E=="function"&&(I=E,E={}),E=E||{};var k=E.algorithm||"PRIMEINC";typeof k=="string"&&(k={name:k}),k.options=k.options||{};var T=E.prng||forge$3.random,O={nextBytes:function($){for(var D=T.getBytesSync($.length),N=0;N<$.length;++N)$[N]=D.charCodeAt(N)}};if(k.name==="PRIMEINC")return a(x,O,k.options,I);throw new Error("Invalid prime generation algorithm: "+k.name)};function a(x,E,I,k){return"workers"in I?u(x,E,I,k):l(x,E,I,k)}function l(x,E,I,k){var T=_(x,E),O=0,$=b(T.bitLength());"millerRabinTests"in I&&($=I.millerRabinTests);var D=10;"maxBlockTime"in I&&(D=I.maxBlockTime),c(T,x,E,O,$,D,k)}function c(x,E,I,k,T,O,$){var D=+new Date;do{if(x.bitLength()>E&&(x=_(E,I)),x.isProbablePrime(T))return $(null,x);x.dAddOffset(r[k++%8],0)}while(O<0||+new Date-D"u")return l(x,E,I,k);var T=_(x,E),O=I.workers,$=I.workLoad||100,D=$*30/8,N=I.workerScript||"forge/prime.worker.js";if(O===-1)return forge$3.util.estimateCores(function(ie,ue){ie&&(ue=2),O=ue-1,H()});H();function H(){O=Math.max(1,O);for(var ie=[],ue=0;uex&&(T=_(x,E));var he=T.toString(16);ce.target.postMessage({hex:he,workLoad:$}),T.dAddOffset(D,0)}}}}function _(x,E){var I=new t(x,E),k=x-1;return I.testBit(k)||I.bitwiseTo(t.ONE.shiftLeft(k),o,I),I.dAddOffset(31-I.mod(n).byteValue(),0),I}function b(x){return x<=100?27:x<=150?18:x<=200?15:x<=250?12:x<=300?9:x<=350?8:x<=400?7:x<=500?6:x<=600?5:x<=800?4:x<=1250?3:2}})();var forge$2=forge$m;if(typeof BigInteger$1>"u")var BigInteger$1=forge$2.jsbn.BigInteger;var _crypto=forge$2.util.isNodejs?require$$6:null,asn1$1=forge$2.asn1,util$5=forge$2.util;forge$2.pki=forge$2.pki||{};forge$2.pki.rsa=forge$2.rsa=forge$2.rsa||{};var pki$1=forge$2.pki,GCD_30_DELTA=[6,4,2,4,2,4,6,2],privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},publicKeyValidator=forge$2.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},digestInfoValidator={name:"DigestInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},emsaPkcs1v15encode=function(e){var t;if(e.algorithm in pki$1.oids)t=pki$1.oids[e.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=asn1$1.oidToDer(t).getBytes(),o=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[]),a=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[]);a.value.push(asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,n)),a.value.push(asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,""));var l=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OCTETSTRING,!1,e.digest().getBytes());return o.value.push(a),o.value.push(l),asn1$1.toDer(o).getBytes()},_modPow=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(BigInteger$1.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(BigInteger$1.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var n;do n=new BigInteger$1(forge$2.util.bytesToHex(forge$2.random.getBytes(t.n.bitLength()/8)),16);while(n.compareTo(t.n)>=0||!n.gcd(t.n).equals(BigInteger$1.ONE));e=e.multiply(n.modPow(t.e,t.n)).mod(t.n);for(var o=e.mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var l=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return l=l.multiply(n.modInverse(t.n)).mod(t.n),l};pki$1.rsa.encrypt=function(e,t,r){var n=r,o,a=Math.ceil(t.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,o=_encodePkcs1_v1_5(e,t,r)):(o=forge$2.util.createBuffer(),o.putBytes(e));for(var l=new BigInteger$1(o.toHex(),16),c=_modPow(l,t,n),u=c.toString(16),_=forge$2.util.createBuffer(),b=a-Math.ceil(u.length/2);b>0;)_.putByte(0),--b;return _.putBytes(forge$2.util.hexToBytes(u)),_.getBytes()};pki$1.rsa.decrypt=function(e,t,r,n){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var l=new BigInteger$1(forge$2.util.createBuffer(e).toHex(),16);if(l.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var c=_modPow(l,t,r),u=c.toString(16),_=forge$2.util.createBuffer(),b=o-Math.ceil(u.length/2);b>0;)_.putByte(0),--b;return _.putBytes(forge$2.util.hexToBytes(u)),n!==!1?_decodePkcs1_v1_5(_.getBytes(),t,r):_.getBytes()};pki$1.rsa.createKeyPairGenerationState=function(e,t,r){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,r=r||{};var n=r.prng||forge$2.random,o={nextBytes:function(c){for(var u=n.getBytesSync(c.length),_=0;_>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},l.e.fromInt(l.eInt);else throw new Error("Invalid key generation algorithm: "+a);return l};pki$1.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new BigInteger$1(null);r.fromInt(30);for(var n=0,o=function(x,E){return x|E},a=+new Date,l,c=0;e.keys===null&&(t<=0||cu?e.pqState=0:e.num.isProbablePrime(_getMillerRabinTests(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(GCD_30_DELTA[n++%8],0):e.pqState===2?e.pqState=e.num.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(BigInteger$1.ONE),e.q1=e.q.subtract(BigInteger$1.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(BigInteger$1.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var b=e.e.modInverse(e.phi);e.keys={privateKey:pki$1.rsa.setPrivateKey(e.n,e.e,b,e.p,e.q,b.mod(e.p1),b.mod(e.q1),e.q.modInverse(e.p)),publicKey:pki$1.rsa.setPublicKey(e.n,e.e)}}l=+new Date,c+=l-a,a=l}return e.keys!==null};pki$1.rsa.generateKeyPair=function(e,t,r,n){if(arguments.length===1?typeof e=="object"?(r=e,e=void 0):typeof e=="function"&&(n=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(n=t,t=void 0):typeof t!="number"&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},e===void 0&&(e=r.bits||2048),t===void 0&&(t=r.e||65537),!r.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(n){if(_detectNodeCrypto("generateKeyPair"))return _crypto.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(c,u,_){if(c)return n(c);n(null,{privateKey:pki$1.privateKeyFromPem(_),publicKey:pki$1.publicKeyFromPem(u)})});if(_detectSubtleCrypto("generateKey")&&_detectSubtleCrypto("exportKey"))return util$5.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_intToUint8Array(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(c){return util$5.globalScope.crypto.subtle.exportKey("pkcs8",c.privateKey)}).then(void 0,function(c){n(c)}).then(function(c){if(c){var u=pki$1.privateKeyFromAsn1(asn1$1.fromDer(forge$2.util.createBuffer(c)));n(null,{privateKey:u,publicKey:pki$1.setRsaPublicKey(u.n,u.e)})}});if(_detectSubtleMsCrypto("generateKey")&&_detectSubtleMsCrypto("exportKey")){var o=util$5.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_intToUint8Array(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);o.oncomplete=function(c){var u=c.target.result,_=util$5.globalScope.msCrypto.subtle.exportKey("pkcs8",u.privateKey);_.oncomplete=function(b){var x=b.target.result,E=pki$1.privateKeyFromAsn1(asn1$1.fromDer(forge$2.util.createBuffer(x)));n(null,{privateKey:E,publicKey:pki$1.setRsaPublicKey(E.n,E.e)})},_.onerror=function(b){n(b)}},o.onerror=function(c){n(c)};return}}else if(_detectNodeCrypto("generateKeyPairSync")){var a=_crypto.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:pki$1.privateKeyFromPem(a.privateKey),publicKey:pki$1.publicKeyFromPem(a.publicKey)}}}var l=pki$1.rsa.createKeyPairGenerationState(e,t,r);if(!n)return pki$1.rsa.stepKeyPairGenerationState(l,0),l.keys;_generateKeyPair(l,r,n)};pki$1.setRsaPublicKey=pki$1.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(n,o,a){if(typeof o=="string"?o=o.toUpperCase():o===void 0&&(o="RSAES-PKCS1-V1_5"),o==="RSAES-PKCS1-V1_5")o={encode:function(c,u,_){return _encodePkcs1_v1_5(c,u,2).getBytes()}};else if(o==="RSA-OAEP"||o==="RSAES-OAEP")o={encode:function(c,u){return forge$2.pkcs1.encode_rsa_oaep(u,c,a)}};else if(["RAW","NONE","NULL",null].indexOf(o)!==-1)o={encode:function(c){return c}};else if(typeof o=="string")throw new Error('Unsupported encryption scheme: "'+o+'".');var l=o.encode(n,r,!0);return pki$1.rsa.encrypt(l,r,!0)},r.verify=function(n,o,a,l){typeof a=="string"?a=a.toUpperCase():a===void 0&&(a="RSASSA-PKCS1-V1_5"),l===void 0&&(l={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in l||(l._parseAllDigestBytes=!0),a==="RSASSA-PKCS1-V1_5"?a={verify:function(u,_){_=_decodePkcs1_v1_5(_,r,!0);var b=asn1$1.fromDer(_,{parseAllBytes:l._parseAllDigestBytes}),x={},E=[];if(!asn1$1.validate(b,digestInfoValidator,x,E)){var I=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw I.errors=E,I}var k=asn1$1.derToOid(x.algorithmIdentifier);if(!(k===forge$2.oids.md2||k===forge$2.oids.md5||k===forge$2.oids.sha1||k===forge$2.oids.sha224||k===forge$2.oids.sha256||k===forge$2.oids.sha384||k===forge$2.oids.sha512||k===forge$2.oids["sha512-224"]||k===forge$2.oids["sha512-256"])){var I=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw I.oid=k,I}if((k===forge$2.oids.md2||k===forge$2.oids.md5)&&!("parameters"in x))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return u===x.digest}}:(a==="NONE"||a==="NULL"||a===null)&&(a={verify:function(u,_){return _=_decodePkcs1_v1_5(_,r,!0),u===_}});var c=pki$1.rsa.decrypt(o,r,!0,!1);return a.verify(n,c,r.n.bitLength())},r};pki$1.setRsaPrivateKey=pki$1.rsa.setPrivateKey=function(e,t,r,n,o,a,l,c){var u={n:e,e:t,d:r,p:n,q:o,dP:a,dQ:l,qInv:c};return u.decrypt=function(_,b,x){typeof b=="string"?b=b.toUpperCase():b===void 0&&(b="RSAES-PKCS1-V1_5");var E=pki$1.rsa.decrypt(_,u,!1,!1);if(b==="RSAES-PKCS1-V1_5")b={decode:_decodePkcs1_v1_5};else if(b==="RSA-OAEP"||b==="RSAES-OAEP")b={decode:function(I,k){return forge$2.pkcs1.decode_rsa_oaep(k,I,x)}};else if(["RAW","NONE","NULL",null].indexOf(b)!==-1)b={decode:function(I){return I}};else throw new Error('Unsupported encryption scheme: "'+b+'".');return b.decode(E,u,!1)},u.sign=function(_,b){var x=!1;typeof b=="string"&&(b=b.toUpperCase()),b===void 0||b==="RSASSA-PKCS1-V1_5"?(b={encode:emsaPkcs1v15encode},x=1):(b==="NONE"||b==="NULL"||b===null)&&(b={encode:function(){return _}},x=1);var E=b.encode(_,u.n.bitLength());return pki$1.rsa.encrypt(E,u,x)},u};pki$1.wrapRsaPrivateKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,asn1$1.integerToDer(0).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,asn1$1.oidToDer(pki$1.oids.rsaEncryption).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,"")]),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OCTETSTRING,!1,asn1$1.toDer(e).getBytes())])};pki$1.privateKeyFromAsn1=function(e){var t={},r=[];if(asn1$1.validate(e,privateKeyValidator,t,r)&&(e=asn1$1.fromDer(forge$2.util.createBuffer(t.privateKey))),t={},r=[],!asn1$1.validate(e,rsaPrivateKeyValidator,t,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var o,a,l,c,u,_,b,x;return o=forge$2.util.createBuffer(t.privateKeyModulus).toHex(),a=forge$2.util.createBuffer(t.privateKeyPublicExponent).toHex(),l=forge$2.util.createBuffer(t.privateKeyPrivateExponent).toHex(),c=forge$2.util.createBuffer(t.privateKeyPrime1).toHex(),u=forge$2.util.createBuffer(t.privateKeyPrime2).toHex(),_=forge$2.util.createBuffer(t.privateKeyExponent1).toHex(),b=forge$2.util.createBuffer(t.privateKeyExponent2).toHex(),x=forge$2.util.createBuffer(t.privateKeyCoefficient).toHex(),pki$1.setRsaPrivateKey(new BigInteger$1(o,16),new BigInteger$1(a,16),new BigInteger$1(l,16),new BigInteger$1(c,16),new BigInteger$1(u,16),new BigInteger$1(_,16),new BigInteger$1(b,16),new BigInteger$1(x,16))};pki$1.privateKeyToAsn1=pki$1.privateKeyToRSAPrivateKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,asn1$1.integerToDer(0).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.n)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.e)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.d)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.p)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.q)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.dP)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.dQ)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.qInv))])};pki$1.publicKeyFromAsn1=function(e){var t={},r=[];if(asn1$1.validate(e,publicKeyValidator,t,r)){var n=asn1$1.derToOid(t.publicKeyOid);if(n!==pki$1.oids.rsaEncryption){var o=new Error("Cannot read public key. Unknown OID.");throw o.oid=n,o}e=t.rsaPublicKey}if(r=[],!asn1$1.validate(e,rsaPublicKeyValidator,t,r)){var o=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw o.errors=r,o}var a=forge$2.util.createBuffer(t.publicKeyModulus).toHex(),l=forge$2.util.createBuffer(t.publicKeyExponent).toHex();return pki$1.setRsaPublicKey(new BigInteger$1(a,16),new BigInteger$1(l,16))};pki$1.publicKeyToAsn1=pki$1.publicKeyToSubjectPublicKeyInfo=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,asn1$1.oidToDer(pki$1.oids.rsaEncryption).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,"")]),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.BITSTRING,!1,[pki$1.publicKeyToRSAPublicKey(e)])])};pki$1.publicKeyToRSAPublicKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.n)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.e))])};function _encodePkcs1_v1_5(e,t,r){var n=forge$2.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var a=new Error("Message is too long for PKCS#1 v1.5 padding.");throw a.length=e.length,a.max=o-11,a}n.putByte(0),n.putByte(r);var l=o-3-e.length,c;if(r===0||r===1){c=r===0?0:255;for(var u=0;u0;){for(var _=0,b=forge$2.random.getBytes(l),u=0;u"u")throw new Error("Encryption block is invalid.");var u=0;if(c===0){u=o-3-n;for(var _=0;_1;){if(a.getByte()!==255){--a.read;break}++u}else if(c===2)for(u=0;a.length()>1;){if(a.getByte()===0){--a.read;break}++u}var b=a.getByte();if(b!==0||u!==o-3-a.length())throw new Error("Encryption block is invalid.");return a.getBytes()}function _generateKeyPair(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(n.prng=t.prng),o();function o(){a(e.pBits,function(c,u){if(c)return r(c);if(e.p=u,e.q!==null)return l(c,e.q);a(e.qBits,l)})}function a(c,u){forge$2.prime.generateProbablePrime(c,n,u)}function l(c,u){if(c)return r(c);if(e.q=u,e.p.compareTo(e.q)<0){var _=e.p;e.p=e.q,e.q=_}if(e.p.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.p=null,o();return}if(e.q.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.q=null,a(e.qBits,l);return}if(e.p1=e.p.subtract(BigInteger$1.ONE),e.q1=e.q.subtract(BigInteger$1.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.p=e.q=null,o();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,a(e.qBits,l);return}var b=e.e.modInverse(e.phi);e.keys={privateKey:pki$1.rsa.setPrivateKey(e.n,e.e,b,e.p,e.q,b.mod(e.p1),b.mod(e.q1),e.q.modInverse(e.p)),publicKey:pki$1.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}}function _bnToBytes(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=forge$2.util.hexToBytes(t);return r.length>1&&(r.charCodeAt(0)===0&&(r.charCodeAt(1)&128)===0||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function _getMillerRabinTests(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function _detectNodeCrypto(e){return forge$2.util.isNodejs&&typeof _crypto[e]=="function"}function _detectSubtleCrypto(e){return typeof util$5.globalScope<"u"&&typeof util$5.globalScope.crypto=="object"&&typeof util$5.globalScope.crypto.subtle=="object"&&typeof util$5.globalScope.crypto.subtle[e]=="function"}function _detectSubtleMsCrypto(e){return typeof util$5.globalScope<"u"&&typeof util$5.globalScope.msCrypto=="object"&&typeof util$5.globalScope.msCrypto.subtle=="object"&&typeof util$5.globalScope.msCrypto.subtle[e]=="function"}function _intToUint8Array(e){for(var t=forge$2.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n"u")var BigInteger=forge$1.jsbn.BigInteger;var asn1=forge$1.asn1,pki=forge$1.pki=forge$1.pki||{};pki.pbe=forge$1.pbe=forge$1.pbe||{};var oids=pki.oids,encryptedPrivateKeyValidator={name:"EncryptedPrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},PBES2AlgorithmsValidator={name:"PBES2Algorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},pkcs12PbeParamsValidator={name:"pkcs-12PbeParams",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"iterations"}]};pki.encryptPrivateKeyInfo=function(e,t,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var n=forge$1.random.getBytesSync(r.saltSize),o=r.count,a=asn1.integerToDer(o),l,c,u;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var _,b,x;switch(r.algorithm){case"aes128":l=16,_=16,b=oids["aes128-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"aes192":l=24,_=16,b=oids["aes192-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"aes256":l=32,_=16,b=oids["aes256-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"des":l=8,_=8,b=oids.desCBC,x=forge$1.des.createEncryptionCipher;break;default:var E=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw E.algorithm=r.algorithm,E}var I="hmacWith"+r.prfAlgorithm.toUpperCase(),k=prfAlgorithmToMessageDigest(I),T=forge$1.pkcs5.pbkdf2(t,n,o,l,k),O=forge$1.random.getBytesSync(_),$=x(T);$.start(O),$.update(asn1.toDer(e)),$.finish(),u=$.output.getBytes();var D=createPbkdf2Params(n,a,l,I);c=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBES2).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBKDF2).getBytes()),D]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(b).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,O)])])])}else if(r.algorithm==="3des"){l=24;var N=new forge$1.util.ByteBuffer(n),T=pki.pbe.generatePkcs12Key(t,N,1,o,l),O=pki.pbe.generatePkcs12Key(t,N,2,o,l),$=forge$1.des.createEncryptionCipher(T);$.start(O),$.update(asn1.toDer(e)),$.finish(),u=$.output.getBytes(),c=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,n),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,a.getBytes())])])}else{var E=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw E.algorithm=r.algorithm,E}var H=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[c,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,u)]);return H};pki.decryptPrivateKeyInfo=function(e,t){var r=null,n={},o=[];if(!asn1.validate(e,encryptedPrivateKeyValidator,n,o)){var a=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}var l=asn1.derToOid(n.encryptionOid),c=pki.pbe.getCipher(l,n.encryptionParams,t),u=forge$1.util.createBuffer(n.encryptedData);return c.update(u),c.finish()&&(r=asn1.fromDer(c.output)),r};pki.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:asn1.toDer(e).getBytes()};return forge$1.pem.encode(r,{maxline:t})};pki.encryptedPrivateKeyFromPem=function(e){var t=forge$1.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return asn1.fromDer(t.body)};pki.encryptRsaPrivateKey=function(e,t,r){if(r=r||{},!r.legacy){var n=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(e));return n=pki.encryptPrivateKeyInfo(n,t,r),pki.encryptedPrivateKeyToPem(n)}var o,a,l,c;switch(r.algorithm){case"aes128":o="AES-128-CBC",l=16,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"aes192":o="AES-192-CBC",l=24,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"aes256":o="AES-256-CBC",l=32,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"3des":o="DES-EDE3-CBC",l=24,a=forge$1.random.getBytesSync(8),c=forge$1.des.createEncryptionCipher;break;case"des":o="DES-CBC",l=8,a=forge$1.random.getBytesSync(8),c=forge$1.des.createEncryptionCipher;break;default:var u=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw u.algorithm=r.algorithm,u}var _=forge$1.pbe.opensslDeriveBytes(t,a.substr(0,8),l),b=c(_);b.start(a),b.update(asn1.toDer(pki.privateKeyToAsn1(e))),b.finish();var x={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:o,parameters:forge$1.util.bytesToHex(a).toUpperCase()},body:b.output.getBytes()};return forge$1.pem.encode(x)};pki.decryptRsaPrivateKey=function(e,t){var r=null,n=forge$1.pem.decode(e)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var o=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw o.headerType=o,o}if(n.procType&&n.procType.type==="ENCRYPTED"){var a,l;switch(n.dekInfo.algorithm){case"DES-CBC":a=8,l=forge$1.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,l=forge$1.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,l=forge$1.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,l=forge$1.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,l=forge$1.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,l=function(x){return forge$1.rc2.createDecryptionCipher(x,40)};break;case"RC2-64-CBC":a=8,l=function(x){return forge$1.rc2.createDecryptionCipher(x,64)};break;case"RC2-128-CBC":a=16,l=function(x){return forge$1.rc2.createDecryptionCipher(x,128)};break;default:var o=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw o.algorithm=n.dekInfo.algorithm,o}var c=forge$1.util.hexToBytes(n.dekInfo.parameters),u=forge$1.pbe.opensslDeriveBytes(t,c.substr(0,8),a),_=l(u);if(_.start(c),_.update(forge$1.util.createBuffer(n.body)),_.finish())r=_.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=pki.decryptPrivateKeyInfo(asn1.fromDer(r),t):r=asn1.fromDer(r),r!==null&&(r=pki.privateKeyFromAsn1(r)),r};pki.pbe.generatePkcs12Key=function(e,t,r,n,o,a){var l,c;if(typeof a>"u"||a===null){if(!("sha1"in forge$1.md))throw new Error('"sha1" hash algorithm unavailable.');a=forge$1.md.sha1.create()}var u=a.digestLength,_=a.blockLength,b=new forge$1.util.ByteBuffer,x=new forge$1.util.ByteBuffer;if(e!=null){for(c=0;c=0;c--)he=he>>8,he+=le.at(c)+ee.at(c),ee.setAt(c,he&255);ve.putBuffer(ee)}N=ve,b.putBuffer(ue)}return b.truncate(b.length()-o),b};pki.pbe.getCipher=function(e,t,r){switch(e){case pki.oids.pkcs5PBES2:return pki.pbe.getCipherForPBES2(e,t,r);case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:return pki.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};pki.pbe.getCipherForPBES2=function(e,t,r){var n={},o=[];if(!asn1.validate(t,PBES2AlgorithmsValidator,n,o)){var a=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}if(e=asn1.derToOid(n.kdfOid),e!==pki.oids.pkcs5PBKDF2){var a=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw a.oid=e,a.supportedOids=["pkcs5PBKDF2"],a}if(e=asn1.derToOid(n.encOid),e!==pki.oids["aes128-CBC"]&&e!==pki.oids["aes192-CBC"]&&e!==pki.oids["aes256-CBC"]&&e!==pki.oids["des-EDE3-CBC"]&&e!==pki.oids.desCBC){var a=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw a.oid=e,a.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],a}var l=n.kdfSalt,c=forge$1.util.createBuffer(n.kdfIterationCount);c=c.getInt(c.length()<<3);var u,_;switch(pki.oids[e]){case"aes128-CBC":u=16,_=forge$1.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,_=forge$1.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,_=forge$1.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,_=forge$1.des.createDecryptionCipher;break;case"desCBC":u=8,_=forge$1.des.createDecryptionCipher;break}var b=prfOidToMessageDigest(n.prfOid),x=forge$1.pkcs5.pbkdf2(r,l,c,u,b),E=n.encIv,I=_(x);return I.start(E),I};pki.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},o=[];if(!asn1.validate(t,pkcs12PbeParamsValidator,n,o)){var a=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}var l=forge$1.util.createBuffer(n.salt),c=forge$1.util.createBuffer(n.iterations);c=c.getInt(c.length()<<3);var u,_,b;switch(e){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:u=24,_=8,b=forge$1.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:u=5,_=8,b=function(T,O){var $=forge$1.rc2.createDecryptionCipher(T,40);return $.start(O,null),$};break;default:var a=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw a.oid=e,a}var x=prfOidToMessageDigest(n.prfOid),E=pki.pbe.generatePkcs12Key(r,l,1,c,u,x);x.start();var I=pki.pbe.generatePkcs12Key(r,l,2,c,_,x);return b(E,I)};pki.pbe.opensslDeriveBytes=function(e,t,r,n){if(typeof n>"u"||n===null){if(!("md5"in forge$1.md))throw new Error('"md5" hash algorithm unavailable.');n=forge$1.md.md5.create()}t===null&&(t="");for(var o=[hash(n,e+t)],a=16,l=1;a=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,H=new Uint8Array(N);$!==D;){for(var ie=k[$],ue=0,de=N-1;(ie!==0||ue>>0,H[de]=ie%c>>>0,ie=ie/c>>>0;if(ie!==0)throw new Error("Non-zero carry");O=ue,$++}for(var le=N-O;le!==N&&H[le]===0;)le++;for(var ce=u.repeat(T);le>>0,N=new Uint8Array(D);k[T];){var H=r[k.charCodeAt(T)];if(H===255)return;for(var ie=0,ue=D-1;(H!==0||ie<$)&&ue!==-1;ue--,ie++)H+=c*N[ue]>>>0,N[ue]=H%256>>>0,H=H/256>>>0;if(H!==0)throw new Error("Non-zero carry");$=ie,T++}if(k[T]!==" "){for(var de=D-$;de!==D&&N[de]===0;)de++;for(var le=new Uint8Array(O+(D-de)),ce=O;de!==D;)le[ce++]=N[de++];return le}}}function I(k){var T=E(k);if(T)return T;throw new Error(`Non-${t} character`)}return{encode:x,decodeUnsafe:E,decode:I}}var src$3=base$4,_brrp__multiformats_scope_baseX$1=src$3;const equals$1=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},fromString$2=e=>new TextEncoder().encode(e),toString$6=e=>new TextDecoder().decode(e);class Encoder$2{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class Decoder$2{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return or$3(this,t)}}class ComposedDecoder$1{constructor(t){this.decoders=t}or(t){return or$3(this,t)}decode(t){const r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$3=(e,t)=>new ComposedDecoder$1({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Codec$1{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Encoder$2(t,r,n),this.decoder=new Decoder$2(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const from$3=({name:e,prefix:t,encode:r,decode:n})=>new Codec$1(e,t,r,n),baseX$2=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=_brrp__multiformats_scope_baseX$1(r,t);return from$3({prefix:e,name:t,encode:n,decode:a=>coerce$2(o(a))})},decode$9=(e,t,r,n)=>{const o={};for(let b=0;b=8&&(c-=8,l[_++]=255&u>>c)}if(c>=r||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return l},encode$b=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<from$3({prefix:t,name:e,encode(o){return encode$b(o,n,r)},decode(o){return decode$9(o,n,r,e)}}),base10$2=baseX$2({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$3=Object.freeze(Object.defineProperty({__proto__:null,base10:base10$2},Symbol.toStringTag,{value:"Module"})),base16$2=rfc4648$3({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper$1=rfc4648$3({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$3=Object.freeze(Object.defineProperty({__proto__:null,base16:base16$2,base16upper:base16upper$1},Symbol.toStringTag,{value:"Module"})),base2$2=rfc4648$3({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$3=Object.freeze(Object.defineProperty({__proto__:null,base2:base2$2},Symbol.toStringTag,{value:"Module"})),alphabet$2=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),alphabetBytesToChars$1=alphabet$2.reduce((e,t,r)=>(e[r]=t,e),[]),alphabetCharsToBytes$1=alphabet$2.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function encode$a(e){return e.reduce((t,r)=>(t+=alphabetBytesToChars$1[r],t),"")}function decode$8(e){const t=[];for(const r of e){const n=alphabetCharsToBytes$1[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}const base256emoji$2=from$3({prefix:"\u{1F680}",name:"base256emoji",encode:encode$a,decode:decode$8}),base256emoji$3=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$2},Symbol.toStringTag,{value:"Module"})),base32$2=rfc4648$3({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$1=rfc4648$3({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$1=rfc4648$3({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$1=rfc4648$3({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$1=rfc4648$3({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$1=rfc4648$3({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$1=rfc4648$3({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$1=rfc4648$3({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$1=rfc4648$3({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$3=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$2,base32upper:base32upper$1,base32pad:base32pad$1,base32padupper:base32padupper$1,base32hex:base32hex$1,base32hexupper:base32hexupper$1,base32hexpad:base32hexpad$1,base32hexpadupper:base32hexpadupper$1,base32z:base32z$1},Symbol.toStringTag,{value:"Module"})),base36$2=baseX$2({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$1=baseX$2({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$3=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$2,base36upper:base36upper$1},Symbol.toStringTag,{value:"Module"})),base58btc$1=baseX$2({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$1=baseX$2({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$1=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$1,base58flickr:base58flickr$1},Symbol.toStringTag,{value:"Module"})),base64$4=rfc4648$3({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$1=rfc4648$3({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$1=rfc4648$3({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$1=rfc4648$3({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$5=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$4,base64pad:base64pad$1,base64url:base64url$1,base64urlpad:base64urlpad$1},Symbol.toStringTag,{value:"Module"})),base8$2=rfc4648$3({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$3=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$2},Symbol.toStringTag,{value:"Module"})),identity$6=from$3({prefix:"\0",name:"identity",encode:e=>toString$6(e),decode:e=>fromString$2(e)}),identityBase$1=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$6},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;var encode_1$1=encode$9,MSB$3=128,REST$3=127,MSBALL$1=~REST$3,INT$1=Math.pow(2,31);function encode$9(e,t,r){t=t||[],r=r||0;for(var n=r;e>=INT$1;)t[r++]=e&255|MSB$3,e/=128;for(;e&MSBALL$1;)t[r++]=e&255|MSB$3,e>>>=7;return t[r]=e|0,encode$9.bytes=r-n+1,t}var decode$7=read$2,MSB$1$1=128,REST$1$1=127;function read$2(e,n){var r=0,n=n||0,o=0,a=n,l,c=e.length;do{if(a>=c)throw read$2.bytes=0,new RangeError("Could not decode varint");l=e[a++],r+=o<28?(l&REST$1$1)<=MSB$1$1);return read$2.bytes=a-n,r}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$2=function(e){return e[_brrp_varint$1.decode(e,t),_brrp_varint$1.decode.bytes],encodeTo$1=(e,t,r=0)=>(_brrp_varint$1.encode(e,t,r),t),encodingLength$1=e=>_brrp_varint$1.encodingLength(e),create$4=(e,t)=>{const r=t.byteLength,n=encodingLength$1(e),o=n+encodingLength$1(r),a=new Uint8Array(o+r);return encodeTo$1(e,a,0),encodeTo$1(r,a,n),a.set(t,o),new Digest$1(e,r,t,a)},decode$5=e=>{const t=coerce$2(e),[r,n]=decode$6(t),[o,a]=decode$6(t.subarray(n)),l=t.subarray(n+a);if(l.byteLength!==o)throw new Error("Incorrect length");return new Digest$1(r,o,l,t)},equals=(e,t)=>{if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&equals$1(e.bytes,r.bytes)}};class Digest$1{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}const code$3=0,name$1="identity",encode$8=coerce$2,digest$1=e=>create$4(code$3,encode$8(e)),identity$4={code:code$3,name:name$1,encode:encode$8,digest:digest$1},identity$5=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$4},Symbol.toStringTag,{value:"Module"})),from$2=({name:e,code:t,encode:r})=>new Hasher$1(e,t,r);class Hasher$1{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?create$4(this.code,r):r.then(n=>create$4(this.code,n))}else throw Error("Unknown type, must be binary type")}}const sha$1=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),sha256$1=from$2({name:"sha2-256",code:18,encode:sha$1("SHA-256")}),sha512$2=from$2({name:"sha2-512",code:19,encode:sha$1("SHA-512")}),sha2$1=Object.freeze(Object.defineProperty({__proto__:null,sha256:sha256$1,sha512:sha512$2},Symbol.toStringTag,{value:"Module"})),format$3=(e,t)=>{const{bytes:r,version:n}=e;switch(n){case 0:return toStringV0(r,baseCache(e),t||base58btc$1.encoder);default:return toStringV1(r,baseCache(e),t||base32$2.encoder)}},cache$2=new WeakMap,baseCache=e=>{const t=cache$2.get(e);if(t==null){const r=new Map;return cache$2.set(e,r),r}return t};class CID{constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:t,multihash:r}=this;if(t!==DAG_PB_CODE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==SHA_256_CODE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return CID.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:r}=this.multihash,n=create$4(t,r);return CID.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return CID.equals(this,t)}static equals(t,r){const n=r;return n&&t.code===n.code&&t.version===n.version&&equals(t.multihash,n.multihash)}toString(t){return format$3(this,t)}toJSON(){return{"/":format$3(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;const r=t;if(r instanceof CID)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:a,bytes:l}=r;return new CID(n,o,a,l||encodeCID(n,o,a.bytes))}else if(r[cidSymbol]===!0){const{version:n,multihash:o,code:a}=r,l=decode$5(o);return CID.create(n,a,l)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==DAG_PB_CODE)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);return new CID(t,r,n,n.bytes)}case 1:{const o=encodeCID(t,r,n.bytes);return new CID(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return CID.create(0,DAG_PB_CODE,t)}static createV1(t,r){return CID.create(1,t,r)}static decode(t){const[r,n]=CID.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){const r=CID.inspectBytes(t),n=r.size-r.multihashSize,o=coerce$2(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const a=o.subarray(r.multihashSize-r.digestSize),l=new Digest$1(r.multihashCode,r.digestSize,a,o);return[r.version===0?CID.createV0(l):CID.createV1(r.codec,l),t.subarray(r.size)]}static inspectBytes(t){let r=0;const n=()=>{const[x,E]=decode$6(t.subarray(r));return r+=E,x};let o=n(),a=DAG_PB_CODE;if(o===18?(o=0,r=0):a=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const l=r,c=n(),u=n(),_=r+u,b=_-l;return{version:o,codec:a,multihashCode:c,digestSize:u,multihashSize:b,size:_}}static parse(t,r){const[n,o]=parseCIDtoBytes(t,r),a=CID.decode(o);if(a.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(a).set(n,t),a}}const parseCIDtoBytes=(e,t)=>{switch(e[0]){case"Q":{const r=t||base58btc$1;return[base58btc$1.prefix,r.decode(`${base58btc$1.prefix}${e}`)]}case base58btc$1.prefix:{const r=t||base58btc$1;return[base58btc$1.prefix,r.decode(e)]}case base32$2.prefix:{const r=t||base32$2;return[base32$2.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},toStringV0=(e,t,r)=>{const{prefix:n}=r;if(n!==base58btc$1.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(o==null){const a=r.encode(e).slice(1);return t.set(n,a),a}else return o},toStringV1=(e,t,r)=>{const{prefix:n}=r,o=t.get(n);if(o==null){const a=r.encode(e);return t.set(n,a),a}else return o},DAG_PB_CODE=112,SHA_256_CODE=18,encodeCID=(e,t,r)=>{const n=encodingLength$1(e),o=n+encodingLength$1(t),a=new Uint8Array(o+r.byteLength);return encodeTo$1(e,a,0),encodeTo$1(t,a,n),a.set(r,o),a},cidSymbol=Symbol.for("@ipld/js-cid/CID"),bases={...identityBase$1,...base2$3,...base8$3,...base10$3,...base16$3,...base32$3,...base36$3,...base58$1,...base64$5,...base256emoji$3};({...sha2$1,...identity$5});function createCodec$1(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const string$1=createCodec$1("utf8","u",e=>{const t=new TextDecoder("utf8");return"u"+t.decode(e)},e=>new TextEncoder().encode(e.substring(1))),ascii=createCodec$1("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);const t=allocUnsafe$2(e.length);for(let r=0;r1&&c.charAt(u)==="=";)++_;return Math.ceil(c.length*3)/4-_};for(var r=new Array(64),n=new Array(123),o=0;o<64;)n[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;t.encode=function(c,u,_){for(var b=null,x=[],E=0,I=0,k;u<_;){var T=c[u++];switch(I){case 0:x[E++]=r[T>>2],k=(T&3)<<4,I=1;break;case 1:x[E++]=r[k|T>>4],k=(T&15)<<2,I=2;break;case 2:x[E++]=r[k|T>>6],x[E++]=r[T&63],I=0;break}E>8191&&((b||(b=[])).push(String.fromCharCode.apply(String,x)),E=0)}return I&&(x[E++]=r[k],x[E++]=61,I===1&&(x[E++]=61)),b?(E&&b.push(String.fromCharCode.apply(String,x.slice(0,E))),b.join("")):String.fromCharCode.apply(String,x.slice(0,E))};var a="invalid encoding";t.decode=function(c,u,_){for(var b=_,x=0,E,I=0;I1)break;if((k=n[k])===void 0)throw Error(a);switch(x){case 0:E=k,x=1;break;case 1:u[_++]=E<<2|(k&48)>>4,E=k,x=2;break;case 2:u[_++]=(E&15)<<4|(k&60)>>2,E=k,x=3;break;case 3:u[_++]=(E&3)<<6|k,x=0;break}}if(x===1)throw Error(a);return _-b},t.test=function(c){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c)}})(base64$3);var eventemitter=EventEmitter$3;function EventEmitter$3(){this._listeners={}}EventEmitter$3.prototype.on=function(t,r,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:r,ctx:n||this}),this};EventEmitter$3.prototype.off=function(t,r){if(t===void 0)this._listeners={};else if(r===void 0)this._listeners[t]=[];else for(var n=this._listeners[t],o=0;o0?0:2147483648,a,l);else if(isNaN(o))n(2143289344,a,l);else if(o>34028234663852886e22)n((c<<31|2139095040)>>>0,a,l);else if(o<11754943508222875e-54)n((c<<31|Math.round(o/1401298464324817e-60))>>>0,a,l);else{var u=Math.floor(Math.log(o)/Math.LN2),_=Math.round(o*Math.pow(2,-u)*8388608)&8388607;n((c<<31|u+127<<23|_)>>>0,a,l)}}e.writeFloatLE=t.bind(null,writeUintLE),e.writeFloatBE=t.bind(null,writeUintBE);function r(n,o,a){var l=n(o,a),c=(l>>31)*2+1,u=l>>>23&255,_=l&8388607;return u===255?_?NaN:c*(1/0):u===0?c*1401298464324817e-60*_:c*Math.pow(2,u-150)*(_+8388608)}e.readFloatLE=r.bind(null,readUintLE),e.readFloatBE=r.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=r[7]===128;function o(u,_,b){t[0]=u,_[b]=r[0],_[b+1]=r[1],_[b+2]=r[2],_[b+3]=r[3],_[b+4]=r[4],_[b+5]=r[5],_[b+6]=r[6],_[b+7]=r[7]}function a(u,_,b){t[0]=u,_[b]=r[7],_[b+1]=r[6],_[b+2]=r[5],_[b+3]=r[4],_[b+4]=r[3],_[b+5]=r[2],_[b+6]=r[1],_[b+7]=r[0]}e.writeDoubleLE=n?o:a,e.writeDoubleBE=n?a:o;function l(u,_){return r[0]=u[_],r[1]=u[_+1],r[2]=u[_+2],r[3]=u[_+3],r[4]=u[_+4],r[5]=u[_+5],r[6]=u[_+6],r[7]=u[_+7],t[0]}function c(u,_){return r[7]=u[_],r[6]=u[_+1],r[5]=u[_+2],r[4]=u[_+3],r[3]=u[_+4],r[2]=u[_+5],r[1]=u[_+6],r[0]=u[_+7],t[0]}e.readDoubleLE=n?l:c,e.readDoubleBE=n?c:l}():function(){function t(n,o,a,l,c,u){var _=l<0?1:0;if(_&&(l=-l),l===0)n(0,c,u+o),n(1/l>0?0:2147483648,c,u+a);else if(isNaN(l))n(0,c,u+o),n(2146959360,c,u+a);else if(l>17976931348623157e292)n(0,c,u+o),n((_<<31|2146435072)>>>0,c,u+a);else{var b;if(l<22250738585072014e-324)b=l/5e-324,n(b>>>0,c,u+o),n((_<<31|b/4294967296)>>>0,c,u+a);else{var x=Math.floor(Math.log(l)/Math.LN2);x===1024&&(x=1023),b=l*Math.pow(2,-x),n(b*4503599627370496>>>0,c,u+o),n((_<<31|x+1023<<20|b*1048576&1048575)>>>0,c,u+a)}}}e.writeDoubleLE=t.bind(null,writeUintLE,0,4),e.writeDoubleBE=t.bind(null,writeUintBE,4,0);function r(n,o,a,l,c){var u=n(l,c+o),_=n(l,c+a),b=(_>>31)*2+1,x=_>>>20&2047,E=4294967296*(_&1048575)+u;return x===2047?E?NaN:b*(1/0):x===0?b*5e-324*E:b*Math.pow(2,x-1075)*(E+4503599627370496)}e.readDoubleLE=r.bind(null,readUintLE,0,4),e.readDoubleBE=r.bind(null,readUintBE,4,0)}(),e}function writeUintLE(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function writeUintBE(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=e&255}function readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}var utf8$3={};(function(e){var t=e;t.length=function(n){for(var o=0,a=0,l=0;l191&&b<224?u[_++]=(b&31)<<6|n[o++]&63:b>239&&b<365?(b=((b&7)<<18|(n[o++]&63)<<12|(n[o++]&63)<<6|n[o++]&63)-65536,u[_++]=55296+(b>>10),u[_++]=56320+(b&1023)):u[_++]=(b&15)<<12|(n[o++]&63)<<6|n[o++]&63,_>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,u)),_=0);return c?(_&&c.push(String.fromCharCode.apply(String,u.slice(0,_))),c.join("")):String.fromCharCode.apply(String,u.slice(0,_))},t.write=function(n,o,a){for(var l=a,c,u,_=0;_>6|192,o[a++]=c&63|128):(c&64512)===55296&&((u=n.charCodeAt(_+1))&64512)===56320?(c=65536+((c&1023)<<10)+(u&1023),++_,o[a++]=c>>18|240,o[a++]=c>>12&63|128,o[a++]=c>>6&63|128,o[a++]=c&63|128):(o[a++]=c>>12|224,o[a++]=c>>6&63|128,o[a++]=c&63|128);return a-l}})(utf8$3);var pool_1=pool;function pool(e,t,r){var n=r||8192,o=n>>>1,a=null,l=n;return function(u){if(u<1||u>o)return e(u);l+u>n&&(a=e(n),l=0);var _=t.call(a,l,l+=u);return l&7&&(l=(l|7)+1),_}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=t;var e=requireMinimal();function t(a,l){this.lo=a>>>0,this.hi=l>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var n=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(l){if(l===0)return r;var c=l<0;c&&(l=-l);var u=l>>>0,_=(l-u)/4294967296>>>0;return c&&(_=~_>>>0,u=~u>>>0,++u>4294967295&&(u=0,++_>4294967295&&(_=0))),new t(u,_)},t.from=function(l){if(typeof l=="number")return t.fromNumber(l);if(e.isString(l))if(e.Long)l=e.Long.fromString(l);else return t.fromNumber(parseInt(l,10));return l.low||l.high?new t(l.low>>>0,l.high>>>0):r},t.prototype.toNumber=function(l){if(!l&&this.hi>>>31){var c=~this.lo+1>>>0,u=~this.hi>>>0;return c||(u=u+1>>>0),-(c+u*4294967296)}return this.lo+this.hi*4294967296},t.prototype.toLong=function(l){return e.Long?new e.Long(this.lo|0,this.hi|0,Boolean(l)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(l)}};var o=String.prototype.charCodeAt;return t.fromHash=function(l){return l===n?r:new t((o.call(l,0)|o.call(l,1)<<8|o.call(l,2)<<16|o.call(l,3)<<24)>>>0,(o.call(l,4)|o.call(l,5)<<8|o.call(l,6)<<16|o.call(l,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var l=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^l)>>>0,this.lo=(this.lo<<1^l)>>>0,this},t.prototype.zzDecode=function(){var l=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^l)>>>0,this.hi=(this.hi>>>1^l)>>>0,this},t.prototype.length=function(){var l=this.lo,c=(this.lo>>>28|this.hi<<4)>>>0,u=this.hi>>>24;return u===0?c===0?l<16384?l<128?1:2:l<2097152?3:4:c<16384?c<128?5:6:c<2097152?7:8:u<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(e){var t=e;t.asPromise=aspromise,t.base64=base64$3,t.EventEmitter=eventemitter,t.float=float,t.inquire=inquire_1,t.utf8=utf8$3,t.pool=pool_1,t.LongBits=requireLongbits(),t.isNode=Boolean(typeof commonjsGlobal$2<"u"&&commonjsGlobal$2&&commonjsGlobal$2.process&&commonjsGlobal$2.process.versions&&commonjsGlobal$2.process.versions.node),t.global=t.isNode&&commonjsGlobal$2||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal$2,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(a){return typeof a=="number"&&isFinite(a)&&Math.floor(a)===a},t.isString=function(a){return typeof a=="string"||a instanceof String},t.isObject=function(a){return a&&typeof a=="object"},t.isset=t.isSet=function(a,l){var c=a[l];return c!=null&&a.hasOwnProperty(l)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=function(){try{var o=t.inquire("buffer").Buffer;return o.prototype.utf8Write?o:null}catch{return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(a){return typeof a=="number"?t.Buffer?t._Buffer_allocUnsafe(a):new t.Array(a):t.Buffer?t._Buffer_from(a):typeof Uint8Array>"u"?a:new Uint8Array(a)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(a){return a?t.LongBits.from(a).toHash():t.LongBits.zeroHash},t.longFromHash=function(a,l){var c=t.LongBits.fromHash(a);return t.Long?t.Long.fromBits(c.lo,c.hi,l):c.toNumber(Boolean(l))};function r(o,a,l){for(var c=Object.keys(a),u=0;u-1;--_)if(l[u[_]]===1&&this[u[_]]!==void 0&&this[u[_]]!==null)return u[_]}},t.oneOfSetter=function(a){return function(l){for(var c=0;c "+e.len)}function Reader$1(e){this.buf=e,this.pos=0,this.len=e.length}var create_array=typeof Uint8Array<"u"?function e(t){if(t instanceof Uint8Array||Array.isArray(t))return new Reader$1(t);throw Error("illegal buffer")}:function e(t){if(Array.isArray(t))return new Reader$1(t);throw Error("illegal buffer")},create$2=function e(){return util$4.Buffer?function(r){return(Reader$1.create=function(o){return util$4.Buffer.isBuffer(o)?new BufferReader$1(o):create_array(o)})(r)}:create_array};Reader$1.create=create$2();Reader$1.prototype._slice=util$4.Array.prototype.subarray||util$4.Array.prototype.slice;Reader$1.prototype.uint32=function e(){var t=4294967295;return function(){if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return t}}();Reader$1.prototype.int32=function e(){return this.uint32()|0};Reader$1.prototype.sint32=function e(){var t=this.uint32();return t>>>1^-(t&1)|0};function readLongVarint(){var e=new LongBits$1(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function e(){return this.uint32()!==0};function readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}Reader$1.prototype.fixed32=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits$1(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var t=util$4.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t};Reader$1.prototype.double=function e(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var t=util$4.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t};Reader$1.prototype.bytes=function e(){var t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw indexOutOfRange(this,t);if(this.pos+=t,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var o=util$4.Buffer;return o?o.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Reader$1.prototype.string=function e(){var t=this.bytes();return utf8$2.read(t,0,t.length)};Reader$1.prototype.skip=function e(t){if(typeof t=="number"){if(this.pos+t>this.len)throw indexOutOfRange(this,t);this.pos+=t}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this};Reader$1._configure=function(e){BufferReader$1=e,Reader$1.create=create$2(),BufferReader$1._configure();var t=util$4.Long?"toLong":"toNumber";util$4.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[t](!1)},uint64:function(){return readLongVarint.call(this)[t](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function(){return readFixed64.call(this)[t](!0)},sfixed64:function(){return readFixed64.call(this)[t](!1)}})};var reader_buffer=BufferReader,Reader=reader$2;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$3=requireMinimal();function BufferReader(e){Reader.call(this,e)}BufferReader._configure=function(){util$3.Buffer&&(BufferReader.prototype._slice=util$3.Buffer.prototype.slice)};BufferReader.prototype.string=function e(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))};BufferReader._configure();var minimalExports=requireMinimal(),writer$1=Writer$1,util$2=requireMinimal(),BufferWriter$1,LongBits=util$2.LongBits,base64$2=util$2.base64,utf8$1=util$2.utf8;function Op(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function noop$4(){}function State(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function Writer$1(){this.len=0,this.head=new Op(noop$4,0,0),this.tail=this.head,this.states=null}var create$1=function e(){return util$2.Buffer?function(){return(Writer$1.create=function(){return new BufferWriter$1})()}:function(){return new Writer$1}};Writer$1.create=create$1();Writer$1.alloc=function e(t){return new util$2.Array(t)};util$2.Array!==Array&&(Writer$1.alloc=util$2.pool(Writer$1.alloc,util$2.Array.prototype.subarray));Writer$1.prototype._push=function e(t,r,n){return this.tail=this.tail.next=new Op(t,r,n),this.len+=r,this};function writeByte(e,t,r){t[r]=e&255}function writeVarint32(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}function VarintOp(e,t){this.len=e,this.next=void 0,this.val=t}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function e(t){return this.len+=(this.tail=this.tail.next=new VarintOp((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this};Writer$1.prototype.int32=function e(t){return t<0?this._push(writeVarint64,10,LongBits.fromNumber(t)):this.uint32(t)};Writer$1.prototype.sint32=function e(t){return this.uint32((t<<1^t>>31)>>>0)};function writeVarint64(e,t,r){for(;e.hi;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}Writer$1.prototype.uint64=function e(t){var r=LongBits.from(t);return this._push(writeVarint64,r.length(),r)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function e(t){var r=LongBits.from(t).zzEncode();return this._push(writeVarint64,r.length(),r)};Writer$1.prototype.bool=function e(t){return this._push(writeByte,1,t?1:0)};function writeFixed32(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}Writer$1.prototype.fixed32=function e(t){return this._push(writeFixed32,4,t>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function e(t){var r=LongBits.from(t);return this._push(writeFixed32,4,r.lo)._push(writeFixed32,4,r.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function e(t){return this._push(util$2.float.writeFloatLE,4,t)};Writer$1.prototype.double=function e(t){return this._push(util$2.float.writeDoubleLE,8,t)};var writeBytes=util$2.Array.prototype.set?function e(t,r,n){r.set(t,n)}:function e(t,r,n){for(var o=0;o>>0;if(!r)return this._push(writeByte,1,0);if(util$2.isString(t)){var n=Writer$1.alloc(r=base64$2.length(t));base64$2.decode(t,n,0),t=n}return this.uint32(r)._push(writeBytes,r,t)};Writer$1.prototype.string=function e(t){var r=utf8$1.length(t);return r?this.uint32(r)._push(utf8$1.write,r,t):this._push(writeByte,1,0)};Writer$1.prototype.fork=function e(){return this.states=new State(this),this.head=this.tail=new Op(noop$4,0,0),this.len=0,this};Writer$1.prototype.reset=function e(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop$4,0,0),this.len=0),this};Writer$1.prototype.ldelim=function e(){var t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=r,this.len+=n),this};Writer$1.prototype.finish=function e(){for(var t=this.head.next,r=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r};Writer$1._configure=function(e){BufferWriter$1=e,Writer$1.create=create$1(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer$1;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$1=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$1._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$1.Buffer&&util$1.Buffer.prototype instanceof Uint8Array&&util$1.Buffer.prototype.set.name==="set"?function(t,r,n){r.set(t,n)}:function(t,r,n){if(t.copy)t.copy(r,n,0,t.length);else for(var o=0;o>>0;return this.uint32(r),r&&this._push(BufferWriter.writeBytesBuffer,r,t),this};function writeStringBuffer(e,t,r){e.length<40?util$1.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}BufferWriter.prototype.string=function e(t){var r=util$1.Buffer.byteLength(t);return this.uint32(r),r&&this._push(writeStringBuffer,r,t),this};BufferWriter._configure();function configure(){minimalExports._configure(),reader$2._configure(reader_buffer),writer$1._configure(writer_buffer)}configure();const methods=["uint64","int64","sint64","fixed64","sfixed64"];function patchReader(e){for(const t of methods){if(e[t]==null)continue;const r=e[t];e[t]=function(){return BigInt(r.call(this).toString())}}return e}function reader$1(e){return patchReader(new reader$2(e))}function patchWriter(e){for(const t of methods){if(e[t]==null)continue;const r=e[t];e[t]=function(n){return r.call(this,n.toString())}}return e}function writer(){return patchWriter(writer$1.create())}function decodeMessage(e,t){const r=reader$1(e instanceof Uint8Array?e:e.subarray());return t.decode(r)}function encodeMessage(e,t){const r=writer();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var CODEC_TYPES;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(CODEC_TYPES||(CODEC_TYPES={}));function createCodec(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function enumeration(e){function t(o){if(e[o.toString()]==null)throw new Error("Invalid enum value");return e[o]}const r=function(a,l){const c=t(a);l.int32(c)},n=function(a){const l=a.int32();return t(l)};return createCodec("enum",CODEC_TYPES.VARINT,r,n)}function message(e,t){return createCodec("message",CODEC_TYPES.LENGTH_DELIMITED,e,t)}var KeyType;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"})(KeyType||(KeyType={}));var __KeyTypeValues;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"})(__KeyTypeValues||(__KeyTypeValues={}));(function(e){e.codec=()=>enumeration(__KeyTypeValues)})(KeyType||(KeyType={}));var PublicKey;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),KeyType.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.Type=KeyType.codec().decode(r);break;case 2:o.Data=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PublicKey||(PublicKey={}));var PrivateKey;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),KeyType.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.Type=KeyType.codec().decode(r);break;case 2:o.Data=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PrivateKey||(PrivateKey={}));class Ed25519PublicKey{constructor(t){Ye(this,"_key");this._key=ensureKey(t,PUBLIC_KEY_BYTE_LENGTH)}async verify(t,r){return hashAndVerify$2(this._key,r,t)}marshal(){return this._key}get bytes(){return PublicKey.encode({Type:KeyType.Ed25519,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class Ed25519PrivateKey{constructor(t,r){Ye(this,"_key");Ye(this,"_publicKey");this._key=ensureKey(t,PRIVATE_KEY_BYTE_LENGTH),this._publicKey=ensureKey(r,PUBLIC_KEY_BYTE_LENGTH)}async sign(t){return hashAndSign$2(this._key,t)}get public(){return new Ed25519PublicKey(this._publicKey)}marshal(){return this._key}get bytes(){return PrivateKey.encode({Type:KeyType.Ed25519,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=identity$4.digest(this.public.bytes);return base58btc$1.encode(t.bytes).substring(1)}async export(t,r="libp2p-key"){if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function unmarshalEd25519PrivateKey(e){if(e.length>PRIVATE_KEY_BYTE_LENGTH){e=ensureKey(e,PRIVATE_KEY_BYTE_LENGTH+PUBLIC_KEY_BYTE_LENGTH);const n=e.subarray(0,PRIVATE_KEY_BYTE_LENGTH),o=e.subarray(PRIVATE_KEY_BYTE_LENGTH,e.length);return new Ed25519PrivateKey(n,o)}e=ensureKey(e,PRIVATE_KEY_BYTE_LENGTH);const t=e.subarray(0,PRIVATE_KEY_BYTE_LENGTH),r=e.subarray(PUBLIC_KEY_BYTE_LENGTH);return new Ed25519PrivateKey(t,r)}function unmarshalEd25519PublicKey(e){return e=ensureKey(e,PUBLIC_KEY_BYTE_LENGTH),new Ed25519PublicKey(e)}async function generateKeyPair$3(){const{privateKey:e,publicKey:t}=await generateKey$2();return new Ed25519PrivateKey(e,t)}async function generateKeyPairFromSeed(e){const{privateKey:t,publicKey:r}=await generateKeyFromSeed(e);return new Ed25519PrivateKey(t,r)}function ensureKey(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new CodeError(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}const Ed25519=Object.freeze(Object.defineProperty({__proto__:null,Ed25519PublicKey,Ed25519PrivateKey,unmarshalEd25519PrivateKey,unmarshalEd25519PublicKey,generateKeyPair:generateKeyPair$3,generateKeyPairFromSeed},Symbol.toStringTag,{value:"Module"}));function toString$5(e,t="utf8"){const r=BASES[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function bigIntegerToUintBase64url(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=concat$1([new Uint8Array(t-r.length),r])}return toString$5(r,"base64url")}function base64urlToBigInteger(e){const t=base64urlToBuffer(e);return new forge$m.jsbn.BigInteger(toString$5(t,"base16"),16)}function base64urlToBuffer(e,t){let r=fromString$1(e,"base64urlpad");if(t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=concat$1([new Uint8Array(t-r.length),r])}return r}const bits={"P-256":256,"P-384":384,"P-521":521},curveTypes=Object.keys(bits);curveTypes.join(" / ");async function importer(e,t){const r=base64$4.decode(e);return create$3().decrypt(r,t)}var forge=forge$m,sha512$1=forge.sha512=forge.sha512||{};forge.md.sha512=forge.md.algorithms.sha512=sha512$1;var sha384=forge.sha384=forge.sha512.sha384=forge.sha512.sha384||{};sha384.create=function(){return sha512$1.create("SHA-384")};forge.md.sha384=forge.md.algorithms.sha384=sha384;forge.sha512.sha256=forge.sha512.sha256||{create:function(){return sha512$1.create("SHA-512/256")}};forge.md["sha512/256"]=forge.md.algorithms["sha512/256"]=forge.sha512.sha256;forge.sha512.sha224=forge.sha512.sha224||{create:function(){return sha512$1.create("SHA-512/224")}};forge.md["sha512/224"]=forge.md.algorithms["sha512/224"]=forge.sha512.sha224;sha512$1.create=function(e){if(_initialized||_init(),typeof e>"u"&&(e="SHA-512"),!(e in _states))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=_states[e],r=null,n=forge.util.createBuffer(),o=new Array(80),a=0;a<80;++a)o[a]=new Array(2);var l=64;switch(e){case"SHA-384":l=48;break;case"SHA-512/256":l=32;break;case"SHA-512/224":l=28;break}var c={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:l,messageLength:0,fullMessageLength:null,messageLengthSize:16};return c.start=function(){c.messageLength=0,c.fullMessageLength=c.messageLength128=[];for(var u=c.messageLengthSize/4,_=0;_>>0,b>>>0];for(var x=c.fullMessageLength.length-1;x>=0;--x)c.fullMessageLength[x]+=b[1],b[1]=b[0]+(c.fullMessageLength[x]/4294967296>>>0),c.fullMessageLength[x]=c.fullMessageLength[x]>>>0,b[0]=b[1]/4294967296>>>0;return n.putBytes(u),_update(r,o,n),(n.read>2048||n.length()===0)&&n.compact(),c},c.digest=function(){var u=forge.util.createBuffer();u.putBytes(n.bytes());var _=c.fullMessageLength[c.fullMessageLength.length-1]+c.messageLengthSize,b=_&c.blockLength-1;u.putBytes(_padding.substr(0,c.blockLength-b));for(var x,E,I=c.fullMessageLength[0]*8,k=0;k>>0,I+=E,u.putInt32(I>>>0),I=x>>>0;u.putInt32(I);for(var T=new Array(r.length),k=0;k=128;){for(te=0;te<16;++te)t[te][0]=r.getInt32()>>>0,t[te][1]=r.getInt32()>>>0;for(;te<80;++te)se=t[te-2],ae=se[0],ge=se[1],n=((ae>>>19|ge<<13)^(ge>>>29|ae<<3)^ae>>>6)>>>0,o=((ae<<13|ge>>>19)^(ge<<3|ae>>>29)^(ae<<26|ge>>>6))>>>0,Pe=t[te-15],ae=Pe[0],ge=Pe[1],a=((ae>>>1|ge<<31)^(ae>>>8|ge<<24)^ae>>>7)>>>0,l=((ae<<31|ge>>>1)^(ae<<24|ge>>>8)^(ae<<25|ge>>>7))>>>0,Se=t[te-7],Ue=t[te-16],ge=o+Se[1]+l+Ue[1],t[te][0]=n+Se[0]+a+Ue[0]+(ge/4294967296>>>0)>>>0,t[te][1]=ge>>>0;for(T=e[0][0],O=e[0][1],$=e[1][0],D=e[1][1],N=e[2][0],H=e[2][1],ie=e[3][0],ue=e[3][1],de=e[4][0],le=e[4][1],ce=e[5][0],ve=e[5][1],ee=e[6][0],he=e[6][1],ne=e[7][0],xe=e[7][1],te=0;te<80;++te)_=((de>>>14|le<<18)^(de>>>18|le<<14)^(le>>>9|de<<23))>>>0,b=((de<<18|le>>>14)^(de<<14|le>>>18)^(le<<23|de>>>9))>>>0,x=(ee^de&(ce^ee))>>>0,E=(he^le&(ve^he))>>>0,c=((T>>>28|O<<4)^(O>>>2|T<<30)^(O>>>7|T<<25))>>>0,u=((T<<4|O>>>28)^(O<<30|T>>>2)^(O<<25|T>>>7))>>>0,I=(T&$|N&(T^$))>>>0,k=(O&D|H&(O^D))>>>0,ge=xe+b+E+_k[te][1]+t[te][1],n=ne+_+x+_k[te][0]+t[te][0]+(ge/4294967296>>>0)>>>0,o=ge>>>0,ge=u+k,a=c+I+(ge/4294967296>>>0)>>>0,l=ge>>>0,ne=ee,xe=he,ee=ce,he=ve,ce=de,ve=le,ge=ue+o,de=ie+n+(ge/4294967296>>>0)>>>0,le=ge>>>0,ie=N,ue=H,N=$,H=D,$=T,D=O,ge=o+l,T=n+a+(ge/4294967296>>>0)>>>0,O=ge>>>0;ge=e[0][1]+O,e[0][0]=e[0][0]+T+(ge/4294967296>>>0)>>>0,e[0][1]=ge>>>0,ge=e[1][1]+D,e[1][0]=e[1][0]+$+(ge/4294967296>>>0)>>>0,e[1][1]=ge>>>0,ge=e[2][1]+H,e[2][0]=e[2][0]+N+(ge/4294967296>>>0)>>>0,e[2][1]=ge>>>0,ge=e[3][1]+ue,e[3][0]=e[3][0]+ie+(ge/4294967296>>>0)>>>0,e[3][1]=ge>>>0,ge=e[4][1]+le,e[4][0]=e[4][0]+de+(ge/4294967296>>>0)>>>0,e[4][1]=ge>>>0,ge=e[5][1]+ve,e[5][0]=e[5][0]+ce+(ge/4294967296>>>0)>>>0,e[5][1]=ge>>>0,ge=e[6][1]+he,e[6][0]=e[6][0]+ee+(ge/4294967296>>>0)>>>0,e[6][1]=ge>>>0,ge=e[7][1]+xe,e[7][0]=e[7][0]+ne+(ge/4294967296>>>0)>>>0,e[7][1]=ge>>>0,Be-=128}}function randomBytes(e){if(isNaN(e)||e<=0)throw new CodeError("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return randomBytes$1(e)}function convert$1(e,t){return t.map(r=>base64urlToBigInteger(e[r]))}function jwk2priv(e){return forge$m.pki.setRsaPrivateKey(...convert$1(e,["n","e","d","p","q","dp","dq","qi"]))}function jwk2pub(e){return forge$m.pki.setRsaPublicKey(...convert$1(e,["n","e"]))}function pkcs1ToJwk(e){const t=forge$m.asn1.fromDer(toString$5(e,"ascii")),r=forge$m.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:bigIntegerToUintBase64url(r.n),e:bigIntegerToUintBase64url(r.e),d:bigIntegerToUintBase64url(r.d),p:bigIntegerToUintBase64url(r.p),q:bigIntegerToUintBase64url(r.q),dp:bigIntegerToUintBase64url(r.dP),dq:bigIntegerToUintBase64url(r.dQ),qi:bigIntegerToUintBase64url(r.qInv),alg:"RS256"}}function jwkToPkcs1(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new CodeError("JWK was missing components","ERR_INVALID_PARAMETERS");const t=forge$m.pki.privateKeyToAsn1({n:base64urlToBigInteger(e.n),e:base64urlToBigInteger(e.e),d:base64urlToBigInteger(e.d),p:base64urlToBigInteger(e.p),q:base64urlToBigInteger(e.q),dP:base64urlToBigInteger(e.dp),dQ:base64urlToBigInteger(e.dq),qInv:base64urlToBigInteger(e.qi)});return fromString$1(forge$m.asn1.toDer(t).getBytes(),"ascii")}function pkixToJwk(e){const t=forge$m.asn1.fromDer(toString$5(e,"ascii")),r=forge$m.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:bigIntegerToUintBase64url(r.n),e:bigIntegerToUintBase64url(r.e)}}function jwkToPkix(e){if(e.n==null||e.e==null)throw new CodeError("JWK was missing components","ERR_INVALID_PARAMETERS");const t=forge$m.pki.publicKeyToAsn1({n:base64urlToBigInteger(e.n),e:base64urlToBigInteger(e.e)});return fromString$1(forge$m.asn1.toDer(t).getBytes(),"ascii")}async function generateKey$1(e){const t=await webcrypto.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await exportKey(t);return{privateKey:r[0],publicKey:r[1]}}async function unmarshalPrivateKey$1(e){const r=[await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await derivePublicFromPrivate(e)],n=await exportKey({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function hashAndSign$1(e,t){const r=await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await webcrypto.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(t));return new Uint8Array(n,0,n.byteLength)}async function hashAndVerify$1(e,t,r){const n=await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return webcrypto.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r)}async function exportKey(e){if(e.privateKey==null||e.publicKey==null)throw new CodeError("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([webcrypto.get().subtle.exportKey("jwk",e.privateKey),webcrypto.get().subtle.exportKey("jwk",e.publicKey)])}async function derivePublicFromPrivate(e){return webcrypto.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function convertKey(e,t,r,n){const o=t?jwk2pub(e):jwk2priv(e),a=toString$5(Uint8Array.from(r),"ascii"),l=n(a,o);return fromString$1(l,"ascii")}function encrypt(e,t){return convertKey(e,!0,t,(r,n)=>n.encrypt(r))}function decrypt(e,t){return convertKey(e,!1,t,(r,n)=>n.decrypt(r))}function keySize(e){if(e.kty!=="RSA")throw new CodeError("invalid key type","ERR_INVALID_KEY_TYPE");if(e.n==null)throw new CodeError("invalid key modulus","ERR_INVALID_KEY_MODULUS");return fromString$1(e.n,"base64url").length*8}const MAX_KEY_SIZE=8192;class RsaPublicKey{constructor(t){Ye(this,"_key");this._key=t}async verify(t,r){return hashAndVerify$1(this._key,r,t)}marshal(){return jwkToPkix(this._key)}get bytes(){return PublicKey.encode({Type:KeyType.RSA,Data:this.marshal()}).subarray()}encrypt(t){return encrypt(this._key,t)}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class RsaPrivateKey{constructor(t,r){Ye(this,"_key");Ye(this,"_publicKey");this._key=t,this._publicKey=r}genSecret(){return randomBytes(16)}async sign(t){return hashAndSign$1(this._key,t)}get public(){if(this._publicKey==null)throw new CodeError("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new RsaPublicKey(this._publicKey)}decrypt(t){return decrypt(this._key,t)}marshal(){return jwkToPkcs1(this._key)}get bytes(){return PrivateKey.encode({Type:KeyType.RSA,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=await this.public.hash();return toString$5(t,"base58btc")}async export(t,r="pkcs-8"){if(r==="pkcs-8"){const n=new forge$m.util.ByteBuffer(this.marshal()),o=forge$m.asn1.fromDer(n),a=forge$m.pki.privateKeyFromAsn1(o),l={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return forge$m.pki.encryptRsaPrivateKey(a,t,l)}else{if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}}async function unmarshalRsaPrivateKey(e){const t=pkcs1ToJwk(e);if(keySize(t)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await unmarshalPrivateKey$1(t);return new RsaPrivateKey(r.privateKey,r.publicKey)}function unmarshalRsaPublicKey(e){const t=pkixToJwk(e);if(keySize(t)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new RsaPublicKey(t)}async function fromJwk(e){if(keySize(e)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await unmarshalPrivateKey$1(e);return new RsaPrivateKey(t.privateKey,t.publicKey)}async function generateKeyPair$2(e){if(e>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await generateKey$1(e);return new RsaPrivateKey(t.privateKey,t.publicKey)}const RSA=Object.freeze(Object.defineProperty({__proto__:null,MAX_KEY_SIZE,RsaPublicKey,RsaPrivateKey,unmarshalRsaPrivateKey,unmarshalRsaPublicKey,fromJwk,generateKeyPair:generateKeyPair$2},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(e){const t=validateBasic(e);validateObject(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=DER;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:b2n(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=DER,r=typeof e=="string"?h2b(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");const{d:o,l:a}=DER._parseInt(r.subarray(2)),{d:l,l:c}=DER._parseInt(a);if(c.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:l}},hexFromSig(e){const t=_=>Number.parseInt(_[0],16)&8?"00"+_:_,r=_=>{const b=_.toString(16);return b.length&1?`0${b}`:b},n=t(r(e.s)),o=t(r(e.r)),a=n.length/2,l=o.length/2,c=r(a),u=r(l);return`30${r(l+a+4)}02${u}${o}02${c}${n}`}},_0n=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(e){const t=validatePointOpts(e),{Fp:r}=t,n=t.toBytes||((k,T,O)=>{const $=T.toAffine();return concatBytes(Uint8Array.from([4]),r.toBytes($.x),r.toBytes($.y))}),o=t.fromBytes||(k=>{const T=k.subarray(1),O=r.fromBytes(T.subarray(0,r.BYTES)),$=r.fromBytes(T.subarray(r.BYTES,2*r.BYTES));return{x:O,y:$}});function a(k){const{a:T,b:O}=t,$=r.sqr(k),D=r.mul($,k);return r.add(r.add(D,r.mul(k,T)),O)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw new Error("bad generator point: equation left != right");function l(k){return typeof k=="bigint"&&_0nr.eql(N,r.ZERO);return D(O)&&D($)?x.ZERO:new x(O,$,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(T){const O=r.invertBatch(T.map($=>$.pz));return T.map(($,D)=>$.toAffine(O[D])).map(x.fromAffine)}static fromHex(T){const O=x.fromAffine(o(ensureBytes("pointHex",T)));return O.assertValidity(),O}static fromPrivateKey(T){return x.BASE.multiply(u(T))}_setWindowSize(T){this._WINDOW_SIZE=T,_.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:T,y:O}=this.toAffine();if(!r.isValid(T)||!r.isValid(O))throw new Error("bad point: x or y not FE");const $=r.sqr(O),D=a(T);if(!r.eql($,D))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:T}=this.toAffine();if(r.isOdd)return!r.isOdd(T);throw new Error("Field doesn't support isOdd")}equals(T){b(T);const{px:O,py:$,pz:D}=this,{px:N,py:H,pz:ie}=T,ue=r.eql(r.mul(O,ie),r.mul(N,D)),de=r.eql(r.mul($,ie),r.mul(H,D));return ue&&de}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){const{a:T,b:O}=t,$=r.mul(O,_3n),{px:D,py:N,pz:H}=this;let ie=r.ZERO,ue=r.ZERO,de=r.ZERO,le=r.mul(D,D),ce=r.mul(N,N),ve=r.mul(H,H),ee=r.mul(D,N);return ee=r.add(ee,ee),de=r.mul(D,H),de=r.add(de,de),ie=r.mul(T,de),ue=r.mul($,ve),ue=r.add(ie,ue),ie=r.sub(ce,ue),ue=r.add(ce,ue),ue=r.mul(ie,ue),ie=r.mul(ee,ie),de=r.mul($,de),ve=r.mul(T,ve),ee=r.sub(le,ve),ee=r.mul(T,ee),ee=r.add(ee,de),de=r.add(le,le),le=r.add(de,le),le=r.add(le,ve),le=r.mul(le,ee),ue=r.add(ue,le),ve=r.mul(N,H),ve=r.add(ve,ve),le=r.mul(ve,ee),ie=r.sub(ie,le),de=r.mul(ve,ce),de=r.add(de,de),de=r.add(de,de),new x(ie,ue,de)}add(T){b(T);const{px:O,py:$,pz:D}=this,{px:N,py:H,pz:ie}=T;let ue=r.ZERO,de=r.ZERO,le=r.ZERO;const ce=t.a,ve=r.mul(t.b,_3n);let ee=r.mul(O,N),he=r.mul($,H),ne=r.mul(D,ie),xe=r.add(O,$),te=r.add(N,H);xe=r.mul(xe,te),te=r.add(ee,he),xe=r.sub(xe,te),te=r.add(O,D);let ae=r.add(N,ie);return te=r.mul(te,ae),ae=r.add(ee,ne),te=r.sub(te,ae),ae=r.add($,D),ue=r.add(H,ie),ae=r.mul(ae,ue),ue=r.add(he,ne),ae=r.sub(ae,ue),le=r.mul(ce,te),ue=r.mul(ve,ne),le=r.add(ue,le),ue=r.sub(he,le),le=r.add(he,le),de=r.mul(ue,le),he=r.add(ee,ee),he=r.add(he,ee),ne=r.mul(ce,ne),te=r.mul(ve,te),he=r.add(he,ne),ne=r.sub(ee,ne),ne=r.mul(ce,ne),te=r.add(te,ne),ee=r.mul(he,te),de=r.add(de,ee),ee=r.mul(ae,te),ue=r.mul(xe,ue),ue=r.sub(ue,ee),ee=r.mul(xe,he),le=r.mul(ae,le),le=r.add(le,ee),new x(ue,de,le)}subtract(T){return this.add(T.negate())}is0(){return this.equals(x.ZERO)}wNAF(T){return I.wNAFCached(this,_,T,O=>{const $=r.invertBatch(O.map(D=>D.pz));return O.map((D,N)=>D.toAffine($[N])).map(x.fromAffine)})}multiplyUnsafe(T){const O=x.ZERO;if(T===_0n)return O;if(c(T),T===_1n$1)return this;const{endo:$}=t;if(!$)return I.unsafeLadder(this,T);let{k1neg:D,k1:N,k2neg:H,k2:ie}=$.splitScalar(T),ue=O,de=O,le=this;for(;N>_0n||ie>_0n;)N&_1n$1&&(ue=ue.add(le)),ie&_1n$1&&(de=de.add(le)),le=le.double(),N>>=_1n$1,ie>>=_1n$1;return D&&(ue=ue.negate()),H&&(de=de.negate()),de=new x(r.mul(de.px,$.beta),de.py,de.pz),ue.add(de)}multiply(T){c(T);let O=T,$,D;const{endo:N}=t;if(N){const{k1neg:H,k1:ie,k2neg:ue,k2:de}=N.splitScalar(O);let{p:le,f:ce}=this.wNAF(ie),{p:ve,f:ee}=this.wNAF(de);le=I.constTimeNegate(H,le),ve=I.constTimeNegate(ue,ve),ve=new x(r.mul(ve.px,N.beta),ve.py,ve.pz),$=le.add(ve),D=ce.add(ee)}else{const{p:H,f:ie}=this.wNAF(O);$=H,D=ie}return x.normalizeZ([$,D])[0]}multiplyAndAddUnsafe(T,O,$){const D=x.BASE,N=(ie,ue)=>ue===_0n||ue===_1n$1||!ie.equals(D)?ie.multiplyUnsafe(ue):ie.multiply(ue),H=N(this,O).add(N(T,$));return H.is0()?void 0:H}toAffine(T){const{px:O,py:$,pz:D}=this,N=this.is0();T==null&&(T=N?r.ONE:r.inv(D));const H=r.mul(O,T),ie=r.mul($,T),ue=r.mul(D,T);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(ue,r.ONE))throw new Error("invZ was invalid");return{x:H,y:ie}}isTorsionFree(){const{h:T,isTorsionFree:O}=t;if(T===_1n$1)return!0;if(O)return O(x,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:T,clearCofactor:O}=t;return T===_1n$1?this:O?O(x,this):this.multiplyUnsafe(t.h)}toRawBytes(T=!0){return this.assertValidity(),n(x,this,T)}toHex(T=!0){return bytesToHex(this.toRawBytes(T))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);const E=t.nBitLength,I=wNAF(x,t.endo?Math.ceil(E/2):E);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:u,weierstrassEquation:a,isWithinCurveOrder:l}}function validateOpts(e){const t=validateBasic(e);return validateObject(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function weierstrass(e){const t=validateOpts(e),{Fp:r,n}=t,o=r.BYTES+1,a=2*r.BYTES+1;function l(te){return _0nbytesToHex(numberToBytesBE(te,t.nByteLength));function k(te){const ae=n>>_1n$1;return te>ae}function T(te){return k(te)?c(-te):te}const O=(te,ae,ge)=>bytesToNumberBE(te.slice(ae,ge));class ${constructor(ae,ge,se){this.r=ae,this.s=ge,this.recovery=se,this.assertValidity()}static fromCompact(ae){const ge=t.nByteLength;return ae=ensureBytes("compactSignature",ae,ge*2),new $(O(ae,0,ge),O(ae,ge,2*ge))}static fromDER(ae){const{r:ge,s:se}=DER.toSig(ensureBytes("DER",ae));return new $(ge,se)}assertValidity(){if(!E(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!E(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(ae){return new $(this.r,this.s,ae)}recoverPublicKey(ae){const{r:ge,s:se,recovery:Se}=this,Pe=de(ensureBytes("msgHash",ae));if(Se==null||![0,1,2,3].includes(Se))throw new Error("recovery id invalid");const Ue=Se===2||Se===3?ge+t.n:ge;if(Ue>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const Be=(Se&1)===0?"02":"03",fe=_.fromHex(Be+I(Ue)),ye=u(Ue),Ce=c(-Pe*ye),Le=c(se*ye),Fe=_.BASE.multiplyAndAddUnsafe(fe,Ce,Le);if(!Fe)throw new Error("point at infinify");return Fe.assertValidity(),Fe}hasHighS(){return k(this.s)}normalizeS(){return this.hasHighS()?new $(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return I(this.r)+I(this.s)}}const D={isValidPrivateKey(te){try{return b(te),!0}catch{return!1}},normPrivateKeyToScalar:b,randomPrivateKey:()=>{const te=getMinHashLength(t.n);return mapHashToField(t.randomBytes(te),t.n)},precompute(te=8,ae=_.BASE){return ae._setWindowSize(te),ae.multiply(BigInt(3)),ae}};function N(te,ae=!0){return _.fromPrivateKey(te).toRawBytes(ae)}function H(te){const ae=te instanceof Uint8Array,ge=typeof te=="string",se=(ae||ge)&&te.length;return ae?se===o||se===a:ge?se===2*o||se===2*a:te instanceof _}function ie(te,ae,ge=!0){if(H(te))throw new Error("first arg must be private key");if(!H(ae))throw new Error("second arg must be public key");return _.fromHex(ae).multiply(b(te)).toRawBytes(ge)}const ue=t.bits2int||function(te){const ae=bytesToNumberBE(te),ge=te.length*8-t.nBitLength;return ge>0?ae>>BigInt(ge):ae},de=t.bits2int_modN||function(te){return c(ue(te))},le=bitMask(t.nBitLength);function ce(te){if(typeof te!="bigint")throw new Error("bigint expected");if(!(_0n<=te&&tebe in ge))throw new Error("sign() legacy options not supported");const{hash:se,randomBytes:Se}=t;let{lowS:Pe,prehash:Ue,extraEntropy:Be}=ge;Pe==null&&(Pe=!0),te=ensureBytes("msgHash",te),Ue&&(te=ensureBytes("prehashed msgHash",se(te)));const fe=de(te),ye=b(ae),Ce=[ce(ye),ce(fe)];if(Be!=null){const be=Be===!0?Se(r.BYTES):Be;Ce.push(ensureBytes("extraEntropy",be))}const Le=concatBytes(...Ce),Fe=fe;function Oe(be){const Re=ue(be);if(!E(Re))return;const Ie=u(Re),we=_.BASE.multiply(Re).toAffine(),oe=c(we.x);if(oe===_0n)return;const pe=c(Ie*c(Fe+oe*ye));if(pe===_0n)return;let ke=(we.x===oe?0:2)|Number(we.y&_1n$1),Ne=pe;return Pe&&k(pe)&&(Ne=T(pe),ke^=1),new $(oe,Ne,ke)}return{seed:Le,k2sig:Oe}}const ee={lowS:t.lowS,prehash:!1},he={lowS:t.lowS,prehash:!1};function ne(te,ae,ge=ee){const{seed:se,k2sig:Se}=ve(te,ae,ge),Pe=t;return createHmacDrbg(Pe.hash.outputLen,Pe.nByteLength,Pe.hmac)(se,Se)}_.BASE._setWindowSize(8);function xe(te,ae,ge,se=he){const Se=te;if(ae=ensureBytes("msgHash",ae),ge=ensureBytes("publicKey",ge),"strict"in se)throw new Error("options.strict was renamed to lowS");const{lowS:Pe,prehash:Ue}=se;let Be,fe;try{if(typeof Se=="string"||Se instanceof Uint8Array)try{Be=$.fromDER(Se)}catch(we){if(!(we instanceof DER.Err))throw we;Be=$.fromCompact(Se)}else if(typeof Se=="object"&&typeof Se.r=="bigint"&&typeof Se.s=="bigint"){const{r:we,s:oe}=Se;Be=new $(we,oe)}else throw new Error("PARSE");fe=_.fromHex(ge)}catch(we){if(we.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(Pe&&Be.hasHighS())return!1;Ue&&(ae=t.hash(ae));const{r:ye,s:Ce}=Be,Le=de(ae),Fe=u(Ce),Oe=c(Le*Fe),be=c(ye*Fe),Re=_.BASE.multiplyAndAddUnsafe(fe,Oe,be)?.toAffine();return Re?c(Re.x)===ye:!1}return{CURVE:t,getPublicKey:N,getSharedSecret:ie,sign:ne,verify:xe,ProjectivePoint:_,Signature:$,utils:D}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(e){return{hash:e,hmac:(t,...r)=>hmac$1(e,t,concatBytes$1(...r)),randomBytes:randomBytes$1}}function createCurve(e,t){const r=n=>weierstrass({...e,...getHash(n)});return Object.freeze({...r(t),create:r})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(e,t)=>(e+t/_2n)/t;function sqrtMod(e){const t=secp256k1P,r=BigInt(3),n=BigInt(6),o=BigInt(11),a=BigInt(22),l=BigInt(23),c=BigInt(44),u=BigInt(88),_=e*e*e%t,b=_*_*e%t,x=pow2(b,r,t)*b%t,E=pow2(x,r,t)*b%t,I=pow2(E,_2n,t)*_%t,k=pow2(I,o,t)*I%t,T=pow2(k,a,t)*k%t,O=pow2(T,c,t)*T%t,$=pow2(O,u,t)*O%t,D=pow2($,c,t)*T%t,N=pow2(D,r,t)*b%t,H=pow2(N,l,t)*k%t,ie=pow2(H,n,t)*_%t,ue=pow2(ie,_2n,t);if(!Fp.eql(Fp.sqr(ue),e))throw new Error("Cannot find square root");return ue}const Fp=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=secp256k1N,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,l=BigInt("0x100000000000000000000000000000000"),c=divNearest(a*e,t),u=divNearest(-n*e,t);let _=mod(e-c*r-u*o,t),b=mod(-c*n-u*a,t);const x=_>l,E=b>l;if(x&&(_=t-_),E&&(b=t-b),_>l||b>l)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:x,k1:_,k2neg:E,k2:b}}}},sha256$3);BigInt(0);secp256k1.ProjectivePoint;function generateKey(){return secp256k1.utils.randomPrivateKey()}async function hashAndSign(e,t){const{digest:r}=await sha256$1.digest(t);try{return secp256k1.sign(r,e).toDERRawBytes()}catch(n){throw new CodeError(String(n),"ERR_INVALID_INPUT")}}async function hashAndVerify(e,t,r){try{const{digest:n}=await sha256$1.digest(r);return secp256k1.verify(t,n,e)}catch(n){throw new CodeError(String(n),"ERR_INVALID_INPUT")}}function compressPublicKey(e){return secp256k1.ProjectivePoint.fromHex(e).toRawBytes(!0)}function validatePrivateKey(e){try{secp256k1.getPublicKey(e,!0)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PRIVATE_KEY")}}function validatePublicKey(e){try{secp256k1.ProjectivePoint.fromHex(e)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PUBLIC_KEY")}}function computePublicKey(e){try{return secp256k1.getPublicKey(e,!0)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PRIVATE_KEY")}}class Secp256k1PublicKey{constructor(t){Ye(this,"_key");validatePublicKey(t),this._key=t}async verify(t,r){return hashAndVerify(this._key,r,t)}marshal(){return compressPublicKey(this._key)}get bytes(){return PublicKey.encode({Type:KeyType.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class Secp256k1PrivateKey{constructor(t,r){Ye(this,"_key");Ye(this,"_publicKey");this._key=t,this._publicKey=r??computePublicKey(t),validatePrivateKey(this._key),validatePublicKey(this._publicKey)}async sign(t){return hashAndSign(this._key,t)}get public(){return new Secp256k1PublicKey(this._publicKey)}marshal(){return this._key}get bytes(){return PrivateKey.encode({Type:KeyType.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=await this.public.hash();return toString$5(t,"base58btc")}async export(t,r="libp2p-key"){if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function unmarshalSecp256k1PrivateKey(e){return new Secp256k1PrivateKey(e)}function unmarshalSecp256k1PublicKey(e){return new Secp256k1PublicKey(e)}async function generateKeyPair$1(){const e=generateKey();return new Secp256k1PrivateKey(e)}const Secp256k1=Object.freeze(Object.defineProperty({__proto__:null,Secp256k1PublicKey,Secp256k1PrivateKey,unmarshalSecp256k1PrivateKey,unmarshalSecp256k1PublicKey,generateKeyPair:generateKeyPair$1},Symbol.toStringTag,{value:"Module"})),supportedKeys={rsa:RSA,ed25519:Ed25519,secp256k1:Secp256k1};function unsupportedKey(e){const t=Object.keys(supportedKeys).join(" / ");return new CodeError(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function typeToKey(e){if(e=e.toLowerCase(),e==="rsa"||e==="ed25519"||e==="secp256k1")return supportedKeys[e];throw unsupportedKey(e)}async function generateKeyPair(e,t){return typeToKey(e).generateKeyPair(t??2048)}function unmarshalPublicKey(e){const t=PublicKey.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case KeyType.RSA:return supportedKeys.rsa.unmarshalRsaPublicKey(r);case KeyType.Ed25519:return supportedKeys.ed25519.unmarshalEd25519PublicKey(r);case KeyType.Secp256k1:return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw unsupportedKey(t.Type??"unknown")}}function marshalPublicKey(e,t){return t=(t??"rsa").toLowerCase(),typeToKey(t),e.bytes}async function unmarshalPrivateKey(e){const t=PrivateKey.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case KeyType.RSA:return supportedKeys.rsa.unmarshalRsaPrivateKey(r);case KeyType.Ed25519:return supportedKeys.ed25519.unmarshalEd25519PrivateKey(r);case KeyType.Secp256k1:return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw unsupportedKey(t.Type??"RSA")}}function marshalPrivateKey(e,t){return t=(t??"rsa").toLowerCase(),typeToKey(t),e.bytes}async function importKey(e,t){try{const o=await importer(e,t);return await unmarshalPrivateKey(o)}catch{}const r=forge$m.pki.decryptRsaPrivateKey(e,t);if(r===null)throw new CodeError("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=forge$m.asn1.toDer(forge$m.pki.privateKeyToAsn1(r));return n=fromString$1(n.getBytes(),"ascii"),supportedKeys.rsa.unmarshalRsaPrivateKey(n)}const symbol$3=Symbol.for("@libp2p/peer-id");function isPeerId(e){return e!=null&&Boolean(e[symbol$3])}const inspect$1=Symbol.for("nodejs.util.inspect.custom"),baseDecoder=Object.values(bases).map(e=>e.decoder).reduce((e,t)=>e.or(t),bases.identity.decoder),LIBP2P_KEY_CODE=114,MARSHALLED_ED225519_PUBLIC_KEY_LENGTH=36,MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH=37;var Zl;class PeerIdImpl{constructor(t){Ye(this,"type");Ye(this,"multihash");Ye(this,"privateKey");Ye(this,"publicKey");Ye(this,"string");Ye(this,Zl,!0);this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}toString(){return this.string==null&&(this.string=base58btc$1.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return CID.createV1(LIBP2P_KEY_CODE,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t instanceof Uint8Array)return equals$2(this.multihash.bytes,t);if(typeof t=="string")return peerIdFromString(t).equals(this);if(t?.multihash?.bytes!=null)return equals$2(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[(Zl=symbol$3,inspect$1)](){return`PeerId(${this.toString()})`}}class RSAPeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"RSA"});Ye(this,"type","RSA");Ye(this,"publicKey");this.publicKey=r.publicKey}}class Ed25519PeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"Ed25519"});Ye(this,"type","Ed25519");Ye(this,"publicKey");this.publicKey=r.multihash.digest}}class Secp256k1PeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"secp256k1"});Ye(this,"type","secp256k1");Ye(this,"publicKey");this.publicKey=r.multihash.digest}}function peerIdFromPeerId(e){if(e.type==="RSA")return new RSAPeerIdImpl(e);if(e.type==="Ed25519")return new Ed25519PeerIdImpl(e);if(e.type==="secp256k1")return new Secp256k1PeerIdImpl(e);throw new CodeError("Not a PeerId","ERR_INVALID_PARAMETERS")}function peerIdFromString(e,t){if(e.charAt(0)==="1"||e.charAt(0)==="Q"){const r=decode$5(base58btc$1.decode(`z${e}`));return e.startsWith("12D")?new Ed25519PeerIdImpl({multihash:r}):e.startsWith("16U")?new Secp256k1PeerIdImpl({multihash:r}):new RSAPeerIdImpl({multihash:r})}return peerIdFromBytes(baseDecoder.decode(e))}function peerIdFromBytes(e){try{const t=decode$5(e);if(t.code===identity$4.code){if(t.digest.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH)return new Ed25519PeerIdImpl({multihash:t});if(t.digest.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH)return new Secp256k1PeerIdImpl({multihash:t})}if(t.code===sha256$1.code)return new RSAPeerIdImpl({multihash:t})}catch{return peerIdFromCID(CID.decode(e))}throw new Error("Supplied PeerID CID is invalid")}function peerIdFromCID(e){if(e==null||e.multihash==null||e.version==null||e.version===1&&e.code!==LIBP2P_KEY_CODE)throw new Error("Supplied PeerID CID is invalid");const t=e.multihash;if(t.code===sha256$1.code)return new RSAPeerIdImpl({multihash:e.multihash});if(t.code===identity$4.code){if(t.digest.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH)return new Ed25519PeerIdImpl({multihash:e.multihash});if(t.digest.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH)return new Secp256k1PeerIdImpl({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function peerIdFromKeys(e,t){return e.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH?new Ed25519PeerIdImpl({multihash:create$4(identity$4.code,e),privateKey:t}):e.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH?new Secp256k1PeerIdImpl({multihash:create$4(identity$4.code,e),privateKey:t}):new RSAPeerIdImpl({multihash:await sha256$1.digest(e),publicKey:e,privateKey:t})}var NoiseExtensions;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const a of r.webtransportCerthashes)n.uint32(10),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={webtransportCerthashes:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.webtransportCerthashes.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(NoiseExtensions||(NoiseExtensions={}));var NoiseHandshakePayload;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),(o.writeDefaults===!0||r.identityKey!=null&&r.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(r.identityKey??new Uint8Array(0))),(o.writeDefaults===!0||r.identitySig!=null&&r.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(r.identitySig??new Uint8Array(0))),r.extensions!=null&&(n.uint32(34),NoiseExtensions.codec().encode(r.extensions,n,{writeDefaults:!1})),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.identityKey=r.bytes();break;case 2:o.identitySig=r.bytes();break;case 4:o.extensions=NoiseExtensions.codec().decode(r,r.uint32());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(NoiseHandshakePayload||(NoiseHandshakePayload={}));async function getPayload(e,t,r){const n=await signPayload(e,getHandshakePayload(t));if(e.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return createHandshakePayload(e.publicKey,n,r)}function createHandshakePayload(e,t,r){return NoiseHandshakePayload.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function signPayload(e,t){if(e.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await unmarshalPrivateKey(e.privateKey)).sign(t)}async function getPeerIdFromPayload(e){return peerIdFromKeys(e.identityKey)}function decodePayload(e){return NoiseHandshakePayload.decode(e)}function getHandshakePayload(e){const t=fromString$1("noise-libp2p-static-key:");return concat$1([t,e],t.length+e.length)}async function verifySignedPayload(e,t,r){const n=await peerIdFromKeys(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);const o=getHandshakePayload(e);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(t.identitySig==null)throw new Error("Signature was missing from message");if(!await unmarshalPublicKey(n.publicKey).verify(o,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function isValidPublicKey(e){return!(!(e instanceof Uint8Array)||e.length!==32)}var browser$7={exports:{}},ms$4,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms$4;hasRequiredMs=1;var e=1e3,t=e*60,r=t*60,n=r*24,o=n*7,a=n*365.25;ms$4=function(b,x){x=x||{};var E=typeof b;if(E==="string"&&b.length>0)return l(b);if(E==="number"&&isFinite(b))return x.long?u(b):c(b);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(b))};function l(b){if(b=String(b),!(b.length>100)){var x=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(b);if(!!x){var E=parseFloat(x[1]),I=(x[2]||"ms").toLowerCase();switch(I){case"years":case"year":case"yrs":case"yr":case"y":return E*a;case"weeks":case"week":case"w":return E*o;case"days":case"day":case"d":return E*n;case"hours":case"hour":case"hrs":case"hr":case"h":return E*r;case"minutes":case"minute":case"mins":case"min":case"m":return E*t;case"seconds":case"second":case"secs":case"sec":case"s":return E*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}}}function c(b){var x=Math.abs(b);return x>=n?Math.round(b/n)+"d":x>=r?Math.round(b/r)+"h":x>=t?Math.round(b/t)+"m":x>=e?Math.round(b/e)+"s":b+"ms"}function u(b){var x=Math.abs(b);return x>=n?_(b,x,n,"day"):x>=r?_(b,x,r,"hour"):x>=t?_(b,x,t,"minute"):x>=e?_(b,x,e,"second"):b+" ms"}function _(b,x,E,I){var k=x>=E*1.5;return Math.round(b/E)+" "+I+(k?"s":"")}return ms$4}function setup(e){r.debug=r,r.default=r,r.coerce=u,r.disable=a,r.enable=o,r.enabled=l,r.humanize=requireMs(),r.destroy=_,Object.keys(e).forEach(b=>{r[b]=e[b]}),r.names=[],r.skips=[],r.formatters={};function t(b){let x=0;for(let E=0;E{if(ue==="%%")return"%";H++;const le=r.formatters[de];if(typeof le=="function"){const ce=O[H];ue=le.call($,ce),O.splice(H,1),H--}return ue}),r.formatArgs.call($,O),($.log||r.log).apply($,O)}return T.namespace=b,T.useColors=r.useColors(),T.color=r.selectColor(b),T.extend=n,T.destroy=r.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>E!==null?E:(I!==r.namespaces&&(I=r.namespaces,k=r.enabled(b)),k),set:O=>{E=O}}),typeof r.init=="function"&&r.init(T),T}function n(b,x){const E=r(this.namespace+(typeof x>"u"?":":x)+b);return E.log=this.log,E}function o(b){r.save(b),r.namespaces=b,r.names=[],r.skips=[];let x;const E=(typeof b=="string"?b:"").split(/[\s,]+/),I=E.length;for(x=0;x"-"+x)].join(",");return r.enable(""),b}function l(b){if(b[b.length-1]==="*")return!0;let x,E;for(x=0,E=r.skips.length;x{let u=!1;return()=>{u||(u=!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`."))}})(),t.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"];function r(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const _="color: "+this.color;u.splice(1,0,_,"color: inherit");let b=0,x=0;u[0].replace(/%[a-zA-Z%]/g,E=>{E!=="%%"&&(b++,E==="%c"&&(x=b))}),u.splice(x,0,_)}t.log=console.debug||console.log||(()=>{});function o(u){try{u?t.storage.setItem("debug",u):t.storage.removeItem("debug")}catch{}}function a(){let u;try{u=t.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}function l(){try{return localStorage}catch{}}e.exports=common(t);const{formatters:c}=e.exports;c.j=function(u){try{return JSON.stringify(u)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}}})(browser$7,browser$7.exports);const debug$9=browser$7.exports;debug$9.formatters.b=e=>e==null?"undefined":base58btc$1.baseEncode(e);debug$9.formatters.t=e=>e==null?"undefined":base32$2.baseEncode(e);debug$9.formatters.m=e=>e==null?"undefined":base64$4.baseEncode(e);debug$9.formatters.p=e=>e==null?"undefined":e.toString();debug$9.formatters.c=e=>e==null?"undefined":e.toString();debug$9.formatters.k=e=>e==null?"undefined":e.toString();debug$9.formatters.a=e=>e==null?"undefined":e.toString();function createDisabledLogger(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}function logger(e){let t=createDisabledLogger(`${e}:trace`);return debug$9.enabled(`${e}:trace`)&&debug$9.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(t=debug$9(`${e}:trace`)),Object.assign(debug$9(e),{error:debug$9(`${e}:error`),trace:t})}const log$B=logger("libp2p:noise");let keyLogger;DUMP_SESSION_KEYS?keyLogger=log$B:keyLogger=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function logLocalStaticKeys(e){keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${toString$5(e.publicKey,"hex")}`),keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${toString$5(e.privateKey,"hex")}`)}function logLocalEphemeralKeys(e){e?(keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${toString$5(e.publicKey,"hex")}`),keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${toString$5(e.privateKey,"hex")}`)):keyLogger("Missing local ephemeral keys.")}function logRemoteStaticKey(e){keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${toString$5(e,"hex")}`)}function logRemoteEphemeralKey(e){keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${toString$5(e,"hex")}`)}function logCipherState(e){e.cs1&&e.cs2?(keyLogger(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${toString$5(e.cs1.k,"hex")}`),keyLogger(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${toString$5(e.cs2.k,"hex")}`)):keyLogger("Missing cipher state.")}const MIN_NONCE=0,MAX_NONCE=4294967295,ERR_MAX_NONCE="Cipherstate has reached maximum n, a new handshake must be performed";class Nonce{constructor(t=MIN_NONCE){Ye(this,"n");Ye(this,"bytes");Ye(this,"view");this.n=t,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>MAX_NONCE)throw new Error(ERR_MAX_NONCE)}}class AbstractHandshake{constructor(t){Ye(this,"crypto");this.crypto=t}encryptWithAd(t,r,n){const o=this.encrypt(t.k,t.n,r,n);return t.n.increment(),o}decryptWithAd(t,r,n,o){const{plaintext:a,valid:l}=this.decrypt(t.k,t.n,r,n,o);return l&&t.n.increment(),{plaintext:a,valid:l}}hasKey(t){return!this.isEmptyKey(t.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(t){const r=this.createEmptyKey();return equals$2(r,t)}encrypt(t,r,n,o){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(o,r.getBytes(),n,t)}encryptAndHash(t,r){let n;return this.hasKey(t.cs)?n=this.encryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,n),n}decrypt(t,r,n,o,a){r.assertValue();const l=this.crypto.chaCha20Poly1305Decrypt(o,r.getBytes(),n,t,a);return l?{plaintext:l,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(t,r){let n,o=!0;return this.hasKey(t.cs)?{plaintext:n,valid:o}=this.decryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,r),{plaintext:n,valid:o}}dh(t,r){try{const n=this.crypto.generateX25519SharedKey(t,r);return n.length===32?n:n.subarray(0,32)}catch(n){const o=n;return log$B.error(o),new Uint8Array(32)}}mixHash(t,r){t.h=this.getHash(t.h,r)}getHash(t,r){return this.crypto.hashSHA256(concat$1([t,r],t.length+r.length))}mixKey(t,r){const[n,o]=this.crypto.getHKDF(t.ck,r);t.cs=this.initializeKey(o),t.ck=n}initializeKey(t){return{k:t,n:new Nonce}}initializeSymmetric(t){const r=fromString$1(t,"utf-8"),n=this.hashProtocolName(r),o=n,a=this.createEmptyKey();return{cs:this.initializeKey(a),ck:o,h:n}}hashProtocolName(t){if(t.length<=32){const r=new Uint8Array(32);return r.set(t),r}else return this.getHash(t,new Uint8Array(0))}split(t){const[r,n]=this.crypto.getHKDF(t.ck,new Uint8Array(0)),o=this.initializeKey(r),a=this.initializeKey(n);return{cs1:o,cs2:a}}writeMessageRegular(t,r){const n=this.encryptWithAd(t,new Uint8Array(0),r),o=this.createEmptyKey(),a=new Uint8Array(0);return{ne:o,ns:a,ciphertext:n}}readMessageRegular(t,r){return this.decryptWithAd(t,new Uint8Array(0),r.ciphertext)}}class XX extends AbstractHandshake{initializeInitiator(t,r,n,o){const a="Noise_XX_25519_ChaChaPoly_SHA256",l=this.initializeSymmetric(a);this.mixHash(l,t);const c=new Uint8Array(32);return{ss:l,s:r,rs:n,psk:o,re:c}}initializeResponder(t,r,n,o){const a="Noise_XX_25519_ChaChaPoly_SHA256",l=this.initializeSymmetric(a);this.mixHash(l,t);const c=new Uint8Array(32);return{ss:l,s:r,rs:n,psk:o,re:c}}writeMessageA(t,r,n){const o=new Uint8Array(0);n!==void 0?t.e=n:t.e=this.crypto.generateX25519KeyPair();const a=t.e.publicKey;this.mixHash(t.ss,a);const l=this.encryptAndHash(t.ss,r);return{ne:a,ns:o,ciphertext:l}}writeMessageB(t,r){t.e=this.crypto.generateX25519KeyPair();const n=t.e.publicKey;this.mixHash(t.ss,n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));const o=t.s.publicKey,a=this.encryptAndHash(t.ss,o);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));const l=this.encryptAndHash(t.ss,r);return{ne:n,ns:a,ciphertext:l}}writeMessageC(t,r){const n=t.s.publicKey,o=this.encryptAndHash(t.ss,n);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));const a=this.encryptAndHash(t.ss,r),c={ne:this.createEmptyKey(),ns:o,ciphertext:a},{cs1:u,cs2:_}=this.split(t.ss);return{h:t.ss.h,messageBuffer:c,cs1:u,cs2:_}}readMessageA(t,r){return isValidPublicKey(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),this.decryptAndHash(t.ss,r.ciphertext)}readMessageB(t,r){if(isValidPublicKey(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));const{plaintext:n,valid:o}=this.decryptAndHash(t.ss,r.ns);o&&isValidPublicKey(n)&&(t.rs=n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));const{plaintext:a,valid:l}=this.decryptAndHash(t.ss,r.ciphertext);return{plaintext:a,valid:o&&l}}readMessageC(t,r){const{plaintext:n,valid:o}=this.decryptAndHash(t.ss,r.ns);if(o&&isValidPublicKey(n)&&(t.rs=n),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));const{plaintext:a,valid:l}=this.decryptAndHash(t.ss,r.ciphertext),{cs1:c,cs2:u}=this.split(t.ss);return{h:t.ss.h,plaintext:a,valid:o&&l,cs1:c,cs2:u}}initSession(t,r,n){const o=this.createEmptyKey(),a=new Uint8Array(32);let l;return t?l=this.initializeInitiator(r,n,a,o):l=this.initializeResponder(r,n,a,o),{hs:l,i:t,mc:0}}sendMessage(t,r,n){let o;if(t.mc===0)o=this.writeMessageA(t.hs,r,n);else if(t.mc===1)o=this.writeMessageB(t.hs,r);else if(t.mc===2){const{h:a,messageBuffer:l,cs1:c,cs2:u}=this.writeMessageC(t.hs,r);o=l,t.h=a,t.cs1=c,t.cs2=u}else if(t.mc>2)if(t.i){if(!t.cs1)throw new Error("CS1 (cipher state) is not defined");o=this.writeMessageRegular(t.cs1,r)}else{if(!t.cs2)throw new Error("CS2 (cipher state) is not defined");o=this.writeMessageRegular(t.cs2,r)}else throw new Error("Session invalid.");return t.mc++,o}recvMessage(t,r){let n=new Uint8Array(0),o=!1;if(t.mc===0)({plaintext:n,valid:o}=this.readMessageA(t.hs,r));else if(t.mc===1)({plaintext:n,valid:o}=this.readMessageB(t.hs,r));else if(t.mc===2){const{h:a,plaintext:l,valid:c,cs1:u,cs2:_}=this.readMessageC(t.hs,r);n=l,o=c,t.h=a,t.cs1=u,t.cs2=_}return t.mc++,{plaintext:n,valid:o}}}class XXHandshake{constructor(t,r,n,o,a,l,c,u){Ye(this,"isInitiator");Ye(this,"session");Ye(this,"remotePeer");Ye(this,"remoteExtensions",{webtransportCerthashes:[]});Ye(this,"payload");Ye(this,"connection");Ye(this,"xx");Ye(this,"staticKeypair");Ye(this,"prologue");this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=a,this.connection=l,c&&(this.remotePeer=c),this.xx=u??new XX(o),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(logLocalStaticKeys(this.session.hs.s),this.isInitiator){log$B.trace("Stage 0 - Initiator starting to send first message.");const t=this.xx.sendMessage(this.session,new Uint8Array(0));await this.connection.write(encode0(t)),log$B.trace("Stage 0 - Initiator finished sending first message."),logLocalEphemeralKeys(this.session.hs.e)}else{log$B.trace("Stage 0 - Responder waiting to receive first message...");const t=decode0((await this.connection.read()).subarray()),{valid:r}=this.xx.recvMessage(this.session,t);if(!r)throw new InvalidCryptoExchangeError("xx handshake stage 0 validation fail");log$B.trace("Stage 0 - Responder received first message."),logRemoteEphemeralKey(this.session.hs.re)}}async exchange(){if(this.isInitiator){log$B.trace("Stage 1 - Initiator waiting to receive first message from responder...");const t=decode1((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new InvalidCryptoExchangeError("xx handshake stage 1 validation fail");log$B.trace("Stage 1 - Initiator received the message."),logRemoteEphemeralKey(this.session.hs.re),logRemoteStaticKey(this.session.hs.rs),log$B.trace("Initiator going to check remote's signature...");try{const o=decodePayload(r);this.remotePeer=this.remotePeer||await getPeerIdFromPayload(o),await verifySignedPayload(this.session.hs.rs,o,this.remotePeer),this.setRemoteNoiseExtension(o.extensions)}catch(o){const a=o;throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${a.message}`)}log$B.trace("All good with the signature!")}else{log$B.trace("Stage 1 - Responder sending out first message with signed payload and static key.");const t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(encode1(t)),log$B.trace("Stage 1 - Responder sent the second handshake message with signed payload."),logLocalEphemeralKeys(this.session.hs.e)}}async finish(){if(this.isInitiator){log$B.trace("Stage 2 - Initiator sending third handshake message.");const t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(encode2(t)),log$B.trace("Stage 2 - Initiator sent message with signed payload.")}else{log$B.trace("Stage 2 - Responder waiting for third handshake message...");const t=decode2((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new InvalidCryptoExchangeError("xx handshake stage 2 validation fail");log$B.trace("Stage 2 - Responder received the message, finished handshake.");try{const o=decodePayload(r);this.remotePeer=this.remotePeer||await getPeerIdFromPayload(o),await verifySignedPayload(this.session.hs.rs,o,this.remotePeer),this.setRemoteNoiseExtension(o.extensions)}catch(o){const a=o;throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${a.message}`)}}logCipherState(this.session)}encrypt(t,r){const n=this.getCS(r);return this.xx.encryptWithAd(n,new Uint8Array(0),t)}decrypt(t,r,n){const o=this.getCS(r,!1);return this.xx.decryptWithAd(o,new Uint8Array(0),t,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(t,r=!0){if(!t.cs1||!t.cs2)throw new InvalidCryptoExchangeError("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?t.cs1:t.cs2:r?t.cs2:t.cs1}setRemoteNoiseExtension(t){t&&(this.remoteExtensions=t)}}function registerMetrics(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}class Noise{constructor(t={}){Ye(this,"protocol","/noise");Ye(this,"crypto");Ye(this,"prologue");Ye(this,"staticKeys");Ye(this,"extensions");Ye(this,"metrics");const{staticNoiseKey:r,extensions:n,crypto:o,prologueBytes:a,metrics:l}=t;this.crypto=o??pureJsCrypto,this.extensions=n,this.metrics=l?registerMetrics(l):void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=a??new Uint8Array(0)}async secureOutbound(t,r,n){const o=lpStream(r,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),a=await this.performHandshake({connection:o,isInitiator:!0,localPeer:t,remotePeer:n});return{conn:await this.createSecureConnection(o,a),remoteExtensions:a.remoteExtensions,remotePeer:a.remotePeer}}async secureInbound(t,r,n){const o=lpStream(r,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),a=await this.performHandshake({connection:o,isInitiator:!1,localPeer:t,remotePeer:n});return{conn:await this.createSecureConnection(o,a),remotePeer:a.remotePeer,remoteExtensions:a.remoteExtensions}}async performHandshake(t){const r=await getPayload(t.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(t,r)}async performXXHandshake(t,r){const{isInitiator:n,remotePeer:o,connection:a}=t,l=new XXHandshake(n,r,this.prologue,this.crypto,this.staticKeys,a,o);try{await l.propose(),await l.exchange(),await l.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){if(this.metrics?.xxHandshakeErrors.increment(),c instanceof Error)throw c.message=`Error occurred during XX handshake: ${c.message}`,c}return l}async createSecureConnection(t,r){const[n,o]=duplexPair(),a=t.unwrap();return await pipe(n,encryptStream(r,this.metrics),a,l=>decode$a(l,{lengthDecoder:uint16BEDecode}),decryptStream(r,this.metrics),n),o}}function noise(e={}){return()=>new Noise(e)}var jr;class EventEmitter$2 extends EventTarget{constructor(){super(...arguments);_r(this,jr,new Map)}listenerCount(r){const n=Jt(this,jr).get(r);return n==null?0:n.length}addEventListener(r,n,o){super.addEventListener(r,n,o);let a=Jt(this,jr).get(r);a==null&&(a=[],Jt(this,jr).set(r,a)),a.push({callback:n,once:(o!==!0&&o!==!1&&o?.once)??!1})}removeEventListener(r,n,o){super.removeEventListener(r.toString(),n??null,o);let a=Jt(this,jr).get(r);a!=null&&(a=a.filter(({callback:l})=>l!==n),Jt(this,jr).set(r,a))}dispatchEvent(r){const n=super.dispatchEvent(r);let o=Jt(this,jr).get(r.type);return o==null||(o=o.filter(({once:a})=>!a),Jt(this,jr).set(r.type,o)),n}safeDispatchEvent(r,n){return this.dispatchEvent(new CustomEvent$1(r,n))}}jr=new WeakMap;class CustomEventPolyfill extends Event{constructor(r,n){super(r,n);Ye(this,"detail");this.detail=n?.detail}}const CustomEvent$1=globalThis.CustomEvent??CustomEventPolyfill,peerDiscovery=Symbol.for("@libp2p/peer-discovery");class Parser{constructor(){Ye(this,"index",0);Ye(this,"input","")}new(t){return this.index=0,this.input=t,this}readAtomically(t){const r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){const r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{const r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let a=0,l=0;const c=this.peekChar();if(c===void 0)return;const u=c==="0",_=2**(8*o)-1;for(;;){const b=this.readAtomically(()=>{const x=this.readChar();if(x===void 0)return;const E=Number.parseInt(x,t);if(!Number.isNaN(E))return E});if(b===void 0)break;if(a*=t,a+=b,a>_||(l+=1,r!==void 0&&l>r))return}if(l!==0)return!n&&u&&l>1?void 0:a})}readIPv4Addr(){return this.readAtomically(()=>{const t=new Uint8Array(4);for(let r=0;rthis.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){const t=r=>{for(let n=0;nthis.readIPv4Addr());if(l!==void 0)return r[o]=l[0],r[o+1]=l[1],r[o+2]=l[2],r[o+3]=l[3],[o+4,!0]}const a=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(a===void 0)return[o,!1];r[o]=a>>8,r[o+1]=a&255}return[r.length,!1]};return this.readAtomically(()=>{const r=new Uint8Array(16),[n,o]=t(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;const a=new Uint8Array(14),l=16-(n+2),[c]=t(a.subarray(0,l));return r.set(a.subarray(0,c),16-c),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}const MAX_IPV6_LENGTH=45,MAX_IPV4_LENGTH=15,parser$4=new Parser;function parseIPv4(e){if(!(e.length>MAX_IPV4_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPv4Addr())}function parseIPv6(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>MAX_IPV6_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPv6Addr())}function parseIP(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>MAX_IPV6_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPAddr())}function isIPv4(e){return Boolean(parseIPv4(e))}function isIPv6(e){return Boolean(parseIPv6(e))}function isIP(e){return Boolean(parseIP(e))}const isV4=isIPv4,isV6=isIPv6,toBytes=function(e){let t=0;if(e=e.toString().trim(),isV4(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach(n=>{r[t++]=parseInt(n,10)&255}),r}if(isV6(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)a.push("0");r.splice.apply(r,a)}const o=new Uint8Array(t+16);for(n=0;n>8&255,o[t++]=a&255}return o}throw new Error("invalid ip address")},toString$4=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(r===4){const o=[];for(let a=0;a{const t=createProtocol(...e);codes$8[t.code]=t,names$3[t.name]=t});function createProtocol(e,t,r,n,o){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(o)}}function getProtocol(e){if(typeof e=="number"){if(codes$8[e]!=null)return codes$8[e];throw new Error(`no protocol with code: ${e}`)}else if(typeof e=="string"){if(names$3[e]!=null)return names$3[e];throw new Error(`no protocol with name: ${e}`)}throw new Error(`invalid protocol id type: ${typeof e}`)}getProtocol("ip4");getProtocol("ip6");getProtocol("ipcidr");function convertToString(e,t){switch(getProtocol(e).code){case 4:case 41:return bytes2ip(t);case 42:return bytes2str(t);case 6:case 273:case 33:case 132:return bytes2port(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return bytes2str(t);case 421:return bytes2mh(t);case 444:return bytes2onion(t);case 445:return bytes2onion(t);case 466:return bytes2mb(t);default:return toString$5(t,"base16")}}function convertToBytes(e,t){switch(getProtocol(e).code){case 4:return ip2bytes(t);case 41:return ip2bytes(t);case 42:return str2bytes(t);case 6:case 273:case 33:case 132:return port2bytes(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return str2bytes(t);case 421:return mh2bytes(t);case 444:return onion2bytes(t);case 445:return onion32bytes(t);case 466:return mb2bytes(t);default:return fromString$1(t,"base16")}}const decoders=Object.values(bases).map(e=>e.decoder),anybaseDecoder=function(){let e=decoders[0].or(decoders[1]);return decoders.slice(2).forEach(t=>e=e.or(t)),e}();function ip2bytes(e){if(!isIP(e))throw new Error("invalid ip address");return toBytes(e)}function bytes2ip(e){const t=toString$4(e,0,e.length);if(t==null)throw new Error("ipBuff is required");if(!isIP(t))throw new Error("invalid ip address");return t}function port2bytes(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function bytes2port(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function str2bytes(e){const t=fromString$1(e),r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function bytes2str(e){const t=decode$b(e);if(e=e.slice(encodingLength$2(t)),e.length!==t)throw new Error("inconsistent lengths");return toString$5(e)}function mh2bytes(e){let t;e[0]==="Q"||e[0]==="1"?t=decode$5(base58btc$1.decode(`z${e}`)).bytes:t=CID.parse(e).multihash.bytes;const r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function mb2bytes(e){const t=anybaseDecoder.decode(e),r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function bytes2mb(e){const t=decode$b(e),r=e.slice(encodingLength$2(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+toString$5(r,"base64url")}function bytes2mh(e){const t=decode$b(e),r=e.slice(encodingLength$2(t));if(r.length!==t)throw new Error("inconsistent lengths");return toString$5(r,"base58btc")}function onion2bytes(e){const t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=base32$2.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=port2bytes(n);return concat$1([r,o],r.length+o.length)}function onion32bytes(e){const t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=base32$2.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=port2bytes(n);return concat$1([r,o],r.length+o.length)}function bytes2onion(e){const t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=toString$5(t,"base32"),o=bytes2port(r);return`${n}:${o}`}function stringToMultiaddrParts(e){e=cleanPath(e);const t=[],r=[];let n=null;const o=e.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let a=0;a=o.length)throw ParseError("invalid address: "+e);if(c.path===!0){n=cleanPath(o.slice(a).join("/")),t.push([c.code,convertToBytes(c.code,n)]),r.push([c.code,n]);break}const u=convertToBytes(c.code,o[a]);t.push([c.code,u]),r.push([c.code,convertToString(c.code,u)])}return{string:stringTuplesToString(r),bytes:tuplesToBytes(t),tuples:t,stringTuples:r,path:n}}function bytesToMultiaddrParts(e){const t=[],r=[];let n=null,o=0;for(;oe.length)throw ParseError("Invalid address Uint8Array: "+toString$5(e,"base16"));t.push([a,_]);const b=convertToString(a,_);if(r.push([a,b]),c.path===!0){n=b;break}}return{bytes:Uint8Array.from(e),string:stringTuplesToString(r),tuples:t,stringTuples:r,path:n}}function stringTuplesToString(e){const t=[];return e.map(r=>{const n=getProtocol(r[0]);return t.push(n.name),r.length>1&&r[1]!=null&&t.push(r[1]),null}),cleanPath(t.join("/"))}function tuplesToBytes(e){return concat$1(e.map(t=>{const r=getProtocol(t[0]);let n=Uint8Array.from(encode$d(r.code));return t.length>1&&t[1]!=null&&(n=concat$1([n,t[1]])),n}))}function sizeForAddr(e,t){if(e.size>0)return e.size/8;if(e.size===0)return 0;{const r=decode$b(t instanceof Uint8Array?t:Uint8Array.from(t));return r+encodingLength$2(r)}}function cleanPath(e){return"/"+e.trim().split("/").filter(t=>t).join("/")}function ParseError(e){return new Error("Error parsing address: "+e)}const inspect=Symbol.for("nodejs.util.inspect.custom"),DNS_CODES=[getProtocol("dns").code,getProtocol("dns4").code,getProtocol("dns6").code,getProtocol("dnsaddr").code],resolvers=new Map,symbol$2=Symbol.for("@multiformats/js-multiaddr/multiaddr");function isMultiaddr(e){return Boolean(e?.[symbol$2])}var vi,xn,Ji,es,Ql;const Kn=class{constructor(t){Ye(this,"bytes");_r(this,vi,void 0);_r(this,xn,void 0);_r(this,Ji,void 0);_r(this,es,void 0);Ye(this,Ql,!0);t==null&&(t="");let r;if(t instanceof Uint8Array)r=bytesToMultiaddrParts(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);r=stringToMultiaddrParts(t)}else if(isMultiaddr(t))r=bytesToMultiaddrParts(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,wn(this,vi,r.string),wn(this,xn,r.tuples),wn(this,Ji,r.stringTuples),wn(this,es,r.path)}toString(){return Jt(this,vi)}toJSON(){return this.toString()}toOptions(){let t,r,n,o,a="";const l=getProtocol("tcp"),c=getProtocol("udp"),u=getProtocol("ip4"),_=getProtocol("ip6"),b=getProtocol("dns6"),x=getProtocol("ip6zone");for(const[I,k]of this.stringTuples())I===x.code&&(a=`%${k??""}`),DNS_CODES.includes(I)&&(r=l.name,o=443,n=`${k??""}${a}`,t=I===b.code?6:4),(I===l.code||I===c.code)&&(r=getProtocol(I).name,o=parseInt(k??"")),(I===u.code||I===_.code)&&(r=getProtocol(I).name,n=`${k??""}${a}`,t=I===_.code?6:4);if(t==null||r==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:r,port:o}}protos(){return Jt(this,xn).map(([t])=>Object.assign({},getProtocol(t)))}protoCodes(){return Jt(this,xn).map(([t])=>t)}protoNames(){return Jt(this,xn).map(([t])=>getProtocol(t).name)}tuples(){return Jt(this,xn)}stringTuples(){return Jt(this,Ji)}encapsulate(t){return t=new Kn(t),new Kn(this.toString()+t.toString())}decapsulate(t){const r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new Kn(n.slice(0,o))}decapsulateCode(t){const r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===t)return new Kn(tuplesToBytes(r.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===names$3.p2p.code&&t.push([n,o]),n===names$3["p2p-circuit"].code&&(t=[])});const r=t.pop();if(r?.[1]!=null){const n=r[1];return n[0]==="Q"||n[0]==="1"?toString$5(base58btc$1.decode(`z${n}`),"base58btc"):toString$5(CID.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return Jt(this,es)}equals(t){return equals$2(this.bytes,t.bytes)}async resolve(t){const r=this.protos().find(a=>a.resolvable);if(r==null)return[this];const n=resolvers.get(r.name);if(n==null)throw new CodeError(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(a=>new Kn(a))}nodeAddress(){const t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){const r=(t??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[(Ql=symbol$2,inspect)](){return`Multiaddr(${Jt(this,vi)})`}};let DefaultMultiaddr=Kn;vi=new WeakMap,xn=new WeakMap,Ji=new WeakMap,es=new WeakMap;function multiaddr(e){return new DefaultMultiaddr(e)}const DNS4=base$3("dns4"),DNS6=base$3("dns6"),DNSADDR=base$3("dnsaddr"),DNS=or$2(base$3("dns"),DNSADDR,DNS4,DNS6),IP=or$2(base$3("ip4"),base$3("ip6")),TCP=or$2(and$1(IP,base$3("tcp")),and$1(DNS,base$3("tcp"))),UDP=and$1(IP,base$3("udp")),UTP=and$1(UDP,base$3("utp")),QUIC=and$1(UDP,base$3("quic")),QUICV1=and$1(UDP,base$3("quic-v1")),_WebSockets$1=or$2(and$1(TCP,base$3("ws")),and$1(DNS,base$3("ws"))),WebSockets$1=or$2(and$1(_WebSockets$1,base$3("p2p")),_WebSockets$1),_WebSocketsSecure$1=or$2(and$1(TCP,base$3("wss")),and$1(DNS,base$3("wss")),and$1(TCP,base$3("tls"),base$3("ws")),and$1(DNS,base$3("tls"),base$3("ws"))),WebSocketsSecure=or$2(and$1(_WebSocketsSecure$1,base$3("p2p")),_WebSocketsSecure$1),HTTP=or$2(and$1(TCP,base$3("http")),and$1(IP,base$3("http")),and$1(DNS,base$3("http"))),HTTPS=or$2(and$1(TCP,base$3("https")),and$1(IP,base$3("https")),and$1(DNS,base$3("https"))),_WebRTCDirect$1=and$1(UDP,base$3("webrtc-direct"),base$3("certhash")),WebRTCDirect=or$2(and$1(_WebRTCDirect$1,base$3("p2p")),_WebRTCDirect$1),_WebTransport$1=and$1(QUICV1,base$3("webtransport"),base$3("certhash"),base$3("certhash")),WebTransport=or$2(and$1(_WebTransport$1,base$3("p2p")),_WebTransport$1),P2PWebRTCStar=or$2(and$1(WebSockets$1,base$3("p2p-webrtc-star"),base$3("p2p")),and$1(WebSocketsSecure,base$3("p2p-webrtc-star"),base$3("p2p")),and$1(WebSockets$1,base$3("p2p-webrtc-star")),and$1(WebSocketsSecure,base$3("p2p-webrtc-star"))),P2PWebRTCDirect=or$2(and$1(HTTP,base$3("p2p-webrtc-direct"),base$3("p2p")),and$1(HTTPS,base$3("p2p-webrtc-direct"),base$3("p2p")),and$1(HTTP,base$3("p2p-webrtc-direct")),and$1(HTTPS,base$3("p2p-webrtc-direct"))),Reliable=or$2(_WebSockets$1,_WebSocketsSecure$1,HTTP,HTTPS,P2PWebRTCStar,P2PWebRTCDirect,TCP,UTP,QUIC,DNS,WebRTCDirect,WebTransport),_P2P$1=or$2(and$1(Reliable,base$3("p2p")),P2PWebRTCStar,P2PWebRTCDirect,WebRTCDirect,WebTransport,base$3("p2p")),_Circuit$1=or$2(and$1(_P2P$1,base$3("p2p-circuit"),_P2P$1),and$1(_P2P$1,base$3("p2p-circuit")),and$1(base$3("p2p-circuit"),_P2P$1),and$1(Reliable,base$3("p2p-circuit")),and$1(base$3("p2p-circuit"),Reliable),base$3("p2p-circuit")),CircuitRecursive=()=>or$2(and$1(_Circuit$1,CircuitRecursive),_Circuit$1),Circuit$1=CircuitRecursive(),P2P=or$2(and$1(Circuit$1,_P2P$1,Circuit$1),and$1(_P2P$1,Circuit$1),and$1(Circuit$1,_P2P$1),Circuit$1,_P2P$1);function makeMatchesFunction(e){function t(r){let n;try{n=multiaddr(r)}catch{return!1}const o=e(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function and$1(...e){function t(r){if(r.length(n=typeof o=="function"?o().partialMatch(r):o.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:makeMatchesFunction(t),partialMatch:t}}function or$2(...e){function t(n){let o=null;return e.some(a=>{const l=typeof a=="function"?a().partialMatch(n):a.partialMatch(n);return l!=null?(o=l,!0):!1}),o}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:makeMatchesFunction(t),partialMatch:t}}function base$3(e){const t=e;function r(o){let a;try{a=multiaddr(o)}catch{return!1}const l=a.protoNames();return l.length===1&&l[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:r,partialMatch:n}}const log$A=logger("libp2p:bootstrap"),DEFAULT_BOOTSTRAP_TAG_NAME="bootstrap",DEFAULT_BOOTSTRAP_TAG_VALUE=50,DEFAULT_BOOTSTRAP_TAG_TTL=12e4,DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT=1e3;var Jl,ec;class Bootstrap extends EventEmitter$2{constructor(r,n={list:[]}){if(n.list==null||n.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super();Ye(this,"timer");Ye(this,"list");Ye(this,"timeout");Ye(this,"components");Ye(this,"_init");Ye(this,Jl,this);Ye(this,ec,"@libp2p/bootstrap");this.components=r,this.timeout=n.timeout??DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT,this.list=[];for(const o of n.list){if(!P2P.matches(o)){log$A.error("Invalid multiaddr");continue}const a=multiaddr(o),l=a.getPeerId();if(l==null){log$A.error("Invalid bootstrap multiaddr without peer id");continue}const c={id:peerIdFromString(l),multiaddrs:[a],protocols:[]};this.list.push(c)}this._init=n}isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(log$A("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(r=>{log$A.error(r)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(const r of this.list){if(await this.components.peerStore.merge(r.id,{tags:{[this._init.tagName??DEFAULT_BOOTSTRAP_TAG_NAME]:{value:this._init.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE,ttl:this._init.tagTTL??DEFAULT_BOOTSTRAP_TAG_TTL}}}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:r})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}}Jl=peerDiscovery,ec=Symbol.toStringTag,Ye(Bootstrap,"tag","bootstrap");function bootstrap(e){return t=>new Bootstrap(t,e)}var TopicValidatorResult;(function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"})(TopicValidatorResult||(TopicValidatorResult={}));function mapIterable(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const n=e.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return r}class PeerMap{constructor(t){Ye(this,"map");if(this.map=new Map,t!=null)for(const[r,n]of t.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){this.map.delete(t.toString())}entries(){return mapIterable(this.map.entries(),t=>[peerIdFromString(t[0]),t[1]])}forEach(t){this.map.forEach((r,n)=>{t(r,peerIdFromString(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,r){this.map.set(t.toString(),r)}keys(){return mapIterable(this.map.keys(),t=>peerIdFromString(t))}values(){return this.map.values()}get size(){return this.map.size}}class PeerSet{constructor(t){Ye(this,"set");if(this.set=new Set,t!=null)for(const r of t)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return mapIterable(this.set.entries(),t=>{const r=peerIdFromString(t[0]);return[r,r]})}forEach(t){this.set.forEach(r=>{const n=peerIdFromString(r);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return mapIterable(this.set.values(),t=>peerIdFromString(t))}intersection(t){const r=new PeerSet;for(const n of t)this.has(n)&&r.add(n);return r}difference(t){const r=new PeerSet;for(const n of this)t.has(n)||r.add(n);return r}union(t){const r=new PeerSet;for(const n of t)r.add(n);for(const n of this)r.add(n);return r}}var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function o(u,_,b){this.fn=u,this.context=_,this.once=b||!1}function a(u,_,b,x,E){if(typeof b!="function")throw new TypeError("The listener must be a function");var I=new o(b,x||u,E),k=r?r+_:_;return u._events[k]?u._events[k].fn?u._events[k]=[u._events[k],I]:u._events[k].push(I):(u._events[k]=I,u._eventsCount++),u}function l(u,_){--u._eventsCount===0?u._events=new n:delete u._events[_]}function c(){this._events=new n,this._eventsCount=0}c.prototype.eventNames=function(){var _=[],b,x;if(this._eventsCount===0)return _;for(x in b=this._events)t.call(b,x)&&_.push(r?x.slice(1):x);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(b)):_},c.prototype.listeners=function(_){var b=r?r+_:_,x=this._events[b];if(!x)return[];if(x.fn)return[x.fn];for(var E=0,I=x.length,k=new Array(I);EglobalThis.DOMException===void 0?new AbortError$3(e):new DOMException(e),getAbortedReason$1=e=>{const t=e.reason===void 0?getDOMException$1("This operation was aborted."):e.reason;return t instanceof Error?t:getDOMException$1(t)};function pTimeout$1(e,t,r,n){let o;const a=new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){l(e);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){const{signal:u}=n;u.aborted&&c(getAbortedReason$1(u)),u.addEventListener("abort",()=>{c(getAbortedReason$1(u))})}o=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{l(r())}catch(b){c(b)}return}const u=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,_=r instanceof Error?r:new TimeoutError$1(u);typeof e.cancel=="function"&&e.cancel(),c(_)},t),(async()=>{try{l(await e)}catch(u){c(u)}finally{n.customTimers.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{clearTimeout(o),o=void 0},a}function lowerBound$1(e,t,r){let n=0,o=e.length;for(;o>0;){const a=Math.trunc(o/2);let l=n+a;r(e[l],t)<=0?(n=++l,o-=a+1):o=a}return n}var __classPrivateFieldGet$1=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},_PriorityQueue_queue;class PriorityQueue{constructor(){_PriorityQueue_queue.set(this,[])}enqueue(t,r){r={priority:0,...r};const n={priority:r.priority,run:t};if(this.size&&__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f")[this.size-1].priority>=r.priority){__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").push(n);return}const o=lowerBound$1(__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f"),n,(a,l)=>l.priority-a.priority);__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").splice(o,0,n)}dequeue(){const t=__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").shift();return t?.run}filter(t){return __classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return __classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").length}}_PriorityQueue_queue=new WeakMap;var __classPrivateFieldSet=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},__classPrivateFieldGet=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},_PQueue_instances,_PQueue_carryoverConcurrencyCount,_PQueue_isIntervalIgnored,_PQueue_intervalCount,_PQueue_intervalCap,_PQueue_interval,_PQueue_intervalEnd,_PQueue_intervalId,_PQueue_timeoutId,_PQueue_queue,_PQueue_queueClass,_PQueue_pending,_PQueue_concurrency,_PQueue_isPaused,_PQueue_throwOnTimeout,_PQueue_doesIntervalAllowAnother_get,_PQueue_doesConcurrentAllowAnother_get,_PQueue_next,_PQueue_onResumeInterval,_PQueue_isIntervalPaused_get,_PQueue_tryToStartAnother,_PQueue_initializeIntervalIfNeeded,_PQueue_onInterval,_PQueue_processQueue,_PQueue_throwOnAbort,_PQueue_onEvent;class AbortError$2 extends Error{}class PQueue extends EventEmitter$1{constructor(t){var r,n,o,a;if(super(),_PQueue_instances.add(this),_PQueue_carryoverConcurrencyCount.set(this,void 0),_PQueue_isIntervalIgnored.set(this,void 0),_PQueue_intervalCount.set(this,0),_PQueue_intervalCap.set(this,void 0),_PQueue_interval.set(this,void 0),_PQueue_intervalEnd.set(this,0),_PQueue_intervalId.set(this,void 0),_PQueue_timeoutId.set(this,void 0),_PQueue_queue.set(this,void 0),_PQueue_queueClass.set(this,void 0),_PQueue_pending.set(this,0),_PQueue_concurrency.set(this,void 0),_PQueue_isPaused.set(this,void 0),_PQueue_throwOnTimeout.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:PriorityQueue,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(o=t.interval)===null||o===void 0?void 0:o.toString())!==null&&a!==void 0?a:""}\` (${typeof t.interval})`);__classPrivateFieldSet(this,_PQueue_carryoverConcurrencyCount,t.carryoverConcurrencyCount,"f"),__classPrivateFieldSet(this,_PQueue_isIntervalIgnored,t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,"f"),__classPrivateFieldSet(this,_PQueue_intervalCap,t.intervalCap,"f"),__classPrivateFieldSet(this,_PQueue_interval,t.interval,"f"),__classPrivateFieldSet(this,_PQueue_queue,new t.queueClass,"f"),__classPrivateFieldSet(this,_PQueue_queueClass,t.queueClass,"f"),this.concurrency=t.concurrency,this.timeout=t.timeout,__classPrivateFieldSet(this,_PQueue_throwOnTimeout,t.throwOnTimeout===!0,"f"),__classPrivateFieldSet(this,_PQueue_isPaused,t.autoStart===!1,"f")}get concurrency(){return __classPrivateFieldGet(this,_PQueue_concurrency,"f")}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);__classPrivateFieldSet(this,_PQueue_concurrency,t,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this)}async add(t,r={}){return r={timeout:this.timeout,throwOnTimeout:__classPrivateFieldGet(this,_PQueue_throwOnTimeout,"f"),...r},new Promise((n,o)=>{__classPrivateFieldGet(this,_PQueue_queue,"f").enqueue(async()=>{var a,l,c;__classPrivateFieldSet(this,_PQueue_pending,(l=__classPrivateFieldGet(this,_PQueue_pending,"f"),l++,l),"f"),__classPrivateFieldSet(this,_PQueue_intervalCount,(c=__classPrivateFieldGet(this,_PQueue_intervalCount,"f"),c++,c),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new AbortError$2("The task was aborted.");let u=t({signal:r.signal});r.timeout&&(u=pTimeout$1(Promise.resolve(u),r.timeout)),r.signal&&(u=Promise.race([u,__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_throwOnAbort).call(this,r.signal)]));const _=await u;n(_),this.emit("completed",_)}catch(u){if(u instanceof TimeoutError$1&&!r.throwOnTimeout){n();return}o(u),this.emit("error",u)}finally{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_next).call(this)}},r),this.emit("add"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_tryToStartAnother).call(this)})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return __classPrivateFieldGet(this,_PQueue_isPaused,"f")?(__classPrivateFieldSet(this,_PQueue_isPaused,!1,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this),this):this}pause(){__classPrivateFieldSet(this,_PQueue_isPaused,!0,"f")}clear(){__classPrivateFieldSet(this,_PQueue_queue,new(__classPrivateFieldGet(this,_PQueue_queueClass,"f")),"f")}async onEmpty(){__classPrivateFieldGet(this,_PQueue_queue,"f").size!==0&&await __classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onEvent).call(this,"empty")}async onSizeLessThan(t){__classPrivateFieldGet(this,_PQueue_queue,"f").size__classPrivateFieldGet(this,_PQueue_queue,"f").size{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onResumeInterval).call(this)},r),"f"),!0}return!1},_PQueue_tryToStartAnother=function e(){if(__classPrivateFieldGet(this,_PQueue_queue,"f").size===0)return __classPrivateFieldGet(this,_PQueue_intervalId,"f")&&clearInterval(__classPrivateFieldGet(this,_PQueue_intervalId,"f")),__classPrivateFieldSet(this,_PQueue_intervalId,void 0,"f"),this.emit("empty"),__classPrivateFieldGet(this,_PQueue_pending,"f")===0&&this.emit("idle"),!1;if(!__classPrivateFieldGet(this,_PQueue_isPaused,"f")){const t=!__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_isIntervalPaused_get);if(__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_doesIntervalAllowAnother_get)&&__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_doesConcurrentAllowAnother_get)){const r=__classPrivateFieldGet(this,_PQueue_queue,"f").dequeue();return r?(this.emit("active"),r(),t&&__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_initializeIntervalIfNeeded).call(this),!0):!1}}return!1},_PQueue_initializeIntervalIfNeeded=function e(){__classPrivateFieldGet(this,_PQueue_isIntervalIgnored,"f")||__classPrivateFieldGet(this,_PQueue_intervalId,"f")!==void 0||(__classPrivateFieldSet(this,_PQueue_intervalId,setInterval(()=>{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onInterval).call(this)},__classPrivateFieldGet(this,_PQueue_interval,"f")),"f"),__classPrivateFieldSet(this,_PQueue_intervalEnd,Date.now()+__classPrivateFieldGet(this,_PQueue_interval,"f"),"f"))},_PQueue_onInterval=function e(){__classPrivateFieldGet(this,_PQueue_intervalCount,"f")===0&&__classPrivateFieldGet(this,_PQueue_pending,"f")===0&&__classPrivateFieldGet(this,_PQueue_intervalId,"f")&&(clearInterval(__classPrivateFieldGet(this,_PQueue_intervalId,"f")),__classPrivateFieldSet(this,_PQueue_intervalId,void 0,"f")),__classPrivateFieldSet(this,_PQueue_intervalCount,__classPrivateFieldGet(this,_PQueue_carryoverConcurrencyCount,"f")?__classPrivateFieldGet(this,_PQueue_pending,"f"):0,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this)},_PQueue_processQueue=function e(){for(;__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_tryToStartAnother).call(this););},_PQueue_throwOnAbort=async function e(t){return new Promise((r,n)=>{t.addEventListener("abort",()=>{n(new AbortError$2("The task was aborted."))},{once:!0})})},_PQueue_onEvent=async function e(t,r){return new Promise(n=>{const o=()=>{r&&!r()||(this.off(t,o),n())};this.on(t,o)})};const codes$7={ERR_INVALID_SIGNATURE_POLICY:"ERR_INVALID_SIGNATURE_POLICY",ERR_UNHANDLED_SIGNATURE_POLICY:"ERR_UNHANDLED_SIGNATURE_POLICY",ERR_MISSING_SIGNATURE:"ERR_MISSING_SIGNATURE",ERR_MISSING_SEQNO:"ERR_MISSING_SEQNO",ERR_MISSING_KEY:"ERR_MISSING_KEY",ERR_INVALID_SIGNATURE:"ERR_INVALID_SIGNATURE",ERR_MISSING_FROM:"ERR_MISSING_FROM",ERR_UNEXPECTED_FROM:"ERR_UNEXPECTED_FROM",ERR_UNEXPECTED_SIGNATURE:"ERR_UNEXPECTED_SIGNATURE",ERR_UNEXPECTED_KEY:"ERR_UNEXPECTED_KEY",ERR_UNEXPECTED_SEQNO:"ERR_UNEXPECTED_SEQNO",ERR_TOPIC_VALIDATOR_REJECT:"ERR_TOPIC_VALIDATOR_REJECT"};class AbortError$1 extends Error{constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function getIterator(e){if(e!=null){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}function abortableSource(e,t,r){const n=r??{},o=getIterator(e);async function*a(){let l;const c=()=>{l?.()};for(t.addEventListener("abort",c);;){let u;try{if(t.aborted){const{abortMessage:b,abortCode:x}=n;throw new AbortError$1(b,x)}const _=new Promise((b,x)=>{l=()=>{const{abortMessage:E,abortCode:I}=n;x(new AbortError$1(E,I))}});u=await Promise.race([_,o.next()]),l=null}catch(_){t.removeEventListener("abort",c);const b=_.type==="aborted"&&t.aborted;if(b&&n.onAbort!=null&&n.onAbort(e),typeof o.return=="function")try{const x=o.return();x instanceof Promise&&x.catch(E=>{n.onReturnError!=null&&n.onReturnError(E)})}catch(x){n.onReturnError!=null&&n.onReturnError(x)}if(b&&n.returnOnAbort===!0)return;throw _}if(u.done===!0)break;yield u.value}t.removeEventListener("abort",c)}return a()}function abortableSink(e,t,r){return n=>e(abortableSource(n,t,r))}function abortableDuplex(e,t,r){return{sink:abortableSink(e.sink,t,{...r,onAbort:void 0}),source:abortableSource(e.source,t,r)}}const log$z=logger("libp2p-pubsub:peer-streams");class PeerStreams extends EventEmitter$2{constructor(r){super();Ye(this,"id");Ye(this,"protocol");Ye(this,"outboundStream");Ye(this,"inboundStream");Ye(this,"_rawOutboundStream");Ye(this,"_rawInboundStream");Ye(this,"_inboundAbortController");Ye(this,"closed");this.id=r.id,this.protocol=r.protocol,this._inboundAbortController=new AbortController,this.closed=!1}get isReadable(){return Boolean(this.inboundStream)}get isWritable(){return Boolean(this.outboundStream)}write(r){if(this.outboundStream==null){const n=this.id.toString();throw new Error("No writable connection to "+n)}this.outboundStream.push(r instanceof Uint8Array?new Uint8ArrayList(r):r)}attachInboundStream(r){return this._rawInboundStream=r,this.inboundStream=abortableSource(pipe(this._rawInboundStream,n=>decode$a(n)),this._inboundAbortController.signal,{returnOnAbort:!0}),this.dispatchEvent(new CustomEvent$1("stream:inbound")),this.inboundStream}async attachOutboundStream(r){const n=this.outboundStream;return this.outboundStream!=null&&this.outboundStream.end(),this._rawOutboundStream=r,this.outboundStream=pushable({objectMode:!0,onEnd:o=>{this._rawOutboundStream!=null&&this._rawOutboundStream.closeWrite().catch(a=>{log$z("error closing outbound stream",a)}),this._rawOutboundStream=void 0,this.outboundStream=void 0,o!=null&&this.dispatchEvent(new CustomEvent$1("close"))}}),pipe(this.outboundStream,o=>encode$c(o),this._rawOutboundStream).catch(o=>{log$z.error(o)}),n==null&&this.dispatchEvent(new CustomEvent$1("stream:outbound")),this.outboundStream}close(){this.closed||(this.closed=!0,this.outboundStream!=null&&this.outboundStream.end(),this.inboundStream!=null&&this._inboundAbortController.abort(),this._rawOutboundStream=void 0,this.outboundStream=void 0,this._rawInboundStream=void 0,this.inboundStream=void 0,this.dispatchEvent(new CustomEvent$1("close")))}}const hashName={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function pbkdf2(e,t,r,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){const c=Object.keys(hashName).join(" / ");throw new CodeError(`Hash '${o}' is unknown or not supported. Must be ${c}`,"ERR_UNSUPPORTED_HASH_TYPE")}const a=hashName[o],l=pbkdf2$1(e,t,r,n,a);return util$7.exports.encode64(l,null)}function randomSeqno(){return BigInt(`0x${toString$5(randomBytes(8),"base16")}`)}const msgId=(e,t)=>{const r=fromString$1(t.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(e.length+r.length);return n.set(e,0),n.set(r,e.length),n},noSignMsgId=e=>sha256$1.encode(e),ensureArray=function(e){return Array.isArray(e)?e:[e]},isSigned=async e=>{if(e.sequenceNumber==null||e.from==null||e.signature==null)return!1;const t=peerIdFromBytes(e.from);return t.publicKey!=null?!0:e.key!=null?(await peerIdFromKeys(e.key)).equals(t):!1},toMessage=async e=>{if(e.from==null)throw new CodeError("RPC message was missing from",codes$7.ERR_MISSING_FROM);if(!await isSigned(e))return{type:"unsigned",topic:e.topic??"",data:e.data??new Uint8Array(0)};const t=peerIdFromBytes(e.from),r={type:"signed",from:peerIdFromBytes(e.from),topic:e.topic??"",sequenceNumber:bigIntFromBytes(e.sequenceNumber??new Uint8Array(0)),data:e.data??new Uint8Array(0),signature:e.signature??new Uint8Array(0),key:e.key??t.publicKey??new Uint8Array(0)};if(r.key.length===0)throw new CodeError("Signed RPC message was missing key",codes$7.ERR_MISSING_KEY);return r},toRpcMessage=e=>e.type==="signed"?{from:e.from.multihash.bytes,data:e.data,sequenceNumber:bigIntToBytes(e.sequenceNumber),topic:e.topic,signature:e.signature,key:e.key}:{data:e.data,topic:e.topic},bigIntToBytes=e=>{let t=e.toString(16);return t.length%2!==0&&(t=`0${t}`),fromString$1(t,"base16")},bigIntFromBytes=e=>BigInt(`0x${toString$5(e,"base16")}`),SignPrefix=fromString$1("libp2p-pubsub:");async function signMessage(e,t,r){if(e.privateKey==null)throw new Error("Cannot sign message, no private key present");if(e.publicKey==null)throw new Error("Cannot sign message, no public key present");const n={type:"signed",topic:t.topic,data:t.data,sequenceNumber:t.sequenceNumber,from:e},o=concat$1([SignPrefix,r(toRpcMessage(n)).subarray()]),a=await unmarshalPrivateKey(e.privateKey);return n.signature=await a.sign(o),n.key=e.publicKey,n}async function verifySignature(e,t){if(e.type!=="signed")throw new Error('Message type must be "signed" to be verified');if(e.signature==null)throw new Error("Message must contain a signature to be verified");if(e.from==null)throw new Error("Message must contain a from property to be verified");const r=concat$1([SignPrefix,t({...toRpcMessage(e),signature:void 0,key:void 0}).subarray()]),n=await messagePublicKey(e);return unmarshalPublicKey(n).verify(r,e.signature)}async function messagePublicKey(e){if(e.type!=="signed")throw new Error('Message type must be "signed" to have a public key');if(e.from==null)throw new Error("Could not get the public key from the originator id");if(e.key!=null){const t=await peerIdFromKeys(e.key);if(t.publicKey!=null)return t.publicKey}if(e.from.publicKey!=null)return e.from.publicKey;throw new Error("Could not get the public key from the originator id")}const log$y=logger("libp2p:pubsub");class PubSubBaseProtocol extends EventEmitter$2{constructor(r,n){super();Ye(this,"started");Ye(this,"topics");Ye(this,"subscriptions");Ye(this,"peers");Ye(this,"globalSignaturePolicy");Ye(this,"canRelayMessage");Ye(this,"emitSelf");Ye(this,"topicValidators");Ye(this,"queue");Ye(this,"multicodecs");Ye(this,"components");Ye(this,"_registrarTopologyIds");Ye(this,"enabled");Ye(this,"maxInboundStreams");Ye(this,"maxOutboundStreams");const{multicodecs:o=[],globalSignaturePolicy:a="StrictSign",canRelayMessage:l=!1,emitSelf:c=!1,messageProcessingConcurrency:u=10,maxInboundStreams:_=1,maxOutboundStreams:b=1}=n;this.components=r,this.multicodecs=ensureArray(o),this.enabled=n.enabled!==!1,this.started=!1,this.topics=new Map,this.subscriptions=new Set,this.peers=new PeerMap,this.globalSignaturePolicy=a==="StrictNoSign"?"StrictNoSign":"StrictSign",this.canRelayMessage=l,this.emitSelf=c,this.topicValidators=new Map,this.queue=new PQueue({concurrency:u}),this.maxInboundStreams=_,this.maxOutboundStreams=b,this._onIncomingStream=this._onIncomingStream.bind(this),this._onPeerConnected=this._onPeerConnected.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this)}async start(){if(this.started||!this.enabled)return;log$y("starting");const r=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>{await r.handle(o,this._onIncomingStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})}));const n={onConnect:this._onPeerConnected,onDisconnect:this._onPeerDisconnected};this._registrarTopologyIds=await Promise.all(this.multicodecs.map(async o=>r.register(o,n))),log$y("started"),this.started=!0}async stop(){if(!this.started||!this.enabled)return;const r=this.components.registrar;this._registrarTopologyIds!=null&&this._registrarTopologyIds?.forEach(n=>{r.unregister(n)}),await Promise.all(this.multicodecs.map(async n=>{await r.unhandle(n)})),log$y("stopping");for(const n of this.peers.values())n.close();this.peers.clear(),this.subscriptions=new Set,this.started=!1,log$y("stopped")}isStarted(){return this.started}_onIncomingStream(r){const{stream:n,connection:o}=r,a=o.remotePeer;if(n.protocol==null){n.abort(new Error("Stream was not multiplexed"));return}const l=this.addPeer(a,n.protocol),c=l.attachInboundStream(n);this.processMessages(a,c,l).catch(u=>{log$y(u)})}_onPeerConnected(r,n){log$y("connected %p",r),Promise.resolve().then(async()=>{try{const o=await n.newStream(this.multicodecs);if(o.protocol==null){o.abort(new Error("Stream was not multiplexed"));return}await this.addPeer(r,o.protocol).attachOutboundStream(o)}catch(o){log$y.error(o)}this.send(r,{subscriptions:Array.from(this.subscriptions).map(o=>o.toString()),subscribe:!0})}).catch(o=>{log$y.error(o)})}_onPeerDisconnected(r,n){const o=r.toString();log$y("connection ended",o),this._removePeer(r)}addPeer(r,n){const o=this.peers.get(r);if(o!=null)return o;log$y("new peer %p",r);const a=new PeerStreams({id:r,protocol:n});return this.peers.set(r,a),a.addEventListener("close",()=>this._removePeer(r),{once:!0}),a}_removePeer(r){const n=this.peers.get(r);if(n!=null){n.close(),log$y("delete peer %p",r),this.peers.delete(r);for(const o of this.topics.values())o.delete(r);return n}}async processMessages(r,n,o){try{await pipe(n,async a=>{for await(const l of a){const c=this.decodeRpc(l),u=[];for(const _ of c.messages??[]){if(_.from==null||_.data==null||_.topic==null){log$y("message from %p was missing from, data or topic fields, dropping",r);continue}u.push({from:_.from,data:_.data,topic:_.topic,sequenceNumber:_.sequenceNumber??void 0,signature:_.signature??void 0,key:_.key??void 0})}this.processRpc(r,o,{subscriptions:(c.subscriptions??[]).map(_=>({subscribe:Boolean(_.subscribe),topic:_.topic??""})),messages:u}).catch(_=>{log$y(_)})}})}catch(a){this._onPeerDisconnected(o.id,a)}}async processRpc(r,n,o){if(!this.acceptFrom(r))return log$y("received message from unacceptable peer %p",r),!1;log$y("rpc from %p",r);const{subscriptions:a,messages:l}=o;return a!=null&&a.length>0&&(log$y("subscription update from %p",r),a.forEach(c=>{this.processRpcSubOpt(r,c)}),super.dispatchEvent(new CustomEvent$1("subscription-change",{detail:{peerId:n.id,subscriptions:a.map(({topic:c,subscribe:u})=>({topic:`${c??""}`,subscribe:Boolean(u)}))}}))),l!=null&&l.length>0&&(log$y("messages from %p",r),this.queue.addAll(l.map(c=>async()=>{if(c.topic==null||!this.subscriptions.has(c.topic)&&!this.canRelayMessage)return log$y("received message we didn't subscribe to. Dropping."),!1;try{const u=await toMessage(c);await this.processMessage(r,u)}catch(u){log$y.error(u)}})).catch(c=>{log$y(c)})),!0}processRpcSubOpt(r,n){const o=n.topic;if(o==null)return;let a=this.topics.get(o);a==null&&(a=new PeerSet,this.topics.set(o,a)),n.subscribe===!0?a.add(r):a.delete(r)}async processMessage(r,n){if(!(this.components.peerId.equals(r)&&!this.emitSelf)){try{await this.validate(r,n)}catch(o){log$y("Message is invalid, dropping it. %O",o);return}this.subscriptions.has(n.topic)&&(!this.components.peerId.equals(r)||this.emitSelf)&&super.dispatchEvent(new CustomEvent$1("message",{detail:n})),await this.publishMessage(r,n)}}getMsgId(r){switch(this.globalSignaturePolicy){case"StrictSign":if(r.type!=="signed")throw new CodeError('Message type should be "signed" when signature policy is StrictSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(r.sequenceNumber==null)throw new CodeError("Need seqno when signature policy is StrictSign but it was missing",codes$7.ERR_MISSING_SEQNO);if(r.key==null)throw new CodeError("Need key when signature policy is StrictSign but it was missing",codes$7.ERR_MISSING_KEY);return msgId(r.key,r.sequenceNumber);case"StrictNoSign":return noSignMsgId(r.data);default:throw new CodeError("Cannot get message id: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}}acceptFrom(r){return!0}send(r,n){const{messages:o,subscriptions:a,subscribe:l}=n;this.sendRpc(r,{subscriptions:(a??[]).map(c=>({topic:c,subscribe:Boolean(l)})),messages:(o??[]).map(toRpcMessage)})}sendRpc(r,n){const o=this.peers.get(r);if(o==null||!o.isWritable){log$y.error("Cannot send RPC to %p as there is no open stream to it available",r);return}o.write(this.encodeRpc(n))}async validate(r,n){switch(this.globalSignaturePolicy){case"StrictNoSign":if(n.type!=="unsigned")throw new CodeError('Message type should be "unsigned" when signature policy is StrictNoSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(n.signature!=null)throw new CodeError("StrictNoSigning: signature should not be present",codes$7.ERR_UNEXPECTED_SIGNATURE);if(n.key!=null)throw new CodeError("StrictNoSigning: key should not be present",codes$7.ERR_UNEXPECTED_KEY);if(n.sequenceNumber!=null)throw new CodeError("StrictNoSigning: seqno should not be present",codes$7.ERR_UNEXPECTED_SEQNO);break;case"StrictSign":if(n.type!=="signed")throw new CodeError('Message type should be "signed" when signature policy is StrictSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(n.signature==null)throw new CodeError("StrictSigning: Signing required and no signature was present",codes$7.ERR_MISSING_SIGNATURE);if(n.sequenceNumber==null)throw new CodeError("StrictSigning: Signing required and no sequenceNumber was present",codes$7.ERR_MISSING_SEQNO);if(!await verifySignature(n,this.encodeMessage.bind(this)))throw new CodeError("StrictSigning: Invalid message signature",codes$7.ERR_INVALID_SIGNATURE);break;default:throw new CodeError("Cannot validate message: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}const a=this.topicValidators.get(n.topic);if(a!=null){const l=await a(r,n);if(l===TopicValidatorResult.Reject||l===TopicValidatorResult.Ignore)throw new CodeError("Message validation failed",codes$7.ERR_TOPIC_VALIDATOR_REJECT)}}async buildMessage(r){switch(this.globalSignaturePolicy){case"StrictSign":return signMessage(this.components.peerId,r,this.encodeMessage.bind(this));case"StrictNoSign":return Promise.resolve({type:"unsigned",...r});default:throw new CodeError("Cannot build message: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}}getSubscribers(r){if(!this.started)throw new CodeError("not started yet","ERR_NOT_STARTED_YET");if(r==null)throw new CodeError("topic is required","ERR_NOT_VALID_TOPIC");const n=this.topics.get(r.toString());return n==null?[]:Array.from(n.values())}async publish(r,n){if(!this.started)throw new Error("Pubsub has not started");const o={from:this.components.peerId,topic:r,data:n??new Uint8Array(0),sequenceNumber:randomSeqno()};log$y("publish topic: %s from: %p data: %m",r,o.from,o.data);const a=await this.buildMessage(o);let l=!1;this.emitSelf&&this.subscriptions.has(r)&&(l=!0,super.dispatchEvent(new CustomEvent$1("message",{detail:a})));const c=await this.publishMessage(this.components.peerId,a);return l&&(c.recipients=[...c.recipients,this.components.peerId]),c}subscribe(r){if(!this.started)throw new Error("Pubsub has not started");if(log$y("subscribe to topic: %s",r),!this.subscriptions.has(r)){this.subscriptions.add(r);for(const n of this.peers.keys())this.send(n,{subscriptions:[r],subscribe:!0})}}unsubscribe(r){if(!this.started)throw new Error("Pubsub is not started");super.removeEventListener(r);const n=this.subscriptions.has(r);if(log$y("unsubscribe from %s - am subscribed %s",r,n),n){this.subscriptions.delete(r);for(const o of this.peers.keys())this.send(o,{subscriptions:[r],subscribe:!1})}}getTopics(){if(!this.started)throw new Error("Pubsub is not started");return Array.from(this.subscriptions)}getPeers(){if(!this.started)throw new Error("Pubsub is not started");return Array.from(this.peers.keys())}}class SimpleTimeCache{constructor(t){Ye(this,"entries");Ye(this,"validityMs");Ye(this,"lastPruneTime",0);this.entries=new Map,this.validityMs=t.validityMs}put(t,r){this.entries.set(t,{value:r,validUntilMs:Date.now()+this.validityMs}),this.prune()}prune(){const t=Date.now();if(!(t-this.lastPruneTime<200)){this.lastPruneTime=t;for(const[r,n]of this.entries.entries())if(n.validUntilMs=Date.now()?r.value:void 0}clear(){this.entries=new Map,this.lastPruneTime=0}}logger("libp2p:floodsub");const multicodec="/floodsub/1.0.0";var RPC;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.subscribe!=null&&(a.uint32(8),a.bool(o.subscribe)),o.topic!=null&&(a.uint32(18),a.string(o.topic)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.subscribe=o.bool();break;case 2:l.topic=o.string();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.SubOpts||(e.SubOpts={})),function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.from!=null&&(a.uint32(10),a.bytes(o.from)),o.data!=null&&(a.uint32(18),a.bytes(o.data)),o.sequenceNumber!=null&&(a.uint32(26),a.bytes(o.sequenceNumber)),o.topic!=null&&(a.uint32(34),a.string(o.topic)),o.signature!=null&&(a.uint32(42),a.bytes(o.signature)),o.key!=null&&(a.uint32(50),a.bytes(o.key)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.from=o.bytes();break;case 2:l.data=o.bytes();break;case 3:l.sequenceNumber=o.bytes();break;case 4:l.topic=o.string();break;case 5:l.signature=o.bytes();break;case 6:l.key=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())}(e.Message||(e.Message={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.subscriptions!=null)for(const a of r.subscriptions)n.uint32(10),e.SubOpts.codec().encode(a,n);if(r.messages!=null)for(const a of r.messages)n.uint32(18),e.Message.codec().encode(a,n);r.control!=null&&(n.uint32(26),ControlMessage.codec().encode(r.control,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={subscriptions:[],messages:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.subscriptions.push(e.SubOpts.codec().decode(r,r.uint32()));break;case 2:o.messages.push(e.Message.codec().decode(r,r.uint32()));break;case 3:o.control=ControlMessage.codec().decode(r,r.uint32());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(RPC||(RPC={}));var ControlMessage;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.ihave!=null)for(const a of r.ihave)n.uint32(10),ControlIHave.codec().encode(a,n);if(r.iwant!=null)for(const a of r.iwant)n.uint32(18),ControlIWant.codec().encode(a,n);if(r.graft!=null)for(const a of r.graft)n.uint32(26),ControlGraft.codec().encode(a,n);if(r.prune!=null)for(const a of r.prune)n.uint32(34),ControlPrune.codec().encode(a,n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={ihave:[],iwant:[],graft:[],prune:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.ihave.push(ControlIHave.codec().decode(r,r.uint32()));break;case 2:o.iwant.push(ControlIWant.codec().decode(r,r.uint32()));break;case 3:o.graft.push(ControlGraft.codec().decode(r,r.uint32()));break;case 4:o.prune.push(ControlPrune.codec().decode(r,r.uint32()));break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlMessage||(ControlMessage={}));var ControlIHave;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),r.messageIDs!=null)for(const a of r.messageIDs)n.uint32(18),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={messageIDs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;case 2:o.messageIDs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlIHave||(ControlIHave={}));var ControlIWant;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.messageIDs!=null)for(const a of r.messageIDs)n.uint32(10),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={messageIDs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.messageIDs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlIWant||(ControlIWant={}));var ControlGraft;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlGraft||(ControlGraft={}));var ControlPrune;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),r.peers!=null)for(const a of r.peers)n.uint32(18),PeerInfo.codec().encode(a,n);r.backoff!=null&&(n.uint32(24),n.uint64(r.backoff)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={peers:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;case 2:o.peers.push(PeerInfo.codec().decode(r,r.uint32()));break;case 3:o.backoff=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlPrune||(ControlPrune={}));var PeerInfo;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.peerID!=null&&(n.uint32(10),n.bytes(r.peerID)),r.signedPeerRecord!=null&&(n.uint32(18),n.bytes(r.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.peerID=r.bytes();break;case 2:o.signedPeerRecord=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerInfo||(PeerInfo={}));const log$x=logger("libp2p:floodsub");class FloodSub extends PubSubBaseProtocol{constructor(r,n){super(r,{...n,canRelayMessage:!0,multicodecs:[multicodec]});Ye(this,"seenCache");this.seenCache=new SimpleTimeCache({validityMs:n?.seenTTL??3e4})}decodeRpc(r){return RPC.decode(r)}encodeRpc(r){return RPC.encode(r)}decodeMessage(r){return RPC.Message.decode(r)}encodeMessage(r){return RPC.Message.encode(r)}async processMessage(r,n){const o=await super.getMsgId(n),a=toString$5(o,"base64");this.seenCache.has(a)||(this.seenCache.put(a,!0),await super.processMessage(r,n))}async publishMessage(r,n){const o=this.getSubscribers(n.topic),a=[];return o==null||o.length===0?(log$x("no peers are subscribed to topic %s",n.topic),{recipients:a}):(o.forEach(l=>{if(this.components.peerId.equals(l)){log$x("not sending message on topic %s to myself",n.topic);return}if(l.equals(r)){log$x("not sending message on topic %s to sender %p",n.topic,l);return}log$x("publish msgs on topics %s %p",n.topic,l),a.push(l),this.send(l,{messages:[n]})}),{recipients:a})}}function floodsub(e={}){return t=>new FloodSub(t,e)}var RateLimiterAbstract_1=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){this._points=t>=0?t:4}get duration(){return this._duration}set duration(t){this._duration=typeof t>"u"?1:t}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:Boolean(t)}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=typeof t>"u"?Math.ceil(this.msDuration/this.points):t}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}},BlockedKeys_1$1=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){const t=Date.now();Object.keys(this._keys).forEach(r=>{this._keys[r]<=t&&delete this._keys[r]}),this._addedKeysAmount=Object.keys(this._keys).length}add(t,r){this.addMs(t,r*1e3)}addMs(t,r){this._keys[t]=Date.now()+r,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(t){const r=this._keys[t];if(r&&r>=Date.now()){this.collectExpired();const n=Date.now();return r>=n?r-n:0}return 0}delete(t){t?delete this._keys[t]:Object.keys(this._keys).forEach(r=>{delete this._keys[r]})}};const BlockedKeys$1=BlockedKeys_1$1;var BlockedKeys_1=BlockedKeys$1,RateLimiterRes_1=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=Boolean(t)}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}};const RateLimiterAbstract$3=RateLimiterAbstract_1,BlockedKeys=BlockedKeys_1,RateLimiterRes$b=RateLimiterRes_1;var RateLimiterStoreAbstract_1=class extends RateLimiterAbstract$3{constructor(t={}){super(t),this.inMemoryBlockOnConsumed=t.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=t.inMemoryBlockDuration,this.insuranceLimiter=t.insuranceLimiter,this._inMemoryBlockedKeys=new BlockedKeys}get client(){return this._client}set client(t){if(typeof t>"u")throw new Error("storeClient is not set");this._client=t}_afterConsume(t,r,n,o,a,l={}){const c=this._getRateLimiterRes(n,o,a);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&c.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,c.msBeforeNext),c.consumedPoints>this.points?r(c):t(c);if(c.consumedPoints>this.points){let u=Promise.resolve();this.blockDuration>0&&c.consumedPoints<=this.points+o&&(c.msBeforeNext=this.msBlockDuration,u=this._block(n,c.consumedPoints,this.msBlockDuration,l)),this.inMemoryBlockOnConsumed>0&&c.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),c.msBeforeNext=this.msInMemoryBlockDuration),u.then(()=>{r(c)}).catch(_=>{r(_)})}else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{n(u)}).catch(u=>{o(u)}):o(t)}getInMemoryBlockMsBeforeExpire(t){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(t):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(t){if(this._inMemoryBlockOnConsumed=t?parseInt(t):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(t){if(this._inMemoryBlockDuration=t?parseInt(t):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(t){if(typeof t<"u"&&!(t instanceof RateLimiterAbstract$3))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=t,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(t,r,n={}){const o=r*1e3;return this._block(this.getKey(t),this.points+1,o,n)}set(t,r,n,o={}){const a=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(t),r,a,o)}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=this.getKey(t),c=this.getInMemoryBlockMsBeforeExpire(l);if(c>0)return a(new RateLimiterRes$b(0,c));this._upsert(l,r,this._getKeySecDuration(n)*1e3,!1,n).then(u=>{this._afterConsume(o,a,l,r,u)}).catch(u=>{this._handleError(u,"consume",o,a,t,r,n)})})}penalty(t,r=1,n={}){const o=this.getKey(t);return new Promise((a,l)=>{this._upsert(o,r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{a(this._getRateLimiterRes(o,r,c))}).catch(c=>{this._handleError(c,"penalty",a,l,t,r,n)})})}reward(t,r=1,n={}){const o=this.getKey(t);return new Promise((a,l)=>{this._upsert(o,-r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{a(this._getRateLimiterRes(o,-r,c))}).catch(c=>{this._handleError(c,"reward",a,l,t,r,n)})})}get(t,r={}){const n=this.getKey(t);return new Promise((o,a)=>{this._get(n,r).then(l=>{o(l===null||typeof l>"u"?null:this._getRateLimiterRes(n,0,l))}).catch(l=>{this._handleError(l,"get",o,a,t,r)})})}delete(t,r={}){const n=this.getKey(t);return new Promise((o,a)=>{this._delete(n,r).then(l=>{this._inMemoryBlockedKeys.delete(n),o(l)}).catch(l=>{this._handleError(l,"delete",o,a,t,r)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(t,r,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(t,r,n,o={}){return new Promise((a,l)=>{this._upsert(t,r,n,!0,o).then(()=>{a(new RateLimiterRes$b(0,n>0?n:-1,r))}).catch(c=>{this._handleError(c,"block",a,l,this.parseKey(t),n/1e3,o)})})}_get(t,r={}){throw new Error("You have to implement the method '_get'!")}_delete(t,r={}){throw new Error("You have to implement the method '_delete'!")}_upsert(t,r,n,o=!1,a={}){throw new Error("You have to implement the method '_upsert'!")}};const RateLimiterStoreAbstract$4=RateLimiterStoreAbstract_1,RateLimiterRes$a=RateLimiterRes_1,incrTtlLuaScript="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ";class RateLimiterRedis$1 extends RateLimiterStoreAbstract$4{constructor(t){super(t),this.client=t.storeClient,this._rejectIfRedisNotReady=!!t.rejectIfRedisNotReady,this.useRedisPackage=t.useRedisPackage,this.useRedis3AndLowerPackage=t.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:incrTtlLuaScript})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(t,r,n){let[o,a]=n;Array.isArray(o)&&([,o]=o,[,a]=a);const l=new RateLimiterRes$a;return l.consumedPoints=parseInt(o),l.isFirstInDuration=l.consumedPoints===r,l.remainingPoints=Math.max(this.points-l.consumedPoints,0),l.msBeforeNext=a,l}async _upsert(t,r,n,o=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");const a=Math.floor(n/1e3),l=this.client.multi();return o?(a>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.set(t,r,"EX",a):l.set(t,r,{EX:a}):l.set(t,r),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.pttl(t).exec(!0):l.pTTL(t).exec(!0)):a>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([t].concat([String(r),String(a)])):this.useRedis3AndLowerPackage?new Promise((c,u)=>{const _=function(b,x){return b?u(b):c(x)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(t,r,a,_):this.client.eval(incrTtlLuaScript,1,t,r,a,_)}):this.client.eval(incrTtlLuaScript,{keys:[t],arguments:[String(r),String(a)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.incrby(t,r).pttl(t).exec(!0):l.incrBy(t,r).pTTL(t).exec(!0)}async _get(t){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(t).pttl(t).exec().then(r=>{const[[,n]]=r;return n===null?null:r}):this.client.multi().get(t).pTTL(t).exec(!0).then(r=>{const[n]=r;return n===null?null:r})}_delete(t){return this.client.del(t).then(r=>r>0)}}var RateLimiterRedis_1=RateLimiterRedis$1;const RateLimiterStoreAbstract$3=RateLimiterStoreAbstract_1,RateLimiterRes$9=RateLimiterRes_1;function getDriverVersion(e){try{const t=e.client?e.client:e,{version:r}=t.topology.s.options.metadata.driver,n=r.split(".").map(o=>parseInt(o));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}class RateLimiterMongo$1 extends RateLimiterStoreAbstract$3{constructor(t){super(t),this.dbName=t.dbName,this.tableName=t.tableName,this.indexKeyPrefix=t.indexKeyPrefix,t.mongo?this.client=t.mongo:this.client=t.storeClient,typeof this.client.then=="function"?this.client.then(r=>{this.client=r,this._initCollection(),this._driverVersion=getDriverVersion(this.client)}):(this._initCollection(),this._driverVersion=getDriverVersion(this.client))}get dbName(){return this._dbName}set dbName(t){this._dbName=typeof t>"u"?RateLimiterMongo$1.getDbName():t}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(t){this._tableName=typeof t>"u"?this.keyPrefix:t}get client(){return this._client}set client(t){if(typeof t>"u")throw new Error("mongo is not set");this._client=t}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(t){this._indexKeyPrefix=t||{}}_initCollection(){const r=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);r.createIndex({expire:-1},{expireAfterSeconds:0}),r.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=r}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$9;let a;return typeof n.value>"u"?a=n:a=n.value,o.isFirstInDuration=a.points===r,o.consumedPoints=a.points,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=a.expire!==null?Math.max(new Date(a.expire).getTime()-Date.now(),0):-1,o}_upsert(t,r,n,o=!1,a={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const l=a.attrs||{};let c,u;o?(c={key:t},c=Object.assign(c,l),u={$set:{key:t,points:r,expire:n>0?new Date(Date.now()+n):null}},u.$set=Object.assign(u.$set,l)):(c={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:t},c=Object.assign(c,l),u={$setOnInsert:{key:t,expire:n>0?new Date(Date.now()+n):null},$inc:{points:r}},u.$setOnInsert=Object.assign(u.$setOnInsert,l));const _={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?_.returnDocument="after":_.returnOriginal=!1,new Promise((b,x)=>{this._collection.findOneAndUpdate(c,u,_).then(E=>{b(E)}).catch(E=>{if(E&&E.code===11e3){const I=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:t},l),k={$set:Object.assign({key:t,points:r,expire:n>0?new Date(Date.now()+n):null},l)};this._collection.findOneAndUpdate(I,k,_).then(T=>{b(T)}).catch(T=>{T&&T.code===11e3?this._upsert(t,r,n,o).then(O=>b(O)).catch(O=>x(O)):x(T)})}else x(E)})})}_get(t,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const n=r.attrs||{},o=Object.assign({key:t,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(o)}_delete(t,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const n=r.attrs||{},o=Object.assign({key:t},n);return this._collection.deleteOne(o).then(a=>a.deletedCount>0)}}var RateLimiterMongo_1=RateLimiterMongo$1;const RateLimiterStoreAbstract$2=RateLimiterStoreAbstract_1,RateLimiterRes$8=RateLimiterRes_1;class RateLimiterMySQL$1 extends RateLimiterStoreAbstract$2{constructor(t,r=null){super(t),this.client=t.storeClient,this.clientType=t.storeType,this.dbName=t.dbName,this.tableName=t.tableName,this.clearExpiredByTimeout=t.clearExpiredByTimeout,this.tableCreated=t.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}clearExpired(t){return new Promise(r=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,t],()=>{this._releaseConnection(n),r()})}).catch(()=>{r()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((t,r)=>{this.client.getConnection((n,o)=>{if(n)return r(n);t(o)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(t){switch(this.clientType){case"pool":return t.release();case"sequelize":return this.client.connectionManager.releaseConnection(t);case"knex":return this.client.client.releaseConnection(t);default:return!0}}_createDbAndTable(){return new Promise((t,r)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,o=>{if(o)return this._releaseConnection(n),r(o);n.query(this._getCreateTableStmt(),a=>{if(a)return this._releaseConnection(n),r(a);this._releaseConnection(n),t()})})}).catch(n=>{r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(t){if(typeof t>"u")if(this.client.constructor.name==="Connection")t="connection";else if(this.client.constructor.name==="Pool")t="pool";else if(this.client.constructor.name==="Sequelize")t="sequelize";else throw new Error("storeType is not defined");this._clientType=t.toLowerCase()}get dbName(){return this._dbName}set dbName(t){this._dbName=typeof t>"u"?"rtlmtrflx":t}get tableName(){return this._tableName}set tableName(t){this._tableName=typeof t>"u"?this.keyPrefix:t}get tableCreated(){return this._tableCreated}set tableCreated(t){this._tableCreated=typeof t>"u"?!1:!!t}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(t){this._clearExpiredByTimeout=typeof t>"u"?!0:Boolean(t)}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$8,[a]=n;return o.isFirstInDuration=r===a.points,o.consumedPoints=o.isFirstInDuration?r:a.points,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=a.expire?Math.max(a.expire-Date.now(),0):-1,o}_upsertTransaction(t,r,n,o,a){return new Promise((l,c)=>{t.query("BEGIN",u=>{if(u)return t.rollback(),c(u);const _=Date.now(),b=o>0?_+o:null;let x,E;a?(x=`INSERT INTO ??.?? VALUES (?, ?, ?) +`+c+t.substr(l+1),a=o-l-1,l=-1,++o}else(t[o]===" "||t[o]===" "||t[o]===",")&&(l=o);return t}function ltrim(e){return e.replace(/^\s+/,"")}var forge$a=forge$m,sha256$2=forge$a.sha256=forge$a.sha256||{};forge$a.md.sha256=forge$a.md.algorithms.sha256=sha256$2;sha256$2.create=function(){_initialized$2||_init$2();var e=null,t=forge$a.util.createBuffer(),r=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var o=n.messageLengthSize/4,a=0;a>>0,l>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=l[1],l[1]=l[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(o),_update$2(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var o=forge$a.util.createBuffer();o.putBytes(t.bytes());var a=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,l=a&n.blockLength-1;o.putBytes(_padding$2.substr(0,n.blockLength-l));for(var c,u,_=n.fullMessageLength[0]*8,b=0;b>>0,_+=u,o.putInt32(_>>>0),_=c>>>0;o.putInt32(_);var x={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};_update$2(x,r,o);var E=forge$a.util.createBuffer();return E.putInt32(x.h0),E.putInt32(x.h1),E.putInt32(x.h2),E.putInt32(x.h3),E.putInt32(x.h4),E.putInt32(x.h5),E.putInt32(x.h6),E.putInt32(x.h7),E},n};var _padding$2=null,_initialized$2=!1,_k$1=null;function _init$2(){_padding$2=String.fromCharCode(128),_padding$2+=forge$a.util.fillString(String.fromCharCode(0),64),_k$1=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],_initialized$2=!0}function _update$2(e,t,r){for(var n,o,a,l,c,u,_,b,x,E,I,k,T,O,$,D=r.length();D>=64;){for(_=0;_<16;++_)t[_]=r.getInt32();for(;_<64;++_)n=t[_-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,o=t[_-15],o=(o>>>7|o<<25)^(o>>>18|o<<14)^o>>>3,t[_]=n+t[_-7]+o+t[_-16]|0;for(b=e.h0,x=e.h1,E=e.h2,I=e.h3,k=e.h4,T=e.h5,O=e.h6,$=e.h7,_=0;_<64;++_)l=(k>>>6|k<<26)^(k>>>11|k<<21)^(k>>>25|k<<7),c=O^k&(T^O),a=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),u=b&x|E&(b^x),n=$+l+c+_k$1[_]+t[_],o=a+u,$=O,O=T,T=k,k=I+n>>>0,I=E,E=x,x=b,b=n+o>>>0;e.h0=e.h0+b|0,e.h1=e.h1+x|0,e.h2=e.h2+E|0,e.h3=e.h3+I|0,e.h4=e.h4+k|0,e.h5=e.h5+T|0,e.h6=e.h6+O|0,e.h7=e.h7+$|0,D-=64}}var forge$9=forge$m,_crypto$1=null;forge$9.util.isNodejs&&!forge$9.options.usePureJavaScript&&!process.versions["node-webkit"]&&(_crypto$1=require$$6);var prng=forge$9.prng=forge$9.prng||{};prng.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=new Array(32),o=0;o<32;++o)n[o]=r.create();t.pools=n,t.pool=0,t.generate=function(_,b){if(!b)return t.generateSync(_);var x=t.plugin.cipher,E=t.plugin.increment,I=t.plugin.formatKey,k=t.plugin.formatSeed,T=forge$9.util.createBuffer();t.key=null,O();function O($){if($)return b($);if(T.length()>=_)return b(null,T.getBytes(_));if(t.generated>1048575&&(t.key=null),t.key===null)return forge$9.util.nextTick(function(){a(O)});var D=x(t.key,t.seed);t.generated+=D.length,T.putBytes(D),t.key=I(x(t.key,E(t.seed))),t.seed=k(x(t.key,t.seed)),forge$9.util.setImmediate(O)}},t.generateSync=function(_){var b=t.plugin.cipher,x=t.plugin.increment,E=t.plugin.formatKey,I=t.plugin.formatSeed;t.key=null;for(var k=forge$9.util.createBuffer();k.length()<_;){t.generated>1048575&&(t.key=null),t.key===null&&l();var T=b(t.key,t.seed);t.generated+=T.length,k.putBytes(T),t.key=E(b(t.key,x(t.seed))),t.seed=I(b(t.key,t.seed))}return k.getBytes(_)};function a(_){if(t.pools[0].messageLength>=32)return c(),_();var b=32-t.pools[0].messageLength<<5;t.seedFile(b,function(x,E){if(x)return _(x);t.collect(E),c(),_()})}function l(){if(t.pools[0].messageLength>=32)return c();var _=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(_)),c()}function c(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var _=t.plugin.md.create();_.update(t.keyBytes);for(var b=1,x=0;x<32;++x)t.reseeds%b===0&&(_.update(t.pools[x].digest().getBytes()),t.pools[x].start()),b=b<<1;t.keyBytes=_.digest().getBytes(),_.start(),_.update(t.keyBytes);var E=_.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(E),t.generated=0}function u(_){var b=null,x=forge$9.util.globalScope,E=x.crypto||x.msCrypto;E&&E.getRandomValues&&(b=function(ie){return E.getRandomValues(ie)});var I=forge$9.util.createBuffer();if(b)for(;I.length()<_;){var k=Math.max(1,Math.min(_-I.length(),65536)/4),T=new Uint32Array(Math.floor(k));try{b(T);for(var O=0;O>16),D+=($&32767)<<16,D+=$>>15,D=(D&2147483647)+(D>>31),H=D&4294967295;for(var O=0;O<3;++O)N=H>>>(O<<3),N^=Math.floor(Math.random()*256),I.putByte(N&255)}return I.getBytes(_)}return _crypto$1?(t.seedFile=function(_,b){_crypto$1.randomBytes(_,function(x,E){if(x)return b(x);b(null,E.toString())})},t.seedFileSync=function(_){return _crypto$1.randomBytes(_).toString()}):(t.seedFile=function(_,b){try{b(null,u(_))}catch(x){b(x)}},t.seedFileSync=u),t.collect=function(_){for(var b=_.length,x=0;x>E&255);t.collect(x)},t.registerWorker=function(_){if(_===self)t.seedFile=function(x,E){function I(k){var T=k.data;T.forge&&T.forge.prng&&(self.removeEventListener("message",I),E(T.forge.prng.err,T.forge.prng.bytes))}self.addEventListener("message",I),self.postMessage({forge:{prng:{needed:x}}})};else{var b=function(x){var E=x.data;E.forge&&E.forge.prng&&t.seedFile(E.forge.prng.needed,function(I,k){_.postMessage({forge:{prng:{err:I,bytes:k}}})})};_.addEventListener("message",b)}},t};var forge$8=forge$m;(function(){forge$8.random&&forge$8.random.getBytes||function(e){var t={},r=new Array(4),n=forge$8.util.createBuffer();t.formatKey=function(x){var E=forge$8.util.createBuffer(x);return x=new Array(4),x[0]=E.getInt32(),x[1]=E.getInt32(),x[2]=E.getInt32(),x[3]=E.getInt32(),forge$8.aes._expandKey(x,!1)},t.formatSeed=function(x){var E=forge$8.util.createBuffer(x);return x=new Array(4),x[0]=E.getInt32(),x[1]=E.getInt32(),x[2]=E.getInt32(),x[3]=E.getInt32(),x},t.cipher=function(x,E){return forge$8.aes._updateBlock(x,E,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},t.increment=function(x){return++x[3],x},t.md=forge$8.md.sha256;function o(){var x=forge$8.prng.create(t);return x.getBytes=function(E,I){return x.generate(E,I)},x.getBytesSync=function(E){return x.generate(E)},x}var a=o(),l=null,c=forge$8.util.globalScope,u=c.crypto||c.msCrypto;if(u&&u.getRandomValues&&(l=function(x){return u.getRandomValues(x)}),!forge$8.util.isNodejs&&!l){if(a.collectInt(+new Date,32),typeof navigator<"u"){var _="";for(var b in navigator)try{typeof navigator[b]=="string"&&(_+=navigator[b])}catch{}a.collect(_),_=null}e&&(e().mousemove(function(x){a.collectInt(x.clientX,16),a.collectInt(x.clientY,16)}),e().keypress(function(x){a.collectInt(x.charCode,8)}))}if(!forge$8.random)forge$8.random=a;else for(var b in a)forge$8.random[b]=a[b];forge$8.random.createInstance=o}(typeof jQuery<"u"?jQuery:null)})();var forge$7=forge$m,piTable=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s$4=[1,2,3,5],rol=function(e,t){return e<>16-t},ror=function(e,t){return(e&65535)>>t|e<<16-t&65535};forge$7.rc2=forge$7.rc2||{};forge$7.rc2.expandKey=function(e,t){typeof e=="string"&&(e=forge$7.util.createBuffer(e)),t=t||128;var r=e,n=e.length(),o=t,a=Math.ceil(o/8),l=255>>(o&7),c;for(c=n;c<128;c++)r.putByte(piTable[r.at(c-1)+r.at(c-n)&255]);for(r.setAt(128-a,piTable[r.at(128-a)&l]),c=127-a;c>=0;c--)r.setAt(c,piTable[r.at(c+1)^r.at(c+a)]);return r};var createCipher=function(e,t,r){var n=!1,o=null,a=null,l=null,c,u,_,b,x=[];for(e=forge$7.rc2.expandKey(e,t),_=0;_<64;_++)x.push(e.getInt16Le());r?(c=function(k){for(_=0;_<4;_++)k[_]+=x[b]+(k[(_+3)%4]&k[(_+2)%4])+(~k[(_+3)%4]&k[(_+1)%4]),k[_]=rol(k[_],s$4[_]),b++},u=function(k){for(_=0;_<4;_++)k[_]+=x[k[(_+3)%4]&63]}):(c=function(k){for(_=3;_>=0;_--)k[_]=ror(k[_],s$4[_]),k[_]-=x[b]+(k[(_+3)%4]&k[(_+2)%4])+(~k[(_+3)%4]&k[(_+1)%4]),b--},u=function(k){for(_=3;_>=0;_--)k[_]-=x[k[(_+3)%4]&63]});var E=function(k){var T=[];for(_=0;_<4;_++){var O=o.getInt16Le();l!==null&&(r?O^=l.getInt16Le():l.putInt16Le(O)),T.push(O&65535)}b=r?0:63;for(var $=0;$=8;)E([[5,c],[1,u],[6,c],[1,u],[5,c]])},finish:function(k){var T=!0;if(r)if(k)T=k(8,o,!r);else{var O=o.length()===8?8:8-o.length();o.fillWithByte(O,O)}if(T&&(n=!0,I.update()),!r&&(T=o.length()===0,T))if(k)T=k(8,a,!r);else{var $=a.length(),D=a.at($-1);D>$?T=!1:a.truncate(D)}return T}},I};forge$7.rc2.startEncrypting=function(e,t,r){var n=forge$7.rc2.createEncryptionCipher(e,128);return n.start(t,r),n};forge$7.rc2.createEncryptionCipher=function(e,t){return createCipher(e,t,!0)};forge$7.rc2.startDecrypting=function(e,t,r){var n=forge$7.rc2.createDecryptionCipher(e,128);return n.start(t,r),n};forge$7.rc2.createDecryptionCipher=function(e,t){return createCipher(e,t,!1)};var forge$6=forge$m;forge$6.jsbn=forge$6.jsbn||{};var dbits;function BigInteger$2(e,t,r){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,r):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}forge$6.jsbn.BigInteger=BigInteger$2;function nbi(){return new BigInteger$2(null)}function am1(e,t,r,n,o,a){for(;--a>=0;){var l=t*this.data[e++]+r.data[n]+o;o=Math.floor(l/67108864),r.data[n++]=l&67108863}return o}function am2(e,t,r,n,o,a){for(var l=t&32767,c=t>>15;--a>=0;){var u=this.data[e]&32767,_=this.data[e++]>>15,b=c*u+_*l;u=l*u+((b&32767)<<15)+r.data[n]+(o&1073741823),o=(u>>>30)+(b>>>15)+c*_+(o>>>30),r.data[n++]=u&1073741823}return o}function am3(e,t,r,n,o,a){for(var l=t&16383,c=t>>14;--a>=0;){var u=this.data[e]&16383,_=this.data[e++]>>14,b=c*u+_*l;u=l*u+((b&16383)<<14)+r.data[n]+o,o=(u>>28)+(b>>14)+c*_,r.data[n++]=u&268435455}return o}typeof navigator>"u"?(BigInteger$2.prototype.am=am3,dbits=28):navigator.appName=="Microsoft Internet Explorer"?(BigInteger$2.prototype.am=am2,dbits=30):navigator.appName!="Netscape"?(BigInteger$2.prototype.am=am1,dbits=26):(BigInteger$2.prototype.am=am3,dbits=28);BigInteger$2.prototype.DB=dbits;BigInteger$2.prototype.DM=(1<=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function bnpFromInt(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function nbv(e){var t=nbi();return t.fromInt(e),t}function bnpFromString(e,t){var r;if(t==16)r=4;else if(t==8)r=3;else if(t==256)r=8;else if(t==2)r=1;else if(t==32)r=5;else if(t==4)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var n=e.length,o=!1,a=0;--n>=0;){var l=r==8?e[n]&255:intAt(e,n);if(l<0){e.charAt(n)=="-"&&(o=!0);continue}o=!1,a==0?this.data[this.t++]=l:a+r>this.DB?(this.data[this.t-1]|=(l&(1<>this.DB-a):this.data[this.t-1]|=l<=this.DB&&(a-=this.DB)}r==8&&(e[0]&128)!=0&&(this.s=-1,a>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t}function bnToString(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var r=(1<0)for(c>c)>0&&(o=!0,a=int2char(n));l>=0;)c>(c+=this.DB-t)):(n=this.data[l]>>(c-=t)&r,c<=0&&(c+=this.DB,--l)),n>0&&(o=!0),o&&(a+=int2char(n));return o?a:"0"}function bnNegate(){var e=nbi();return BigInteger$2.ZERO.subTo(this,e),e}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(e){var t=this.s-e.s;if(t!=0)return t;var r=this.t;if(t=r-e.t,t!=0)return this.s<0?-t:t;for(;--r>=0;)if((t=this.data[r]-e.data[r])!=0)return t;return 0}function nbits(e){var t=1,r;return(r=e>>>16)!=0&&(e=r,t+=16),(r=e>>8)!=0&&(e=r,t+=8),(r=e>>4)!=0&&(e=r,t+=4),(r=e>>2)!=0&&(e=r,t+=2),(r=e>>1)!=0&&(e=r,t+=1),t}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function bnpDRShiftTo(e,t){for(var r=e;r=0;--c)t.data[c+a+1]=this.data[c]>>n|l,l=(this.data[c]&o)<=0;--c)t.data[c]=0;t.data[a]=l,t.t=this.t+a+1,t.s=this.s,t.clamp()}function bnpRShiftTo(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,o=this.DB-n,a=(1<>n;for(var l=r+1;l>n;n>0&&(t.data[this.t-r-1]|=(this.s&a)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()}function bnpMultiplyTo(e,t){var r=this.abs(),n=e.abs(),o=r.t;for(t.t=o+n.t;--o>=0;)t.data[o]=0;for(o=0;o=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function bnpDivRemTo(e,t,r){var n=e.abs();if(!(n.t<=0)){var o=this.abs();if(o.t0?(n.lShiftTo(u,a),o.lShiftTo(u,r)):(n.copyTo(a),o.copyTo(r));var _=a.t,b=a.data[_-1];if(b!=0){var x=b*(1<1?a.data[_-2]>>this.F2:0),E=this.FV/x,I=(1<=0&&(r.data[r.t++]=1,r.subTo($,r)),BigInteger$2.ONE.dlShiftTo(_,$),$.subTo(a,a);a.t<_;)a.data[a.t++]=0;for(;--O>=0;){var D=r.data[--T]==b?this.DM:Math.floor(r.data[T]*E+(r.data[T-1]+k)*I);if((r.data[T]+=a.am(0,D,r,O,0,_))0&&r.rShiftTo(u,r),l<0&&BigInteger$2.ZERO.subTo(r,r)}}}function bnMod(e){var t=nbi();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(BigInteger$2.ZERO)>0&&e.subTo(t,t),t}function Classic(e){this.m=e}function cConvert(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function cRevert(e){return e}function cReduce(e){e.divRemTo(this.m,null,e)}function cMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function cSqrTo(e,t){e.squareTo(t),this.reduce(t)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function Montgomery(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function montRevert(e){var t=nbi();return e.copyTo(t),this.reduce(t),t}function montReduce(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function montSqrTo(e,t){e.squareTo(t),this.reduce(t)}function montMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,t){if(e>4294967295||e<1)return BigInteger$2.ONE;var r=nbi(),n=nbi(),o=t.convert(this),a=nbits(e)-1;for(o.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,o,r);else{var l=r;r=n,n=l}return t.revert(r)}function bnModPowInt(e,t){var r;return e<256||t.isEven()?r=new Classic(t):r=new Montgomery(t),this.exp(e,r)}BigInteger$2.prototype.copyTo=bnpCopyTo;BigInteger$2.prototype.fromInt=bnpFromInt;BigInteger$2.prototype.fromString=bnpFromString;BigInteger$2.prototype.clamp=bnpClamp;BigInteger$2.prototype.dlShiftTo=bnpDLShiftTo;BigInteger$2.prototype.drShiftTo=bnpDRShiftTo;BigInteger$2.prototype.lShiftTo=bnpLShiftTo;BigInteger$2.prototype.rShiftTo=bnpRShiftTo;BigInteger$2.prototype.subTo=bnpSubTo;BigInteger$2.prototype.multiplyTo=bnpMultiplyTo;BigInteger$2.prototype.squareTo=bnpSquareTo;BigInteger$2.prototype.divRemTo=bnpDivRemTo;BigInteger$2.prototype.invDigit=bnpInvDigit;BigInteger$2.prototype.isEven=bnpIsEven;BigInteger$2.prototype.exp=bnpExp;BigInteger$2.prototype.toString=bnToString;BigInteger$2.prototype.negate=bnNegate;BigInteger$2.prototype.abs=bnAbs;BigInteger$2.prototype.compareTo=bnCompareTo;BigInteger$2.prototype.bitLength=bnBitLength;BigInteger$2.prototype.mod=bnMod;BigInteger$2.prototype.modPowInt=bnModPowInt;BigInteger$2.ZERO=nbv(0);BigInteger$2.ONE=nbv(1);function bnClone(){var e=nbi();return this.copyTo(e),e}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function bnSigNum(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function bnpToRadix(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=nbv(r),o=nbi(),a=nbi(),l="";for(this.divRemTo(n,o,a);o.signum()>0;)l=(r+a.intValue()).toString(e).substr(1)+l,o.divRemTo(n,o,a);return a.intValue().toString(e)+l}function bnpFromRadix(e,t){this.fromInt(0),t==null&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),o=!1,a=0,l=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(l,0),a=0,l=0)}a>0&&(this.dMultiply(Math.pow(t,a)),this.dAddOffset(l,0)),o&&BigInteger$2.ZERO.subTo(this,this)}function bnpFromNumber(e,t,r){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(BigInteger$2.ONE.shiftLeft(e-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(BigInteger$2.ONE.shiftLeft(e-1),this);else{var n=new Array,o=e&7;n.length=(e>>3)+1,t.nextBytes(n),o>0?n[0]&=(1<0)for(r>r)!=(this.s&this.DM)>>r&&(t[o++]=n|this.s<=0;)r<8?(n=(this.data[e]&(1<>(r+=this.DB-8)):(n=this.data[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),(n&128)!=0&&(n|=-256),o==0&&(this.s&128)!=(n&128)&&++o,(o>0||n!=this.s)&&(t[o++]=n);return t}function bnEquals(e){return this.compareTo(e)==0}function bnMin(e){return this.compareTo(e)<0?this:e}function bnMax(e){return this.compareTo(e)>0?this:e}function bnpBitwiseTo(e,t,r){var n,o,a=Math.min(e.t,this.t);for(n=0;n>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function bnGetLowestSetBit(){for(var e=0;e=this.t?this.s!=0:(this.data[t]&1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()}function bnAdd(e){var t=nbi();return this.addTo(e,t),t}function bnSubtract(e){var t=nbi();return this.subTo(e,t),t}function bnMultiply(e){var t=nbi();return this.multiplyTo(e,t),t}function bnDivide(e){var t=nbi();return this.divRemTo(e,t,null),t}function bnRemainder(e){var t=nbi();return this.divRemTo(e,null,t),t}function bnDivideAndRemainder(e){var t=nbi(),r=nbi();return this.divRemTo(e,t,r),new Array(t,r)}function bnpDMultiply(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function NullExp(){}function nNop(e){return e}function nMulTo(e,t,r){e.multiplyTo(t,r)}function nSqrTo(e,t){e.squareTo(t)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(e,t,r){var n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var o;for(o=r.t-this.t;n=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t}function barrettRevert(e){return e}function barrettReduce(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function barrettSqrTo(e,t){e.squareTo(t),this.reduce(t)}function barrettMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,t){var r=e.bitLength(),n,o=nbv(1),a;if(r<=0)return o;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?a=new Classic(t):t.isEven()?a=new Barrett(t):a=new Montgomery(t);var l=new Array,c=3,u=n-1,_=(1<1){var b=nbi();for(a.sqrTo(l[1],b);c<=_;)l[c]=nbi(),a.mulTo(b,l[c-2],l[c]),c+=2}var x=e.t-1,E,I=!0,k=nbi(),T;for(r=nbits(e.data[x])-1;x>=0;){for(r>=u?E=e.data[x]>>r-u&_:(E=(e.data[x]&(1<0&&(E|=e.data[x-1]>>this.DB+r-u)),c=n;(E&1)==0;)E>>=1,--c;if((r-=c)<0&&(r+=this.DB,--x),I)l[E].copyTo(o),I=!1;else{for(;c>1;)a.sqrTo(o,k),a.sqrTo(k,o),c-=2;c>0?a.sqrTo(o,k):(T=o,o=k,k=T),a.mulTo(k,l[E],o)}for(;x>=0&&(e.data[x]&1<0&&(t.rShiftTo(a,t),r.rShiftTo(a,r));t.signum()>0;)(o=t.getLowestSetBit())>0&&t.rShiftTo(o,t),(o=r.getLowestSetBit())>0&&r.rShiftTo(o,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return a>0&&r.lShiftTo(a,r),r}function bnpModInt(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(t==0)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r}function bnModInverse(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return BigInteger$2.ZERO;for(var r=e.clone(),n=this.clone(),o=nbv(1),a=nbv(0),l=nbv(0),c=nbv(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),t?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(e,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);for(;n.isEven();)n.rShiftTo(1,n),t?((!l.isEven()||!c.isEven())&&(l.addTo(this,l),c.subTo(e,c)),l.rShiftTo(1,l)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);r.compareTo(n)>=0?(r.subTo(n,r),t&&o.subTo(l,o),a.subTo(c,a)):(n.subTo(r,n),t&&l.subTo(o,l),c.subTo(a,c))}if(n.compareTo(BigInteger$2.ONE)!=0)return BigInteger$2.ZERO;if(c.compareTo(e)>=0)return c.subtract(e);if(c.signum()<0)c.addTo(e,c);else return c;return c.signum()<0?c.add(e):c}var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var t,r=this.abs();if(r.t==1&&r.data[0]<=lowprimes[lowprimes.length-1]){for(t=0;t=0);var c=a.modPow(n,this);if(c.compareTo(BigInteger$2.ONE)!=0&&c.compareTo(t)!=0){for(var u=1;u++>>0,l>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=l[1],l[1]=l[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(o),_update$1(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var o=forge$5.util.createBuffer();o.putBytes(t.bytes());var a=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,l=a&n.blockLength-1;o.putBytes(_padding$1.substr(0,n.blockLength-l));for(var c,u,_=n.fullMessageLength[0]*8,b=0;b>>0,_+=u,o.putInt32(_>>>0),_=c>>>0;o.putInt32(_);var x={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};_update$1(x,r,o);var E=forge$5.util.createBuffer();return E.putInt32(x.h0),E.putInt32(x.h1),E.putInt32(x.h2),E.putInt32(x.h3),E.putInt32(x.h4),E},n};var _padding$1=null,_initialized$1=!1;function _init$1(){_padding$1=String.fromCharCode(128),_padding$1+=forge$5.util.fillString(String.fromCharCode(0),64),_initialized$1=!0}function _update$1(e,t,r){for(var n,o,a,l,c,u,_,b,x=r.length();x>=64;){for(o=e.h0,a=e.h1,l=e.h2,c=e.h3,u=e.h4,b=0;b<16;++b)n=r.getInt32(),t[b]=n,_=c^a&(l^c),n=(o<<5|o>>>27)+_+u+1518500249+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<20;++b)n=t[b-3]^t[b-8]^t[b-14]^t[b-16],n=n<<1|n>>>31,t[b]=n,_=c^a&(l^c),n=(o<<5|o>>>27)+_+u+1518500249+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<32;++b)n=t[b-3]^t[b-8]^t[b-14]^t[b-16],n=n<<1|n>>>31,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+1859775393+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<40;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+1859775393+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<60;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a&l|c&(a^l),n=(o<<5|o>>>27)+_+u+2400959708+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;for(;b<80;++b)n=t[b-6]^t[b-16]^t[b-28]^t[b-32],n=n<<2|n>>>30,t[b]=n,_=a^l^c,n=(o<<5|o>>>27)+_+u+3395469782+n,u=c,c=l,l=(a<<30|a>>>2)>>>0,a=o,o=n;e.h0=e.h0+o|0,e.h1=e.h1+a|0,e.h2=e.h2+l|0,e.h3=e.h3+c|0,e.h4=e.h4+u|0,x-=64}}var forge$4=forge$m,pkcs1=forge$4.pkcs1=forge$4.pkcs1||{};pkcs1.encode_rsa_oaep=function(e,t,r){var n,o,a,l;typeof r=="string"?(n=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(n=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(l=r.mgf1.md)),a?a.start():a=forge$4.md.sha1.create(),l||(l=a);var c=Math.ceil(e.n.bitLength()/8),u=c-2*a.digestLength-2;if(t.length>u){var _=new Error("RSAES-OAEP input message length is too long.");throw _.length=t.length,_.maxLength=u,_}n||(n=""),a.update(n,"raw");for(var b=a.digest(),x="",E=u-t.length,I=0;I>24&255,a>>16&255,a>>8&255,a&255);r.start(),r.update(e+l),n+=r.digest().getBytes()}return n.substring(0,t)}var forge$3=forge$m;(function(){if(forge$3.prime)return;var e=forge$3.prime=forge$3.prime||{},t=forge$3.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new t(null);n.fromInt(30);var o=function(x,E){return x|E};e.generateProbablePrime=function(x,E,I){typeof E=="function"&&(I=E,E={}),E=E||{};var k=E.algorithm||"PRIMEINC";typeof k=="string"&&(k={name:k}),k.options=k.options||{};var T=E.prng||forge$3.random,O={nextBytes:function($){for(var D=T.getBytesSync($.length),N=0;N<$.length;++N)$[N]=D.charCodeAt(N)}};if(k.name==="PRIMEINC")return a(x,O,k.options,I);throw new Error("Invalid prime generation algorithm: "+k.name)};function a(x,E,I,k){return"workers"in I?u(x,E,I,k):l(x,E,I,k)}function l(x,E,I,k){var T=_(x,E),O=0,$=b(T.bitLength());"millerRabinTests"in I&&($=I.millerRabinTests);var D=10;"maxBlockTime"in I&&(D=I.maxBlockTime),c(T,x,E,O,$,D,k)}function c(x,E,I,k,T,O,$){var D=+new Date;do{if(x.bitLength()>E&&(x=_(E,I)),x.isProbablePrime(T))return $(null,x);x.dAddOffset(r[k++%8],0)}while(O<0||+new Date-D"u")return l(x,E,I,k);var T=_(x,E),O=I.workers,$=I.workLoad||100,D=$*30/8,N=I.workerScript||"forge/prime.worker.js";if(O===-1)return forge$3.util.estimateCores(function(ie,ue){ie&&(ue=2),O=ue-1,H()});H();function H(){O=Math.max(1,O);for(var ie=[],ue=0;uex&&(T=_(x,E));var he=T.toString(16);ce.target.postMessage({hex:he,workLoad:$}),T.dAddOffset(D,0)}}}}function _(x,E){var I=new t(x,E),k=x-1;return I.testBit(k)||I.bitwiseTo(t.ONE.shiftLeft(k),o,I),I.dAddOffset(31-I.mod(n).byteValue(),0),I}function b(x){return x<=100?27:x<=150?18:x<=200?15:x<=250?12:x<=300?9:x<=350?8:x<=400?7:x<=500?6:x<=600?5:x<=800?4:x<=1250?3:2}})();var forge$2=forge$m;if(typeof BigInteger$1>"u")var BigInteger$1=forge$2.jsbn.BigInteger;var _crypto=forge$2.util.isNodejs?require$$6:null,asn1$1=forge$2.asn1,util$5=forge$2.util;forge$2.pki=forge$2.pki||{};forge$2.pki.rsa=forge$2.rsa=forge$2.rsa||{};var pki$1=forge$2.pki,GCD_30_DELTA=[6,4,2,4,2,4,6,2],privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},publicKeyValidator=forge$2.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},digestInfoValidator={name:"DigestInfo",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:asn1$1.Class.UNIVERSAL,type:asn1$1.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},emsaPkcs1v15encode=function(e){var t;if(e.algorithm in pki$1.oids)t=pki$1.oids[e.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=asn1$1.oidToDer(t).getBytes(),o=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[]),a=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[]);a.value.push(asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,n)),a.value.push(asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,""));var l=asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OCTETSTRING,!1,e.digest().getBytes());return o.value.push(a),o.value.push(l),asn1$1.toDer(o).getBytes()},_modPow=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(BigInteger$1.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(BigInteger$1.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var n;do n=new BigInteger$1(forge$2.util.bytesToHex(forge$2.random.getBytes(t.n.bitLength()/8)),16);while(n.compareTo(t.n)>=0||!n.gcd(t.n).equals(BigInteger$1.ONE));e=e.multiply(n.modPow(t.e,t.n)).mod(t.n);for(var o=e.mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var l=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return l=l.multiply(n.modInverse(t.n)).mod(t.n),l};pki$1.rsa.encrypt=function(e,t,r){var n=r,o,a=Math.ceil(t.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,o=_encodePkcs1_v1_5(e,t,r)):(o=forge$2.util.createBuffer(),o.putBytes(e));for(var l=new BigInteger$1(o.toHex(),16),c=_modPow(l,t,n),u=c.toString(16),_=forge$2.util.createBuffer(),b=a-Math.ceil(u.length/2);b>0;)_.putByte(0),--b;return _.putBytes(forge$2.util.hexToBytes(u)),_.getBytes()};pki$1.rsa.decrypt=function(e,t,r,n){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var l=new BigInteger$1(forge$2.util.createBuffer(e).toHex(),16);if(l.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var c=_modPow(l,t,r),u=c.toString(16),_=forge$2.util.createBuffer(),b=o-Math.ceil(u.length/2);b>0;)_.putByte(0),--b;return _.putBytes(forge$2.util.hexToBytes(u)),n!==!1?_decodePkcs1_v1_5(_.getBytes(),t,r):_.getBytes()};pki$1.rsa.createKeyPairGenerationState=function(e,t,r){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,r=r||{};var n=r.prng||forge$2.random,o={nextBytes:function(c){for(var u=n.getBytesSync(c.length),_=0;_>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},l.e.fromInt(l.eInt);else throw new Error("Invalid key generation algorithm: "+a);return l};pki$1.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new BigInteger$1(null);r.fromInt(30);for(var n=0,o=function(x,E){return x|E},a=+new Date,l,c=0;e.keys===null&&(t<=0||cu?e.pqState=0:e.num.isProbablePrime(_getMillerRabinTests(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(GCD_30_DELTA[n++%8],0):e.pqState===2?e.pqState=e.num.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(BigInteger$1.ONE),e.q1=e.q.subtract(BigInteger$1.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(BigInteger$1.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var b=e.e.modInverse(e.phi);e.keys={privateKey:pki$1.rsa.setPrivateKey(e.n,e.e,b,e.p,e.q,b.mod(e.p1),b.mod(e.q1),e.q.modInverse(e.p)),publicKey:pki$1.rsa.setPublicKey(e.n,e.e)}}l=+new Date,c+=l-a,a=l}return e.keys!==null};pki$1.rsa.generateKeyPair=function(e,t,r,n){if(arguments.length===1?typeof e=="object"?(r=e,e=void 0):typeof e=="function"&&(n=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(n=t,t=void 0):typeof t!="number"&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},e===void 0&&(e=r.bits||2048),t===void 0&&(t=r.e||65537),!r.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(n){if(_detectNodeCrypto("generateKeyPair"))return _crypto.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(c,u,_){if(c)return n(c);n(null,{privateKey:pki$1.privateKeyFromPem(_),publicKey:pki$1.publicKeyFromPem(u)})});if(_detectSubtleCrypto("generateKey")&&_detectSubtleCrypto("exportKey"))return util$5.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_intToUint8Array(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(c){return util$5.globalScope.crypto.subtle.exportKey("pkcs8",c.privateKey)}).then(void 0,function(c){n(c)}).then(function(c){if(c){var u=pki$1.privateKeyFromAsn1(asn1$1.fromDer(forge$2.util.createBuffer(c)));n(null,{privateKey:u,publicKey:pki$1.setRsaPublicKey(u.n,u.e)})}});if(_detectSubtleMsCrypto("generateKey")&&_detectSubtleMsCrypto("exportKey")){var o=util$5.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_intToUint8Array(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);o.oncomplete=function(c){var u=c.target.result,_=util$5.globalScope.msCrypto.subtle.exportKey("pkcs8",u.privateKey);_.oncomplete=function(b){var x=b.target.result,E=pki$1.privateKeyFromAsn1(asn1$1.fromDer(forge$2.util.createBuffer(x)));n(null,{privateKey:E,publicKey:pki$1.setRsaPublicKey(E.n,E.e)})},_.onerror=function(b){n(b)}},o.onerror=function(c){n(c)};return}}else if(_detectNodeCrypto("generateKeyPairSync")){var a=_crypto.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:pki$1.privateKeyFromPem(a.privateKey),publicKey:pki$1.publicKeyFromPem(a.publicKey)}}}var l=pki$1.rsa.createKeyPairGenerationState(e,t,r);if(!n)return pki$1.rsa.stepKeyPairGenerationState(l,0),l.keys;_generateKeyPair(l,r,n)};pki$1.setRsaPublicKey=pki$1.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(n,o,a){if(typeof o=="string"?o=o.toUpperCase():o===void 0&&(o="RSAES-PKCS1-V1_5"),o==="RSAES-PKCS1-V1_5")o={encode:function(c,u,_){return _encodePkcs1_v1_5(c,u,2).getBytes()}};else if(o==="RSA-OAEP"||o==="RSAES-OAEP")o={encode:function(c,u){return forge$2.pkcs1.encode_rsa_oaep(u,c,a)}};else if(["RAW","NONE","NULL",null].indexOf(o)!==-1)o={encode:function(c){return c}};else if(typeof o=="string")throw new Error('Unsupported encryption scheme: "'+o+'".');var l=o.encode(n,r,!0);return pki$1.rsa.encrypt(l,r,!0)},r.verify=function(n,o,a,l){typeof a=="string"?a=a.toUpperCase():a===void 0&&(a="RSASSA-PKCS1-V1_5"),l===void 0&&(l={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in l||(l._parseAllDigestBytes=!0),a==="RSASSA-PKCS1-V1_5"?a={verify:function(u,_){_=_decodePkcs1_v1_5(_,r,!0);var b=asn1$1.fromDer(_,{parseAllBytes:l._parseAllDigestBytes}),x={},E=[];if(!asn1$1.validate(b,digestInfoValidator,x,E)){var I=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw I.errors=E,I}var k=asn1$1.derToOid(x.algorithmIdentifier);if(!(k===forge$2.oids.md2||k===forge$2.oids.md5||k===forge$2.oids.sha1||k===forge$2.oids.sha224||k===forge$2.oids.sha256||k===forge$2.oids.sha384||k===forge$2.oids.sha512||k===forge$2.oids["sha512-224"]||k===forge$2.oids["sha512-256"])){var I=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw I.oid=k,I}if((k===forge$2.oids.md2||k===forge$2.oids.md5)&&!("parameters"in x))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return u===x.digest}}:(a==="NONE"||a==="NULL"||a===null)&&(a={verify:function(u,_){return _=_decodePkcs1_v1_5(_,r,!0),u===_}});var c=pki$1.rsa.decrypt(o,r,!0,!1);return a.verify(n,c,r.n.bitLength())},r};pki$1.setRsaPrivateKey=pki$1.rsa.setPrivateKey=function(e,t,r,n,o,a,l,c){var u={n:e,e:t,d:r,p:n,q:o,dP:a,dQ:l,qInv:c};return u.decrypt=function(_,b,x){typeof b=="string"?b=b.toUpperCase():b===void 0&&(b="RSAES-PKCS1-V1_5");var E=pki$1.rsa.decrypt(_,u,!1,!1);if(b==="RSAES-PKCS1-V1_5")b={decode:_decodePkcs1_v1_5};else if(b==="RSA-OAEP"||b==="RSAES-OAEP")b={decode:function(I,k){return forge$2.pkcs1.decode_rsa_oaep(k,I,x)}};else if(["RAW","NONE","NULL",null].indexOf(b)!==-1)b={decode:function(I){return I}};else throw new Error('Unsupported encryption scheme: "'+b+'".');return b.decode(E,u,!1)},u.sign=function(_,b){var x=!1;typeof b=="string"&&(b=b.toUpperCase()),b===void 0||b==="RSASSA-PKCS1-V1_5"?(b={encode:emsaPkcs1v15encode},x=1):(b==="NONE"||b==="NULL"||b===null)&&(b={encode:function(){return _}},x=1);var E=b.encode(_,u.n.bitLength());return pki$1.rsa.encrypt(E,u,x)},u};pki$1.wrapRsaPrivateKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,asn1$1.integerToDer(0).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,asn1$1.oidToDer(pki$1.oids.rsaEncryption).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,"")]),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OCTETSTRING,!1,asn1$1.toDer(e).getBytes())])};pki$1.privateKeyFromAsn1=function(e){var t={},r=[];if(asn1$1.validate(e,privateKeyValidator,t,r)&&(e=asn1$1.fromDer(forge$2.util.createBuffer(t.privateKey))),t={},r=[],!asn1$1.validate(e,rsaPrivateKeyValidator,t,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var o,a,l,c,u,_,b,x;return o=forge$2.util.createBuffer(t.privateKeyModulus).toHex(),a=forge$2.util.createBuffer(t.privateKeyPublicExponent).toHex(),l=forge$2.util.createBuffer(t.privateKeyPrivateExponent).toHex(),c=forge$2.util.createBuffer(t.privateKeyPrime1).toHex(),u=forge$2.util.createBuffer(t.privateKeyPrime2).toHex(),_=forge$2.util.createBuffer(t.privateKeyExponent1).toHex(),b=forge$2.util.createBuffer(t.privateKeyExponent2).toHex(),x=forge$2.util.createBuffer(t.privateKeyCoefficient).toHex(),pki$1.setRsaPrivateKey(new BigInteger$1(o,16),new BigInteger$1(a,16),new BigInteger$1(l,16),new BigInteger$1(c,16),new BigInteger$1(u,16),new BigInteger$1(_,16),new BigInteger$1(b,16),new BigInteger$1(x,16))};pki$1.privateKeyToAsn1=pki$1.privateKeyToRSAPrivateKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,asn1$1.integerToDer(0).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.n)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.e)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.d)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.p)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.q)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.dP)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.dQ)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.qInv))])};pki$1.publicKeyFromAsn1=function(e){var t={},r=[];if(asn1$1.validate(e,publicKeyValidator,t,r)){var n=asn1$1.derToOid(t.publicKeyOid);if(n!==pki$1.oids.rsaEncryption){var o=new Error("Cannot read public key. Unknown OID.");throw o.oid=n,o}e=t.rsaPublicKey}if(r=[],!asn1$1.validate(e,rsaPublicKeyValidator,t,r)){var o=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw o.errors=r,o}var a=forge$2.util.createBuffer(t.publicKeyModulus).toHex(),l=forge$2.util.createBuffer(t.publicKeyExponent).toHex();return pki$1.setRsaPublicKey(new BigInteger$1(a,16),new BigInteger$1(l,16))};pki$1.publicKeyToAsn1=pki$1.publicKeyToSubjectPublicKeyInfo=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.OID,!1,asn1$1.oidToDer(pki$1.oids.rsaEncryption).getBytes()),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.NULL,!1,"")]),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.BITSTRING,!1,[pki$1.publicKeyToRSAPublicKey(e)])])};pki$1.publicKeyToRSAPublicKey=function(e){return asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.SEQUENCE,!0,[asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.n)),asn1$1.create(asn1$1.Class.UNIVERSAL,asn1$1.Type.INTEGER,!1,_bnToBytes(e.e))])};function _encodePkcs1_v1_5(e,t,r){var n=forge$2.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var a=new Error("Message is too long for PKCS#1 v1.5 padding.");throw a.length=e.length,a.max=o-11,a}n.putByte(0),n.putByte(r);var l=o-3-e.length,c;if(r===0||r===1){c=r===0?0:255;for(var u=0;u0;){for(var _=0,b=forge$2.random.getBytes(l),u=0;u"u")throw new Error("Encryption block is invalid.");var u=0;if(c===0){u=o-3-n;for(var _=0;_1;){if(a.getByte()!==255){--a.read;break}++u}else if(c===2)for(u=0;a.length()>1;){if(a.getByte()===0){--a.read;break}++u}var b=a.getByte();if(b!==0||u!==o-3-a.length())throw new Error("Encryption block is invalid.");return a.getBytes()}function _generateKeyPair(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(n.prng=t.prng),o();function o(){a(e.pBits,function(c,u){if(c)return r(c);if(e.p=u,e.q!==null)return l(c,e.q);a(e.qBits,l)})}function a(c,u){forge$2.prime.generateProbablePrime(c,n,u)}function l(c,u){if(c)return r(c);if(e.q=u,e.p.compareTo(e.q)<0){var _=e.p;e.p=e.q,e.q=_}if(e.p.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.p=null,o();return}if(e.q.subtract(BigInteger$1.ONE).gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.q=null,a(e.qBits,l);return}if(e.p1=e.p.subtract(BigInteger$1.ONE),e.q1=e.q.subtract(BigInteger$1.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(BigInteger$1.ONE)!==0){e.p=e.q=null,o();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,a(e.qBits,l);return}var b=e.e.modInverse(e.phi);e.keys={privateKey:pki$1.rsa.setPrivateKey(e.n,e.e,b,e.p,e.q,b.mod(e.p1),b.mod(e.q1),e.q.modInverse(e.p)),publicKey:pki$1.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}}function _bnToBytes(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=forge$2.util.hexToBytes(t);return r.length>1&&(r.charCodeAt(0)===0&&(r.charCodeAt(1)&128)===0||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function _getMillerRabinTests(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function _detectNodeCrypto(e){return forge$2.util.isNodejs&&typeof _crypto[e]=="function"}function _detectSubtleCrypto(e){return typeof util$5.globalScope<"u"&&typeof util$5.globalScope.crypto=="object"&&typeof util$5.globalScope.crypto.subtle=="object"&&typeof util$5.globalScope.crypto.subtle[e]=="function"}function _detectSubtleMsCrypto(e){return typeof util$5.globalScope<"u"&&typeof util$5.globalScope.msCrypto=="object"&&typeof util$5.globalScope.msCrypto.subtle=="object"&&typeof util$5.globalScope.msCrypto.subtle[e]=="function"}function _intToUint8Array(e){for(var t=forge$2.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n"u")var BigInteger=forge$1.jsbn.BigInteger;var asn1=forge$1.asn1,pki=forge$1.pki=forge$1.pki||{};pki.pbe=forge$1.pbe=forge$1.pbe||{};var oids=pki.oids,encryptedPrivateKeyValidator={name:"EncryptedPrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},PBES2AlgorithmsValidator={name:"PBES2Algorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},pkcs12PbeParamsValidator={name:"pkcs-12PbeParams",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"iterations"}]};pki.encryptPrivateKeyInfo=function(e,t,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var n=forge$1.random.getBytesSync(r.saltSize),o=r.count,a=asn1.integerToDer(o),l,c,u;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var _,b,x;switch(r.algorithm){case"aes128":l=16,_=16,b=oids["aes128-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"aes192":l=24,_=16,b=oids["aes192-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"aes256":l=32,_=16,b=oids["aes256-CBC"],x=forge$1.aes.createEncryptionCipher;break;case"des":l=8,_=8,b=oids.desCBC,x=forge$1.des.createEncryptionCipher;break;default:var E=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw E.algorithm=r.algorithm,E}var I="hmacWith"+r.prfAlgorithm.toUpperCase(),k=prfAlgorithmToMessageDigest(I),T=forge$1.pkcs5.pbkdf2(t,n,o,l,k),O=forge$1.random.getBytesSync(_),$=x(T);$.start(O),$.update(asn1.toDer(e)),$.finish(),u=$.output.getBytes();var D=createPbkdf2Params(n,a,l,I);c=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBES2).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBKDF2).getBytes()),D]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(b).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,O)])])])}else if(r.algorithm==="3des"){l=24;var N=new forge$1.util.ByteBuffer(n),T=pki.pbe.generatePkcs12Key(t,N,1,o,l),O=pki.pbe.generatePkcs12Key(t,N,2,o,l),$=forge$1.des.createEncryptionCipher(T);$.start(O),$.update(asn1.toDer(e)),$.finish(),u=$.output.getBytes(),c=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,n),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,a.getBytes())])])}else{var E=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw E.algorithm=r.algorithm,E}var H=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[c,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,u)]);return H};pki.decryptPrivateKeyInfo=function(e,t){var r=null,n={},o=[];if(!asn1.validate(e,encryptedPrivateKeyValidator,n,o)){var a=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}var l=asn1.derToOid(n.encryptionOid),c=pki.pbe.getCipher(l,n.encryptionParams,t),u=forge$1.util.createBuffer(n.encryptedData);return c.update(u),c.finish()&&(r=asn1.fromDer(c.output)),r};pki.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:asn1.toDer(e).getBytes()};return forge$1.pem.encode(r,{maxline:t})};pki.encryptedPrivateKeyFromPem=function(e){var t=forge$1.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return asn1.fromDer(t.body)};pki.encryptRsaPrivateKey=function(e,t,r){if(r=r||{},!r.legacy){var n=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(e));return n=pki.encryptPrivateKeyInfo(n,t,r),pki.encryptedPrivateKeyToPem(n)}var o,a,l,c;switch(r.algorithm){case"aes128":o="AES-128-CBC",l=16,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"aes192":o="AES-192-CBC",l=24,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"aes256":o="AES-256-CBC",l=32,a=forge$1.random.getBytesSync(16),c=forge$1.aes.createEncryptionCipher;break;case"3des":o="DES-EDE3-CBC",l=24,a=forge$1.random.getBytesSync(8),c=forge$1.des.createEncryptionCipher;break;case"des":o="DES-CBC",l=8,a=forge$1.random.getBytesSync(8),c=forge$1.des.createEncryptionCipher;break;default:var u=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw u.algorithm=r.algorithm,u}var _=forge$1.pbe.opensslDeriveBytes(t,a.substr(0,8),l),b=c(_);b.start(a),b.update(asn1.toDer(pki.privateKeyToAsn1(e))),b.finish();var x={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:o,parameters:forge$1.util.bytesToHex(a).toUpperCase()},body:b.output.getBytes()};return forge$1.pem.encode(x)};pki.decryptRsaPrivateKey=function(e,t){var r=null,n=forge$1.pem.decode(e)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var o=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw o.headerType=o,o}if(n.procType&&n.procType.type==="ENCRYPTED"){var a,l;switch(n.dekInfo.algorithm){case"DES-CBC":a=8,l=forge$1.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,l=forge$1.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,l=forge$1.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,l=forge$1.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,l=forge$1.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,l=function(x){return forge$1.rc2.createDecryptionCipher(x,40)};break;case"RC2-64-CBC":a=8,l=function(x){return forge$1.rc2.createDecryptionCipher(x,64)};break;case"RC2-128-CBC":a=16,l=function(x){return forge$1.rc2.createDecryptionCipher(x,128)};break;default:var o=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw o.algorithm=n.dekInfo.algorithm,o}var c=forge$1.util.hexToBytes(n.dekInfo.parameters),u=forge$1.pbe.opensslDeriveBytes(t,c.substr(0,8),a),_=l(u);if(_.start(c),_.update(forge$1.util.createBuffer(n.body)),_.finish())r=_.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=pki.decryptPrivateKeyInfo(asn1.fromDer(r),t):r=asn1.fromDer(r),r!==null&&(r=pki.privateKeyFromAsn1(r)),r};pki.pbe.generatePkcs12Key=function(e,t,r,n,o,a){var l,c;if(typeof a>"u"||a===null){if(!("sha1"in forge$1.md))throw new Error('"sha1" hash algorithm unavailable.');a=forge$1.md.sha1.create()}var u=a.digestLength,_=a.blockLength,b=new forge$1.util.ByteBuffer,x=new forge$1.util.ByteBuffer;if(e!=null){for(c=0;c=0;c--)he=he>>8,he+=le.at(c)+ee.at(c),ee.setAt(c,he&255);ve.putBuffer(ee)}N=ve,b.putBuffer(ue)}return b.truncate(b.length()-o),b};pki.pbe.getCipher=function(e,t,r){switch(e){case pki.oids.pkcs5PBES2:return pki.pbe.getCipherForPBES2(e,t,r);case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:return pki.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};pki.pbe.getCipherForPBES2=function(e,t,r){var n={},o=[];if(!asn1.validate(t,PBES2AlgorithmsValidator,n,o)){var a=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}if(e=asn1.derToOid(n.kdfOid),e!==pki.oids.pkcs5PBKDF2){var a=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw a.oid=e,a.supportedOids=["pkcs5PBKDF2"],a}if(e=asn1.derToOid(n.encOid),e!==pki.oids["aes128-CBC"]&&e!==pki.oids["aes192-CBC"]&&e!==pki.oids["aes256-CBC"]&&e!==pki.oids["des-EDE3-CBC"]&&e!==pki.oids.desCBC){var a=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw a.oid=e,a.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],a}var l=n.kdfSalt,c=forge$1.util.createBuffer(n.kdfIterationCount);c=c.getInt(c.length()<<3);var u,_;switch(pki.oids[e]){case"aes128-CBC":u=16,_=forge$1.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,_=forge$1.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,_=forge$1.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,_=forge$1.des.createDecryptionCipher;break;case"desCBC":u=8,_=forge$1.des.createDecryptionCipher;break}var b=prfOidToMessageDigest(n.prfOid),x=forge$1.pkcs5.pbkdf2(r,l,c,u,b),E=n.encIv,I=_(x);return I.start(E),I};pki.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},o=[];if(!asn1.validate(t,pkcs12PbeParamsValidator,n,o)){var a=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=o,a}var l=forge$1.util.createBuffer(n.salt),c=forge$1.util.createBuffer(n.iterations);c=c.getInt(c.length()<<3);var u,_,b;switch(e){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:u=24,_=8,b=forge$1.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:u=5,_=8,b=function(T,O){var $=forge$1.rc2.createDecryptionCipher(T,40);return $.start(O,null),$};break;default:var a=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw a.oid=e,a}var x=prfOidToMessageDigest(n.prfOid),E=pki.pbe.generatePkcs12Key(r,l,1,c,u,x);x.start();var I=pki.pbe.generatePkcs12Key(r,l,2,c,_,x);return b(E,I)};pki.pbe.opensslDeriveBytes=function(e,t,r,n){if(typeof n>"u"||n===null){if(!("md5"in forge$1.md))throw new Error('"md5" hash algorithm unavailable.');n=forge$1.md.md5.create()}t===null&&(t="");for(var o=[hash(n,e+t)],a=16,l=1;a=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,H=new Uint8Array(N);$!==D;){for(var ie=k[$],ue=0,de=N-1;(ie!==0||ue>>0,H[de]=ie%c>>>0,ie=ie/c>>>0;if(ie!==0)throw new Error("Non-zero carry");O=ue,$++}for(var le=N-O;le!==N&&H[le]===0;)le++;for(var ce=u.repeat(T);le>>0,N=new Uint8Array(D);k[T];){var H=r[k.charCodeAt(T)];if(H===255)return;for(var ie=0,ue=D-1;(H!==0||ie<$)&&ue!==-1;ue--,ie++)H+=c*N[ue]>>>0,N[ue]=H%256>>>0,H=H/256>>>0;if(H!==0)throw new Error("Non-zero carry");$=ie,T++}if(k[T]!==" "){for(var de=D-$;de!==D&&N[de]===0;)de++;for(var le=new Uint8Array(O+(D-de)),ce=O;de!==D;)le[ce++]=N[de++];return le}}}function I(k){var T=E(k);if(T)return T;throw new Error(`Non-${t} character`)}return{encode:x,decodeUnsafe:E,decode:I}}var src$3=base$4,_brrp__multiformats_scope_baseX$1=src$3;const equals$1=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},fromString$2=e=>new TextEncoder().encode(e),toString$6=e=>new TextDecoder().decode(e);class Encoder$2{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class Decoder$2{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return or$3(this,t)}}class ComposedDecoder$1{constructor(t){this.decoders=t}or(t){return or$3(this,t)}decode(t){const r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$3=(e,t)=>new ComposedDecoder$1({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Codec$1{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Encoder$2(t,r,n),this.decoder=new Decoder$2(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const from$3=({name:e,prefix:t,encode:r,decode:n})=>new Codec$1(e,t,r,n),baseX$2=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=_brrp__multiformats_scope_baseX$1(r,t);return from$3({prefix:e,name:t,encode:n,decode:a=>coerce$2(o(a))})},decode$9=(e,t,r,n)=>{const o={};for(let b=0;b=8&&(c-=8,l[_++]=255&u>>c)}if(c>=r||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return l},encode$b=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<from$3({prefix:t,name:e,encode(o){return encode$b(o,n,r)},decode(o){return decode$9(o,n,r,e)}}),base10$2=baseX$2({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$3=Object.freeze(Object.defineProperty({__proto__:null,base10:base10$2},Symbol.toStringTag,{value:"Module"})),base16$2=rfc4648$3({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper$1=rfc4648$3({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$3=Object.freeze(Object.defineProperty({__proto__:null,base16:base16$2,base16upper:base16upper$1},Symbol.toStringTag,{value:"Module"})),base2$2=rfc4648$3({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$3=Object.freeze(Object.defineProperty({__proto__:null,base2:base2$2},Symbol.toStringTag,{value:"Module"})),alphabet$2=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),alphabetBytesToChars$1=alphabet$2.reduce((e,t,r)=>(e[r]=t,e),[]),alphabetCharsToBytes$1=alphabet$2.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function encode$a(e){return e.reduce((t,r)=>(t+=alphabetBytesToChars$1[r],t),"")}function decode$8(e){const t=[];for(const r of e){const n=alphabetCharsToBytes$1[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}const base256emoji$2=from$3({prefix:"\u{1F680}",name:"base256emoji",encode:encode$a,decode:decode$8}),base256emoji$3=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$2},Symbol.toStringTag,{value:"Module"})),base32$2=rfc4648$3({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$1=rfc4648$3({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$1=rfc4648$3({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$1=rfc4648$3({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$1=rfc4648$3({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$1=rfc4648$3({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$1=rfc4648$3({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$1=rfc4648$3({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$1=rfc4648$3({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$3=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$2,base32upper:base32upper$1,base32pad:base32pad$1,base32padupper:base32padupper$1,base32hex:base32hex$1,base32hexupper:base32hexupper$1,base32hexpad:base32hexpad$1,base32hexpadupper:base32hexpadupper$1,base32z:base32z$1},Symbol.toStringTag,{value:"Module"})),base36$2=baseX$2({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$1=baseX$2({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$3=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$2,base36upper:base36upper$1},Symbol.toStringTag,{value:"Module"})),base58btc$1=baseX$2({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$1=baseX$2({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$1=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$1,base58flickr:base58flickr$1},Symbol.toStringTag,{value:"Module"})),base64$4=rfc4648$3({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$1=rfc4648$3({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$1=rfc4648$3({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$1=rfc4648$3({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$5=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$4,base64pad:base64pad$1,base64url:base64url$1,base64urlpad:base64urlpad$1},Symbol.toStringTag,{value:"Module"})),base8$2=rfc4648$3({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$3=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$2},Symbol.toStringTag,{value:"Module"})),identity$6=from$3({prefix:"\0",name:"identity",encode:e=>toString$6(e),decode:e=>fromString$2(e)}),identityBase$1=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$6},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;var encode_1$1=encode$9,MSB$3=128,REST$3=127,MSBALL$1=~REST$3,INT$1=Math.pow(2,31);function encode$9(e,t,r){t=t||[],r=r||0;for(var n=r;e>=INT$1;)t[r++]=e&255|MSB$3,e/=128;for(;e&MSBALL$1;)t[r++]=e&255|MSB$3,e>>>=7;return t[r]=e|0,encode$9.bytes=r-n+1,t}var decode$7=read$2,MSB$1$1=128,REST$1$1=127;function read$2(e,n){var r=0,n=n||0,o=0,a=n,l,c=e.length;do{if(a>=c)throw read$2.bytes=0,new RangeError("Could not decode varint");l=e[a++],r+=o<28?(l&REST$1$1)<=MSB$1$1);return read$2.bytes=a-n,r}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$2=function(e){return e[_brrp_varint$1.decode(e,t),_brrp_varint$1.decode.bytes],encodeTo$1=(e,t,r=0)=>(_brrp_varint$1.encode(e,t,r),t),encodingLength$1=e=>_brrp_varint$1.encodingLength(e),create$4=(e,t)=>{const r=t.byteLength,n=encodingLength$1(e),o=n+encodingLength$1(r),a=new Uint8Array(o+r);return encodeTo$1(e,a,0),encodeTo$1(r,a,n),a.set(t,o),new Digest$1(e,r,t,a)},decode$5=e=>{const t=coerce$2(e),[r,n]=decode$6(t),[o,a]=decode$6(t.subarray(n)),l=t.subarray(n+a);if(l.byteLength!==o)throw new Error("Incorrect length");return new Digest$1(r,o,l,t)},equals=(e,t)=>{if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&equals$1(e.bytes,r.bytes)}};class Digest$1{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}const code$3=0,name$1="identity",encode$8=coerce$2,digest$1=e=>create$4(code$3,encode$8(e)),identity$4={code:code$3,name:name$1,encode:encode$8,digest:digest$1},identity$5=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$4},Symbol.toStringTag,{value:"Module"})),from$2=({name:e,code:t,encode:r})=>new Hasher$1(e,t,r);class Hasher$1{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?create$4(this.code,r):r.then(n=>create$4(this.code,n))}else throw Error("Unknown type, must be binary type")}}const sha$1=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),sha256$1=from$2({name:"sha2-256",code:18,encode:sha$1("SHA-256")}),sha512$2=from$2({name:"sha2-512",code:19,encode:sha$1("SHA-512")}),sha2$1=Object.freeze(Object.defineProperty({__proto__:null,sha256:sha256$1,sha512:sha512$2},Symbol.toStringTag,{value:"Module"})),format$3=(e,t)=>{const{bytes:r,version:n}=e;switch(n){case 0:return toStringV0(r,baseCache(e),t||base58btc$1.encoder);default:return toStringV1(r,baseCache(e),t||base32$2.encoder)}},cache$2=new WeakMap,baseCache=e=>{const t=cache$2.get(e);if(t==null){const r=new Map;return cache$2.set(e,r),r}return t};class CID{constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:t,multihash:r}=this;if(t!==DAG_PB_CODE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==SHA_256_CODE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return CID.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:r}=this.multihash,n=create$4(t,r);return CID.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return CID.equals(this,t)}static equals(t,r){const n=r;return n&&t.code===n.code&&t.version===n.version&&equals(t.multihash,n.multihash)}toString(t){return format$3(this,t)}toJSON(){return{"/":format$3(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;const r=t;if(r instanceof CID)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:a,bytes:l}=r;return new CID(n,o,a,l||encodeCID(n,o,a.bytes))}else if(r[cidSymbol]===!0){const{version:n,multihash:o,code:a}=r,l=decode$5(o);return CID.create(n,a,l)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==DAG_PB_CODE)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);return new CID(t,r,n,n.bytes)}case 1:{const o=encodeCID(t,r,n.bytes);return new CID(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return CID.create(0,DAG_PB_CODE,t)}static createV1(t,r){return CID.create(1,t,r)}static decode(t){const[r,n]=CID.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){const r=CID.inspectBytes(t),n=r.size-r.multihashSize,o=coerce$2(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const a=o.subarray(r.multihashSize-r.digestSize),l=new Digest$1(r.multihashCode,r.digestSize,a,o);return[r.version===0?CID.createV0(l):CID.createV1(r.codec,l),t.subarray(r.size)]}static inspectBytes(t){let r=0;const n=()=>{const[x,E]=decode$6(t.subarray(r));return r+=E,x};let o=n(),a=DAG_PB_CODE;if(o===18?(o=0,r=0):a=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const l=r,c=n(),u=n(),_=r+u,b=_-l;return{version:o,codec:a,multihashCode:c,digestSize:u,multihashSize:b,size:_}}static parse(t,r){const[n,o]=parseCIDtoBytes(t,r),a=CID.decode(o);if(a.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(a).set(n,t),a}}const parseCIDtoBytes=(e,t)=>{switch(e[0]){case"Q":{const r=t||base58btc$1;return[base58btc$1.prefix,r.decode(`${base58btc$1.prefix}${e}`)]}case base58btc$1.prefix:{const r=t||base58btc$1;return[base58btc$1.prefix,r.decode(e)]}case base32$2.prefix:{const r=t||base32$2;return[base32$2.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},toStringV0=(e,t,r)=>{const{prefix:n}=r;if(n!==base58btc$1.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(o==null){const a=r.encode(e).slice(1);return t.set(n,a),a}else return o},toStringV1=(e,t,r)=>{const{prefix:n}=r,o=t.get(n);if(o==null){const a=r.encode(e);return t.set(n,a),a}else return o},DAG_PB_CODE=112,SHA_256_CODE=18,encodeCID=(e,t,r)=>{const n=encodingLength$1(e),o=n+encodingLength$1(t),a=new Uint8Array(o+r.byteLength);return encodeTo$1(e,a,0),encodeTo$1(t,a,n),a.set(r,o),a},cidSymbol=Symbol.for("@ipld/js-cid/CID"),bases={...identityBase$1,...base2$3,...base8$3,...base10$3,...base16$3,...base32$3,...base36$3,...base58$1,...base64$5,...base256emoji$3};({...sha2$1,...identity$5});function createCodec$1(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const string$1=createCodec$1("utf8","u",e=>{const t=new TextDecoder("utf8");return"u"+t.decode(e)},e=>new TextEncoder().encode(e.substring(1))),ascii=createCodec$1("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);const t=allocUnsafe$2(e.length);for(let r=0;r1&&c.charAt(u)==="=";)++_;return Math.ceil(c.length*3)/4-_};for(var r=new Array(64),n=new Array(123),o=0;o<64;)n[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;t.encode=function(c,u,_){for(var b=null,x=[],E=0,I=0,k;u<_;){var T=c[u++];switch(I){case 0:x[E++]=r[T>>2],k=(T&3)<<4,I=1;break;case 1:x[E++]=r[k|T>>4],k=(T&15)<<2,I=2;break;case 2:x[E++]=r[k|T>>6],x[E++]=r[T&63],I=0;break}E>8191&&((b||(b=[])).push(String.fromCharCode.apply(String,x)),E=0)}return I&&(x[E++]=r[k],x[E++]=61,I===1&&(x[E++]=61)),b?(E&&b.push(String.fromCharCode.apply(String,x.slice(0,E))),b.join("")):String.fromCharCode.apply(String,x.slice(0,E))};var a="invalid encoding";t.decode=function(c,u,_){for(var b=_,x=0,E,I=0;I1)break;if((k=n[k])===void 0)throw Error(a);switch(x){case 0:E=k,x=1;break;case 1:u[_++]=E<<2|(k&48)>>4,E=k,x=2;break;case 2:u[_++]=(E&15)<<4|(k&60)>>2,E=k,x=3;break;case 3:u[_++]=(E&3)<<6|k,x=0;break}}if(x===1)throw Error(a);return _-b},t.test=function(c){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c)}})(base64$3);var eventemitter=EventEmitter$3;function EventEmitter$3(){this._listeners={}}EventEmitter$3.prototype.on=function(t,r,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:r,ctx:n||this}),this};EventEmitter$3.prototype.off=function(t,r){if(t===void 0)this._listeners={};else if(r===void 0)this._listeners[t]=[];else for(var n=this._listeners[t],o=0;o0?0:2147483648,a,l);else if(isNaN(o))n(2143289344,a,l);else if(o>34028234663852886e22)n((c<<31|2139095040)>>>0,a,l);else if(o<11754943508222875e-54)n((c<<31|Math.round(o/1401298464324817e-60))>>>0,a,l);else{var u=Math.floor(Math.log(o)/Math.LN2),_=Math.round(o*Math.pow(2,-u)*8388608)&8388607;n((c<<31|u+127<<23|_)>>>0,a,l)}}e.writeFloatLE=t.bind(null,writeUintLE),e.writeFloatBE=t.bind(null,writeUintBE);function r(n,o,a){var l=n(o,a),c=(l>>31)*2+1,u=l>>>23&255,_=l&8388607;return u===255?_?NaN:c*(1/0):u===0?c*1401298464324817e-60*_:c*Math.pow(2,u-150)*(_+8388608)}e.readFloatLE=r.bind(null,readUintLE),e.readFloatBE=r.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=r[7]===128;function o(u,_,b){t[0]=u,_[b]=r[0],_[b+1]=r[1],_[b+2]=r[2],_[b+3]=r[3],_[b+4]=r[4],_[b+5]=r[5],_[b+6]=r[6],_[b+7]=r[7]}function a(u,_,b){t[0]=u,_[b]=r[7],_[b+1]=r[6],_[b+2]=r[5],_[b+3]=r[4],_[b+4]=r[3],_[b+5]=r[2],_[b+6]=r[1],_[b+7]=r[0]}e.writeDoubleLE=n?o:a,e.writeDoubleBE=n?a:o;function l(u,_){return r[0]=u[_],r[1]=u[_+1],r[2]=u[_+2],r[3]=u[_+3],r[4]=u[_+4],r[5]=u[_+5],r[6]=u[_+6],r[7]=u[_+7],t[0]}function c(u,_){return r[7]=u[_],r[6]=u[_+1],r[5]=u[_+2],r[4]=u[_+3],r[3]=u[_+4],r[2]=u[_+5],r[1]=u[_+6],r[0]=u[_+7],t[0]}e.readDoubleLE=n?l:c,e.readDoubleBE=n?c:l}():function(){function t(n,o,a,l,c,u){var _=l<0?1:0;if(_&&(l=-l),l===0)n(0,c,u+o),n(1/l>0?0:2147483648,c,u+a);else if(isNaN(l))n(0,c,u+o),n(2146959360,c,u+a);else if(l>17976931348623157e292)n(0,c,u+o),n((_<<31|2146435072)>>>0,c,u+a);else{var b;if(l<22250738585072014e-324)b=l/5e-324,n(b>>>0,c,u+o),n((_<<31|b/4294967296)>>>0,c,u+a);else{var x=Math.floor(Math.log(l)/Math.LN2);x===1024&&(x=1023),b=l*Math.pow(2,-x),n(b*4503599627370496>>>0,c,u+o),n((_<<31|x+1023<<20|b*1048576&1048575)>>>0,c,u+a)}}}e.writeDoubleLE=t.bind(null,writeUintLE,0,4),e.writeDoubleBE=t.bind(null,writeUintBE,4,0);function r(n,o,a,l,c){var u=n(l,c+o),_=n(l,c+a),b=(_>>31)*2+1,x=_>>>20&2047,E=4294967296*(_&1048575)+u;return x===2047?E?NaN:b*(1/0):x===0?b*5e-324*E:b*Math.pow(2,x-1075)*(E+4503599627370496)}e.readDoubleLE=r.bind(null,readUintLE,0,4),e.readDoubleBE=r.bind(null,readUintBE,4,0)}(),e}function writeUintLE(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function writeUintBE(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=e&255}function readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}var utf8$3={};(function(e){var t=e;t.length=function(n){for(var o=0,a=0,l=0;l191&&b<224?u[_++]=(b&31)<<6|n[o++]&63:b>239&&b<365?(b=((b&7)<<18|(n[o++]&63)<<12|(n[o++]&63)<<6|n[o++]&63)-65536,u[_++]=55296+(b>>10),u[_++]=56320+(b&1023)):u[_++]=(b&15)<<12|(n[o++]&63)<<6|n[o++]&63,_>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,u)),_=0);return c?(_&&c.push(String.fromCharCode.apply(String,u.slice(0,_))),c.join("")):String.fromCharCode.apply(String,u.slice(0,_))},t.write=function(n,o,a){for(var l=a,c,u,_=0;_>6|192,o[a++]=c&63|128):(c&64512)===55296&&((u=n.charCodeAt(_+1))&64512)===56320?(c=65536+((c&1023)<<10)+(u&1023),++_,o[a++]=c>>18|240,o[a++]=c>>12&63|128,o[a++]=c>>6&63|128,o[a++]=c&63|128):(o[a++]=c>>12|224,o[a++]=c>>6&63|128,o[a++]=c&63|128);return a-l}})(utf8$3);var pool_1=pool;function pool(e,t,r){var n=r||8192,o=n>>>1,a=null,l=n;return function(u){if(u<1||u>o)return e(u);l+u>n&&(a=e(n),l=0);var _=t.call(a,l,l+=u);return l&7&&(l=(l|7)+1),_}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=t;var e=requireMinimal();function t(a,l){this.lo=a>>>0,this.hi=l>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var n=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(l){if(l===0)return r;var c=l<0;c&&(l=-l);var u=l>>>0,_=(l-u)/4294967296>>>0;return c&&(_=~_>>>0,u=~u>>>0,++u>4294967295&&(u=0,++_>4294967295&&(_=0))),new t(u,_)},t.from=function(l){if(typeof l=="number")return t.fromNumber(l);if(e.isString(l))if(e.Long)l=e.Long.fromString(l);else return t.fromNumber(parseInt(l,10));return l.low||l.high?new t(l.low>>>0,l.high>>>0):r},t.prototype.toNumber=function(l){if(!l&&this.hi>>>31){var c=~this.lo+1>>>0,u=~this.hi>>>0;return c||(u=u+1>>>0),-(c+u*4294967296)}return this.lo+this.hi*4294967296},t.prototype.toLong=function(l){return e.Long?new e.Long(this.lo|0,this.hi|0,Boolean(l)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(l)}};var o=String.prototype.charCodeAt;return t.fromHash=function(l){return l===n?r:new t((o.call(l,0)|o.call(l,1)<<8|o.call(l,2)<<16|o.call(l,3)<<24)>>>0,(o.call(l,4)|o.call(l,5)<<8|o.call(l,6)<<16|o.call(l,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var l=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^l)>>>0,this.lo=(this.lo<<1^l)>>>0,this},t.prototype.zzDecode=function(){var l=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^l)>>>0,this.hi=(this.hi>>>1^l)>>>0,this},t.prototype.length=function(){var l=this.lo,c=(this.lo>>>28|this.hi<<4)>>>0,u=this.hi>>>24;return u===0?c===0?l<16384?l<128?1:2:l<2097152?3:4:c<16384?c<128?5:6:c<2097152?7:8:u<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(e){var t=e;t.asPromise=aspromise,t.base64=base64$3,t.EventEmitter=eventemitter,t.float=float,t.inquire=inquire_1,t.utf8=utf8$3,t.pool=pool_1,t.LongBits=requireLongbits(),t.isNode=Boolean(typeof commonjsGlobal$2<"u"&&commonjsGlobal$2&&commonjsGlobal$2.process&&commonjsGlobal$2.process.versions&&commonjsGlobal$2.process.versions.node),t.global=t.isNode&&commonjsGlobal$2||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal$2,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(a){return typeof a=="number"&&isFinite(a)&&Math.floor(a)===a},t.isString=function(a){return typeof a=="string"||a instanceof String},t.isObject=function(a){return a&&typeof a=="object"},t.isset=t.isSet=function(a,l){var c=a[l];return c!=null&&a.hasOwnProperty(l)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=function(){try{var o=t.inquire("buffer").Buffer;return o.prototype.utf8Write?o:null}catch{return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(a){return typeof a=="number"?t.Buffer?t._Buffer_allocUnsafe(a):new t.Array(a):t.Buffer?t._Buffer_from(a):typeof Uint8Array>"u"?a:new Uint8Array(a)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(a){return a?t.LongBits.from(a).toHash():t.LongBits.zeroHash},t.longFromHash=function(a,l){var c=t.LongBits.fromHash(a);return t.Long?t.Long.fromBits(c.lo,c.hi,l):c.toNumber(Boolean(l))};function r(o,a,l){for(var c=Object.keys(a),u=0;u-1;--_)if(l[u[_]]===1&&this[u[_]]!==void 0&&this[u[_]]!==null)return u[_]}},t.oneOfSetter=function(a){return function(l){for(var c=0;c "+e.len)}function Reader$1(e){this.buf=e,this.pos=0,this.len=e.length}var create_array=typeof Uint8Array<"u"?function e(t){if(t instanceof Uint8Array||Array.isArray(t))return new Reader$1(t);throw Error("illegal buffer")}:function e(t){if(Array.isArray(t))return new Reader$1(t);throw Error("illegal buffer")},create$2=function e(){return util$4.Buffer?function(r){return(Reader$1.create=function(o){return util$4.Buffer.isBuffer(o)?new BufferReader$1(o):create_array(o)})(r)}:create_array};Reader$1.create=create$2();Reader$1.prototype._slice=util$4.Array.prototype.subarray||util$4.Array.prototype.slice;Reader$1.prototype.uint32=function e(){var t=4294967295;return function(){if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return t}}();Reader$1.prototype.int32=function e(){return this.uint32()|0};Reader$1.prototype.sint32=function e(){var t=this.uint32();return t>>>1^-(t&1)|0};function readLongVarint(){var e=new LongBits$1(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function e(){return this.uint32()!==0};function readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}Reader$1.prototype.fixed32=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits$1(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function e(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var t=util$4.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t};Reader$1.prototype.double=function e(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var t=util$4.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t};Reader$1.prototype.bytes=function e(){var t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw indexOutOfRange(this,t);if(this.pos+=t,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var o=util$4.Buffer;return o?o.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Reader$1.prototype.string=function e(){var t=this.bytes();return utf8$2.read(t,0,t.length)};Reader$1.prototype.skip=function e(t){if(typeof t=="number"){if(this.pos+t>this.len)throw indexOutOfRange(this,t);this.pos+=t}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this};Reader$1._configure=function(e){BufferReader$1=e,Reader$1.create=create$2(),BufferReader$1._configure();var t=util$4.Long?"toLong":"toNumber";util$4.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[t](!1)},uint64:function(){return readLongVarint.call(this)[t](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function(){return readFixed64.call(this)[t](!0)},sfixed64:function(){return readFixed64.call(this)[t](!1)}})};var reader_buffer=BufferReader,Reader=reader$2;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$3=requireMinimal();function BufferReader(e){Reader.call(this,e)}BufferReader._configure=function(){util$3.Buffer&&(BufferReader.prototype._slice=util$3.Buffer.prototype.slice)};BufferReader.prototype.string=function e(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))};BufferReader._configure();var minimalExports=requireMinimal(),writer$1=Writer$1,util$2=requireMinimal(),BufferWriter$1,LongBits=util$2.LongBits,base64$2=util$2.base64,utf8$1=util$2.utf8;function Op(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function noop$4(){}function State(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function Writer$1(){this.len=0,this.head=new Op(noop$4,0,0),this.tail=this.head,this.states=null}var create$1=function e(){return util$2.Buffer?function(){return(Writer$1.create=function(){return new BufferWriter$1})()}:function(){return new Writer$1}};Writer$1.create=create$1();Writer$1.alloc=function e(t){return new util$2.Array(t)};util$2.Array!==Array&&(Writer$1.alloc=util$2.pool(Writer$1.alloc,util$2.Array.prototype.subarray));Writer$1.prototype._push=function e(t,r,n){return this.tail=this.tail.next=new Op(t,r,n),this.len+=r,this};function writeByte(e,t,r){t[r]=e&255}function writeVarint32(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}function VarintOp(e,t){this.len=e,this.next=void 0,this.val=t}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function e(t){return this.len+=(this.tail=this.tail.next=new VarintOp((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this};Writer$1.prototype.int32=function e(t){return t<0?this._push(writeVarint64,10,LongBits.fromNumber(t)):this.uint32(t)};Writer$1.prototype.sint32=function e(t){return this.uint32((t<<1^t>>31)>>>0)};function writeVarint64(e,t,r){for(;e.hi;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}Writer$1.prototype.uint64=function e(t){var r=LongBits.from(t);return this._push(writeVarint64,r.length(),r)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function e(t){var r=LongBits.from(t).zzEncode();return this._push(writeVarint64,r.length(),r)};Writer$1.prototype.bool=function e(t){return this._push(writeByte,1,t?1:0)};function writeFixed32(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}Writer$1.prototype.fixed32=function e(t){return this._push(writeFixed32,4,t>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function e(t){var r=LongBits.from(t);return this._push(writeFixed32,4,r.lo)._push(writeFixed32,4,r.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function e(t){return this._push(util$2.float.writeFloatLE,4,t)};Writer$1.prototype.double=function e(t){return this._push(util$2.float.writeDoubleLE,8,t)};var writeBytes=util$2.Array.prototype.set?function e(t,r,n){r.set(t,n)}:function e(t,r,n){for(var o=0;o>>0;if(!r)return this._push(writeByte,1,0);if(util$2.isString(t)){var n=Writer$1.alloc(r=base64$2.length(t));base64$2.decode(t,n,0),t=n}return this.uint32(r)._push(writeBytes,r,t)};Writer$1.prototype.string=function e(t){var r=utf8$1.length(t);return r?this.uint32(r)._push(utf8$1.write,r,t):this._push(writeByte,1,0)};Writer$1.prototype.fork=function e(){return this.states=new State(this),this.head=this.tail=new Op(noop$4,0,0),this.len=0,this};Writer$1.prototype.reset=function e(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop$4,0,0),this.len=0),this};Writer$1.prototype.ldelim=function e(){var t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=r,this.len+=n),this};Writer$1.prototype.finish=function e(){for(var t=this.head.next,r=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r};Writer$1._configure=function(e){BufferWriter$1=e,Writer$1.create=create$1(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer$1;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$1=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$1._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$1.Buffer&&util$1.Buffer.prototype instanceof Uint8Array&&util$1.Buffer.prototype.set.name==="set"?function(t,r,n){r.set(t,n)}:function(t,r,n){if(t.copy)t.copy(r,n,0,t.length);else for(var o=0;o>>0;return this.uint32(r),r&&this._push(BufferWriter.writeBytesBuffer,r,t),this};function writeStringBuffer(e,t,r){e.length<40?util$1.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}BufferWriter.prototype.string=function e(t){var r=util$1.Buffer.byteLength(t);return this.uint32(r),r&&this._push(writeStringBuffer,r,t),this};BufferWriter._configure();function configure(){minimalExports._configure(),reader$2._configure(reader_buffer),writer$1._configure(writer_buffer)}configure();const methods=["uint64","int64","sint64","fixed64","sfixed64"];function patchReader(e){for(const t of methods){if(e[t]==null)continue;const r=e[t];e[t]=function(){return BigInt(r.call(this).toString())}}return e}function reader$1(e){return patchReader(new reader$2(e))}function patchWriter(e){for(const t of methods){if(e[t]==null)continue;const r=e[t];e[t]=function(n){return r.call(this,n.toString())}}return e}function writer(){return patchWriter(writer$1.create())}function decodeMessage(e,t){const r=reader$1(e instanceof Uint8Array?e:e.subarray());return t.decode(r)}function encodeMessage(e,t){const r=writer();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var CODEC_TYPES;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(CODEC_TYPES||(CODEC_TYPES={}));function createCodec(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function enumeration(e){function t(o){if(e[o.toString()]==null)throw new Error("Invalid enum value");return e[o]}const r=function(a,l){const c=t(a);l.int32(c)},n=function(a){const l=a.int32();return t(l)};return createCodec("enum",CODEC_TYPES.VARINT,r,n)}function message(e,t){return createCodec("message",CODEC_TYPES.LENGTH_DELIMITED,e,t)}var KeyType;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"})(KeyType||(KeyType={}));var __KeyTypeValues;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"})(__KeyTypeValues||(__KeyTypeValues={}));(function(e){e.codec=()=>enumeration(__KeyTypeValues)})(KeyType||(KeyType={}));var PublicKey;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),KeyType.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.Type=KeyType.codec().decode(r);break;case 2:o.Data=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PublicKey||(PublicKey={}));var PrivateKey;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),KeyType.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.Type=KeyType.codec().decode(r);break;case 2:o.Data=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PrivateKey||(PrivateKey={}));class Ed25519PublicKey{constructor(t){Ke(this,"_key");this._key=ensureKey(t,PUBLIC_KEY_BYTE_LENGTH)}async verify(t,r){return hashAndVerify$2(this._key,r,t)}marshal(){return this._key}get bytes(){return PublicKey.encode({Type:KeyType.Ed25519,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class Ed25519PrivateKey{constructor(t,r){Ke(this,"_key");Ke(this,"_publicKey");this._key=ensureKey(t,PRIVATE_KEY_BYTE_LENGTH),this._publicKey=ensureKey(r,PUBLIC_KEY_BYTE_LENGTH)}async sign(t){return hashAndSign$2(this._key,t)}get public(){return new Ed25519PublicKey(this._publicKey)}marshal(){return this._key}get bytes(){return PrivateKey.encode({Type:KeyType.Ed25519,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=identity$4.digest(this.public.bytes);return base58btc$1.encode(t.bytes).substring(1)}async export(t,r="libp2p-key"){if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function unmarshalEd25519PrivateKey(e){if(e.length>PRIVATE_KEY_BYTE_LENGTH){e=ensureKey(e,PRIVATE_KEY_BYTE_LENGTH+PUBLIC_KEY_BYTE_LENGTH);const n=e.subarray(0,PRIVATE_KEY_BYTE_LENGTH),o=e.subarray(PRIVATE_KEY_BYTE_LENGTH,e.length);return new Ed25519PrivateKey(n,o)}e=ensureKey(e,PRIVATE_KEY_BYTE_LENGTH);const t=e.subarray(0,PRIVATE_KEY_BYTE_LENGTH),r=e.subarray(PUBLIC_KEY_BYTE_LENGTH);return new Ed25519PrivateKey(t,r)}function unmarshalEd25519PublicKey(e){return e=ensureKey(e,PUBLIC_KEY_BYTE_LENGTH),new Ed25519PublicKey(e)}async function generateKeyPair$3(){const{privateKey:e,publicKey:t}=await generateKey$2();return new Ed25519PrivateKey(e,t)}async function generateKeyPairFromSeed(e){const{privateKey:t,publicKey:r}=await generateKeyFromSeed(e);return new Ed25519PrivateKey(t,r)}function ensureKey(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new CodeError(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}const Ed25519=Object.freeze(Object.defineProperty({__proto__:null,Ed25519PublicKey,Ed25519PrivateKey,unmarshalEd25519PrivateKey,unmarshalEd25519PublicKey,generateKeyPair:generateKeyPair$3,generateKeyPairFromSeed},Symbol.toStringTag,{value:"Module"}));function toString$5(e,t="utf8"){const r=BASES[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function bigIntegerToUintBase64url(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=concat$1([new Uint8Array(t-r.length),r])}return toString$5(r,"base64url")}function base64urlToBigInteger(e){const t=base64urlToBuffer(e);return new forge$m.jsbn.BigInteger(toString$5(t,"base16"),16)}function base64urlToBuffer(e,t){let r=fromString$1(e,"base64urlpad");if(t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=concat$1([new Uint8Array(t-r.length),r])}return r}const bits={"P-256":256,"P-384":384,"P-521":521},curveTypes=Object.keys(bits);curveTypes.join(" / ");async function importer(e,t){const r=base64$4.decode(e);return create$3().decrypt(r,t)}var forge=forge$m,sha512$1=forge.sha512=forge.sha512||{};forge.md.sha512=forge.md.algorithms.sha512=sha512$1;var sha384=forge.sha384=forge.sha512.sha384=forge.sha512.sha384||{};sha384.create=function(){return sha512$1.create("SHA-384")};forge.md.sha384=forge.md.algorithms.sha384=sha384;forge.sha512.sha256=forge.sha512.sha256||{create:function(){return sha512$1.create("SHA-512/256")}};forge.md["sha512/256"]=forge.md.algorithms["sha512/256"]=forge.sha512.sha256;forge.sha512.sha224=forge.sha512.sha224||{create:function(){return sha512$1.create("SHA-512/224")}};forge.md["sha512/224"]=forge.md.algorithms["sha512/224"]=forge.sha512.sha224;sha512$1.create=function(e){if(_initialized||_init(),typeof e>"u"&&(e="SHA-512"),!(e in _states))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=_states[e],r=null,n=forge.util.createBuffer(),o=new Array(80),a=0;a<80;++a)o[a]=new Array(2);var l=64;switch(e){case"SHA-384":l=48;break;case"SHA-512/256":l=32;break;case"SHA-512/224":l=28;break}var c={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:l,messageLength:0,fullMessageLength:null,messageLengthSize:16};return c.start=function(){c.messageLength=0,c.fullMessageLength=c.messageLength128=[];for(var u=c.messageLengthSize/4,_=0;_>>0,b>>>0];for(var x=c.fullMessageLength.length-1;x>=0;--x)c.fullMessageLength[x]+=b[1],b[1]=b[0]+(c.fullMessageLength[x]/4294967296>>>0),c.fullMessageLength[x]=c.fullMessageLength[x]>>>0,b[0]=b[1]/4294967296>>>0;return n.putBytes(u),_update(r,o,n),(n.read>2048||n.length()===0)&&n.compact(),c},c.digest=function(){var u=forge.util.createBuffer();u.putBytes(n.bytes());var _=c.fullMessageLength[c.fullMessageLength.length-1]+c.messageLengthSize,b=_&c.blockLength-1;u.putBytes(_padding.substr(0,c.blockLength-b));for(var x,E,I=c.fullMessageLength[0]*8,k=0;k>>0,I+=E,u.putInt32(I>>>0),I=x>>>0;u.putInt32(I);for(var T=new Array(r.length),k=0;k=128;){for(te=0;te<16;++te)t[te][0]=r.getInt32()>>>0,t[te][1]=r.getInt32()>>>0;for(;te<80;++te)se=t[te-2],ae=se[0],ge=se[1],n=((ae>>>19|ge<<13)^(ge>>>29|ae<<3)^ae>>>6)>>>0,o=((ae<<13|ge>>>19)^(ge<<3|ae>>>29)^(ae<<26|ge>>>6))>>>0,Pe=t[te-15],ae=Pe[0],ge=Pe[1],a=((ae>>>1|ge<<31)^(ae>>>8|ge<<24)^ae>>>7)>>>0,l=((ae<<31|ge>>>1)^(ae<<24|ge>>>8)^(ae<<25|ge>>>7))>>>0,Se=t[te-7],Ue=t[te-16],ge=o+Se[1]+l+Ue[1],t[te][0]=n+Se[0]+a+Ue[0]+(ge/4294967296>>>0)>>>0,t[te][1]=ge>>>0;for(T=e[0][0],O=e[0][1],$=e[1][0],D=e[1][1],N=e[2][0],H=e[2][1],ie=e[3][0],ue=e[3][1],de=e[4][0],le=e[4][1],ce=e[5][0],ve=e[5][1],ee=e[6][0],he=e[6][1],ne=e[7][0],xe=e[7][1],te=0;te<80;++te)_=((de>>>14|le<<18)^(de>>>18|le<<14)^(le>>>9|de<<23))>>>0,b=((de<<18|le>>>14)^(de<<14|le>>>18)^(le<<23|de>>>9))>>>0,x=(ee^de&(ce^ee))>>>0,E=(he^le&(ve^he))>>>0,c=((T>>>28|O<<4)^(O>>>2|T<<30)^(O>>>7|T<<25))>>>0,u=((T<<4|O>>>28)^(O<<30|T>>>2)^(O<<25|T>>>7))>>>0,I=(T&$|N&(T^$))>>>0,k=(O&D|H&(O^D))>>>0,ge=xe+b+E+_k[te][1]+t[te][1],n=ne+_+x+_k[te][0]+t[te][0]+(ge/4294967296>>>0)>>>0,o=ge>>>0,ge=u+k,a=c+I+(ge/4294967296>>>0)>>>0,l=ge>>>0,ne=ee,xe=he,ee=ce,he=ve,ce=de,ve=le,ge=ue+o,de=ie+n+(ge/4294967296>>>0)>>>0,le=ge>>>0,ie=N,ue=H,N=$,H=D,$=T,D=O,ge=o+l,T=n+a+(ge/4294967296>>>0)>>>0,O=ge>>>0;ge=e[0][1]+O,e[0][0]=e[0][0]+T+(ge/4294967296>>>0)>>>0,e[0][1]=ge>>>0,ge=e[1][1]+D,e[1][0]=e[1][0]+$+(ge/4294967296>>>0)>>>0,e[1][1]=ge>>>0,ge=e[2][1]+H,e[2][0]=e[2][0]+N+(ge/4294967296>>>0)>>>0,e[2][1]=ge>>>0,ge=e[3][1]+ue,e[3][0]=e[3][0]+ie+(ge/4294967296>>>0)>>>0,e[3][1]=ge>>>0,ge=e[4][1]+le,e[4][0]=e[4][0]+de+(ge/4294967296>>>0)>>>0,e[4][1]=ge>>>0,ge=e[5][1]+ve,e[5][0]=e[5][0]+ce+(ge/4294967296>>>0)>>>0,e[5][1]=ge>>>0,ge=e[6][1]+he,e[6][0]=e[6][0]+ee+(ge/4294967296>>>0)>>>0,e[6][1]=ge>>>0,ge=e[7][1]+xe,e[7][0]=e[7][0]+ne+(ge/4294967296>>>0)>>>0,e[7][1]=ge>>>0,Be-=128}}function randomBytes(e){if(isNaN(e)||e<=0)throw new CodeError("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return randomBytes$1(e)}function convert$1(e,t){return t.map(r=>base64urlToBigInteger(e[r]))}function jwk2priv(e){return forge$m.pki.setRsaPrivateKey(...convert$1(e,["n","e","d","p","q","dp","dq","qi"]))}function jwk2pub(e){return forge$m.pki.setRsaPublicKey(...convert$1(e,["n","e"]))}function pkcs1ToJwk(e){const t=forge$m.asn1.fromDer(toString$5(e,"ascii")),r=forge$m.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:bigIntegerToUintBase64url(r.n),e:bigIntegerToUintBase64url(r.e),d:bigIntegerToUintBase64url(r.d),p:bigIntegerToUintBase64url(r.p),q:bigIntegerToUintBase64url(r.q),dp:bigIntegerToUintBase64url(r.dP),dq:bigIntegerToUintBase64url(r.dQ),qi:bigIntegerToUintBase64url(r.qInv),alg:"RS256"}}function jwkToPkcs1(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new CodeError("JWK was missing components","ERR_INVALID_PARAMETERS");const t=forge$m.pki.privateKeyToAsn1({n:base64urlToBigInteger(e.n),e:base64urlToBigInteger(e.e),d:base64urlToBigInteger(e.d),p:base64urlToBigInteger(e.p),q:base64urlToBigInteger(e.q),dP:base64urlToBigInteger(e.dp),dQ:base64urlToBigInteger(e.dq),qInv:base64urlToBigInteger(e.qi)});return fromString$1(forge$m.asn1.toDer(t).getBytes(),"ascii")}function pkixToJwk(e){const t=forge$m.asn1.fromDer(toString$5(e,"ascii")),r=forge$m.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:bigIntegerToUintBase64url(r.n),e:bigIntegerToUintBase64url(r.e)}}function jwkToPkix(e){if(e.n==null||e.e==null)throw new CodeError("JWK was missing components","ERR_INVALID_PARAMETERS");const t=forge$m.pki.publicKeyToAsn1({n:base64urlToBigInteger(e.n),e:base64urlToBigInteger(e.e)});return fromString$1(forge$m.asn1.toDer(t).getBytes(),"ascii")}async function generateKey$1(e){const t=await webcrypto.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await exportKey(t);return{privateKey:r[0],publicKey:r[1]}}async function unmarshalPrivateKey$1(e){const r=[await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await derivePublicFromPrivate(e)],n=await exportKey({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function hashAndSign$1(e,t){const r=await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await webcrypto.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(t));return new Uint8Array(n,0,n.byteLength)}async function hashAndVerify$1(e,t,r){const n=await webcrypto.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return webcrypto.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r)}async function exportKey(e){if(e.privateKey==null||e.publicKey==null)throw new CodeError("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([webcrypto.get().subtle.exportKey("jwk",e.privateKey),webcrypto.get().subtle.exportKey("jwk",e.publicKey)])}async function derivePublicFromPrivate(e){return webcrypto.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function convertKey(e,t,r,n){const o=t?jwk2pub(e):jwk2priv(e),a=toString$5(Uint8Array.from(r),"ascii"),l=n(a,o);return fromString$1(l,"ascii")}function encrypt(e,t){return convertKey(e,!0,t,(r,n)=>n.encrypt(r))}function decrypt(e,t){return convertKey(e,!1,t,(r,n)=>n.decrypt(r))}function keySize(e){if(e.kty!=="RSA")throw new CodeError("invalid key type","ERR_INVALID_KEY_TYPE");if(e.n==null)throw new CodeError("invalid key modulus","ERR_INVALID_KEY_MODULUS");return fromString$1(e.n,"base64url").length*8}const MAX_KEY_SIZE=8192;class RsaPublicKey{constructor(t){Ke(this,"_key");this._key=t}async verify(t,r){return hashAndVerify$1(this._key,r,t)}marshal(){return jwkToPkix(this._key)}get bytes(){return PublicKey.encode({Type:KeyType.RSA,Data:this.marshal()}).subarray()}encrypt(t){return encrypt(this._key,t)}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class RsaPrivateKey{constructor(t,r){Ke(this,"_key");Ke(this,"_publicKey");this._key=t,this._publicKey=r}genSecret(){return randomBytes(16)}async sign(t){return hashAndSign$1(this._key,t)}get public(){if(this._publicKey==null)throw new CodeError("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new RsaPublicKey(this._publicKey)}decrypt(t){return decrypt(this._key,t)}marshal(){return jwkToPkcs1(this._key)}get bytes(){return PrivateKey.encode({Type:KeyType.RSA,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=await this.public.hash();return toString$5(t,"base58btc")}async export(t,r="pkcs-8"){if(r==="pkcs-8"){const n=new forge$m.util.ByteBuffer(this.marshal()),o=forge$m.asn1.fromDer(n),a=forge$m.pki.privateKeyFromAsn1(o),l={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return forge$m.pki.encryptRsaPrivateKey(a,t,l)}else{if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}}async function unmarshalRsaPrivateKey(e){const t=pkcs1ToJwk(e);if(keySize(t)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await unmarshalPrivateKey$1(t);return new RsaPrivateKey(r.privateKey,r.publicKey)}function unmarshalRsaPublicKey(e){const t=pkixToJwk(e);if(keySize(t)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new RsaPublicKey(t)}async function fromJwk(e){if(keySize(e)>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await unmarshalPrivateKey$1(e);return new RsaPrivateKey(t.privateKey,t.publicKey)}async function generateKeyPair$2(e){if(e>MAX_KEY_SIZE)throw new CodeError("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await generateKey$1(e);return new RsaPrivateKey(t.privateKey,t.publicKey)}const RSA=Object.freeze(Object.defineProperty({__proto__:null,MAX_KEY_SIZE,RsaPublicKey,RsaPrivateKey,unmarshalRsaPrivateKey,unmarshalRsaPublicKey,fromJwk,generateKeyPair:generateKeyPair$2},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(e){const t=validateBasic(e);validateObject(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=DER;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:b2n(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=DER,r=typeof e=="string"?h2b(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");const{d:o,l:a}=DER._parseInt(r.subarray(2)),{d:l,l:c}=DER._parseInt(a);if(c.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:l}},hexFromSig(e){const t=_=>Number.parseInt(_[0],16)&8?"00"+_:_,r=_=>{const b=_.toString(16);return b.length&1?`0${b}`:b},n=t(r(e.s)),o=t(r(e.r)),a=n.length/2,l=o.length/2,c=r(a),u=r(l);return`30${r(l+a+4)}02${u}${o}02${c}${n}`}},_0n=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(e){const t=validatePointOpts(e),{Fp:r}=t,n=t.toBytes||((k,T,O)=>{const $=T.toAffine();return concatBytes(Uint8Array.from([4]),r.toBytes($.x),r.toBytes($.y))}),o=t.fromBytes||(k=>{const T=k.subarray(1),O=r.fromBytes(T.subarray(0,r.BYTES)),$=r.fromBytes(T.subarray(r.BYTES,2*r.BYTES));return{x:O,y:$}});function a(k){const{a:T,b:O}=t,$=r.sqr(k),D=r.mul($,k);return r.add(r.add(D,r.mul(k,T)),O)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw new Error("bad generator point: equation left != right");function l(k){return typeof k=="bigint"&&_0nr.eql(N,r.ZERO);return D(O)&&D($)?x.ZERO:new x(O,$,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(T){const O=r.invertBatch(T.map($=>$.pz));return T.map(($,D)=>$.toAffine(O[D])).map(x.fromAffine)}static fromHex(T){const O=x.fromAffine(o(ensureBytes("pointHex",T)));return O.assertValidity(),O}static fromPrivateKey(T){return x.BASE.multiply(u(T))}_setWindowSize(T){this._WINDOW_SIZE=T,_.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:T,y:O}=this.toAffine();if(!r.isValid(T)||!r.isValid(O))throw new Error("bad point: x or y not FE");const $=r.sqr(O),D=a(T);if(!r.eql($,D))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:T}=this.toAffine();if(r.isOdd)return!r.isOdd(T);throw new Error("Field doesn't support isOdd")}equals(T){b(T);const{px:O,py:$,pz:D}=this,{px:N,py:H,pz:ie}=T,ue=r.eql(r.mul(O,ie),r.mul(N,D)),de=r.eql(r.mul($,ie),r.mul(H,D));return ue&&de}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){const{a:T,b:O}=t,$=r.mul(O,_3n),{px:D,py:N,pz:H}=this;let ie=r.ZERO,ue=r.ZERO,de=r.ZERO,le=r.mul(D,D),ce=r.mul(N,N),ve=r.mul(H,H),ee=r.mul(D,N);return ee=r.add(ee,ee),de=r.mul(D,H),de=r.add(de,de),ie=r.mul(T,de),ue=r.mul($,ve),ue=r.add(ie,ue),ie=r.sub(ce,ue),ue=r.add(ce,ue),ue=r.mul(ie,ue),ie=r.mul(ee,ie),de=r.mul($,de),ve=r.mul(T,ve),ee=r.sub(le,ve),ee=r.mul(T,ee),ee=r.add(ee,de),de=r.add(le,le),le=r.add(de,le),le=r.add(le,ve),le=r.mul(le,ee),ue=r.add(ue,le),ve=r.mul(N,H),ve=r.add(ve,ve),le=r.mul(ve,ee),ie=r.sub(ie,le),de=r.mul(ve,ce),de=r.add(de,de),de=r.add(de,de),new x(ie,ue,de)}add(T){b(T);const{px:O,py:$,pz:D}=this,{px:N,py:H,pz:ie}=T;let ue=r.ZERO,de=r.ZERO,le=r.ZERO;const ce=t.a,ve=r.mul(t.b,_3n);let ee=r.mul(O,N),he=r.mul($,H),ne=r.mul(D,ie),xe=r.add(O,$),te=r.add(N,H);xe=r.mul(xe,te),te=r.add(ee,he),xe=r.sub(xe,te),te=r.add(O,D);let ae=r.add(N,ie);return te=r.mul(te,ae),ae=r.add(ee,ne),te=r.sub(te,ae),ae=r.add($,D),ue=r.add(H,ie),ae=r.mul(ae,ue),ue=r.add(he,ne),ae=r.sub(ae,ue),le=r.mul(ce,te),ue=r.mul(ve,ne),le=r.add(ue,le),ue=r.sub(he,le),le=r.add(he,le),de=r.mul(ue,le),he=r.add(ee,ee),he=r.add(he,ee),ne=r.mul(ce,ne),te=r.mul(ve,te),he=r.add(he,ne),ne=r.sub(ee,ne),ne=r.mul(ce,ne),te=r.add(te,ne),ee=r.mul(he,te),de=r.add(de,ee),ee=r.mul(ae,te),ue=r.mul(xe,ue),ue=r.sub(ue,ee),ee=r.mul(xe,he),le=r.mul(ae,le),le=r.add(le,ee),new x(ue,de,le)}subtract(T){return this.add(T.negate())}is0(){return this.equals(x.ZERO)}wNAF(T){return I.wNAFCached(this,_,T,O=>{const $=r.invertBatch(O.map(D=>D.pz));return O.map((D,N)=>D.toAffine($[N])).map(x.fromAffine)})}multiplyUnsafe(T){const O=x.ZERO;if(T===_0n)return O;if(c(T),T===_1n$1)return this;const{endo:$}=t;if(!$)return I.unsafeLadder(this,T);let{k1neg:D,k1:N,k2neg:H,k2:ie}=$.splitScalar(T),ue=O,de=O,le=this;for(;N>_0n||ie>_0n;)N&_1n$1&&(ue=ue.add(le)),ie&_1n$1&&(de=de.add(le)),le=le.double(),N>>=_1n$1,ie>>=_1n$1;return D&&(ue=ue.negate()),H&&(de=de.negate()),de=new x(r.mul(de.px,$.beta),de.py,de.pz),ue.add(de)}multiply(T){c(T);let O=T,$,D;const{endo:N}=t;if(N){const{k1neg:H,k1:ie,k2neg:ue,k2:de}=N.splitScalar(O);let{p:le,f:ce}=this.wNAF(ie),{p:ve,f:ee}=this.wNAF(de);le=I.constTimeNegate(H,le),ve=I.constTimeNegate(ue,ve),ve=new x(r.mul(ve.px,N.beta),ve.py,ve.pz),$=le.add(ve),D=ce.add(ee)}else{const{p:H,f:ie}=this.wNAF(O);$=H,D=ie}return x.normalizeZ([$,D])[0]}multiplyAndAddUnsafe(T,O,$){const D=x.BASE,N=(ie,ue)=>ue===_0n||ue===_1n$1||!ie.equals(D)?ie.multiplyUnsafe(ue):ie.multiply(ue),H=N(this,O).add(N(T,$));return H.is0()?void 0:H}toAffine(T){const{px:O,py:$,pz:D}=this,N=this.is0();T==null&&(T=N?r.ONE:r.inv(D));const H=r.mul(O,T),ie=r.mul($,T),ue=r.mul(D,T);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(ue,r.ONE))throw new Error("invZ was invalid");return{x:H,y:ie}}isTorsionFree(){const{h:T,isTorsionFree:O}=t;if(T===_1n$1)return!0;if(O)return O(x,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:T,clearCofactor:O}=t;return T===_1n$1?this:O?O(x,this):this.multiplyUnsafe(t.h)}toRawBytes(T=!0){return this.assertValidity(),n(x,this,T)}toHex(T=!0){return bytesToHex(this.toRawBytes(T))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);const E=t.nBitLength,I=wNAF(x,t.endo?Math.ceil(E/2):E);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:u,weierstrassEquation:a,isWithinCurveOrder:l}}function validateOpts(e){const t=validateBasic(e);return validateObject(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function weierstrass(e){const t=validateOpts(e),{Fp:r,n}=t,o=r.BYTES+1,a=2*r.BYTES+1;function l(te){return _0nbytesToHex(numberToBytesBE(te,t.nByteLength));function k(te){const ae=n>>_1n$1;return te>ae}function T(te){return k(te)?c(-te):te}const O=(te,ae,ge)=>bytesToNumberBE(te.slice(ae,ge));class ${constructor(ae,ge,se){this.r=ae,this.s=ge,this.recovery=se,this.assertValidity()}static fromCompact(ae){const ge=t.nByteLength;return ae=ensureBytes("compactSignature",ae,ge*2),new $(O(ae,0,ge),O(ae,ge,2*ge))}static fromDER(ae){const{r:ge,s:se}=DER.toSig(ensureBytes("DER",ae));return new $(ge,se)}assertValidity(){if(!E(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!E(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(ae){return new $(this.r,this.s,ae)}recoverPublicKey(ae){const{r:ge,s:se,recovery:Se}=this,Pe=de(ensureBytes("msgHash",ae));if(Se==null||![0,1,2,3].includes(Se))throw new Error("recovery id invalid");const Ue=Se===2||Se===3?ge+t.n:ge;if(Ue>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const Be=(Se&1)===0?"02":"03",fe=_.fromHex(Be+I(Ue)),ye=u(Ue),Ce=c(-Pe*ye),Le=c(se*ye),Fe=_.BASE.multiplyAndAddUnsafe(fe,Ce,Le);if(!Fe)throw new Error("point at infinify");return Fe.assertValidity(),Fe}hasHighS(){return k(this.s)}normalizeS(){return this.hasHighS()?new $(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return I(this.r)+I(this.s)}}const D={isValidPrivateKey(te){try{return b(te),!0}catch{return!1}},normPrivateKeyToScalar:b,randomPrivateKey:()=>{const te=getMinHashLength(t.n);return mapHashToField(t.randomBytes(te),t.n)},precompute(te=8,ae=_.BASE){return ae._setWindowSize(te),ae.multiply(BigInt(3)),ae}};function N(te,ae=!0){return _.fromPrivateKey(te).toRawBytes(ae)}function H(te){const ae=te instanceof Uint8Array,ge=typeof te=="string",se=(ae||ge)&&te.length;return ae?se===o||se===a:ge?se===2*o||se===2*a:te instanceof _}function ie(te,ae,ge=!0){if(H(te))throw new Error("first arg must be private key");if(!H(ae))throw new Error("second arg must be public key");return _.fromHex(ae).multiply(b(te)).toRawBytes(ge)}const ue=t.bits2int||function(te){const ae=bytesToNumberBE(te),ge=te.length*8-t.nBitLength;return ge>0?ae>>BigInt(ge):ae},de=t.bits2int_modN||function(te){return c(ue(te))},le=bitMask(t.nBitLength);function ce(te){if(typeof te!="bigint")throw new Error("bigint expected");if(!(_0n<=te&&tebe in ge))throw new Error("sign() legacy options not supported");const{hash:se,randomBytes:Se}=t;let{lowS:Pe,prehash:Ue,extraEntropy:Be}=ge;Pe==null&&(Pe=!0),te=ensureBytes("msgHash",te),Ue&&(te=ensureBytes("prehashed msgHash",se(te)));const fe=de(te),ye=b(ae),Ce=[ce(ye),ce(fe)];if(Be!=null){const be=Be===!0?Se(r.BYTES):Be;Ce.push(ensureBytes("extraEntropy",be))}const Le=concatBytes(...Ce),Fe=fe;function Oe(be){const Re=ue(be);if(!E(Re))return;const Ie=u(Re),we=_.BASE.multiply(Re).toAffine(),oe=c(we.x);if(oe===_0n)return;const pe=c(Ie*c(Fe+oe*ye));if(pe===_0n)return;let ke=(we.x===oe?0:2)|Number(we.y&_1n$1),Ne=pe;return Pe&&k(pe)&&(Ne=T(pe),ke^=1),new $(oe,Ne,ke)}return{seed:Le,k2sig:Oe}}const ee={lowS:t.lowS,prehash:!1},he={lowS:t.lowS,prehash:!1};function ne(te,ae,ge=ee){const{seed:se,k2sig:Se}=ve(te,ae,ge),Pe=t;return createHmacDrbg(Pe.hash.outputLen,Pe.nByteLength,Pe.hmac)(se,Se)}_.BASE._setWindowSize(8);function xe(te,ae,ge,se=he){const Se=te;if(ae=ensureBytes("msgHash",ae),ge=ensureBytes("publicKey",ge),"strict"in se)throw new Error("options.strict was renamed to lowS");const{lowS:Pe,prehash:Ue}=se;let Be,fe;try{if(typeof Se=="string"||Se instanceof Uint8Array)try{Be=$.fromDER(Se)}catch(we){if(!(we instanceof DER.Err))throw we;Be=$.fromCompact(Se)}else if(typeof Se=="object"&&typeof Se.r=="bigint"&&typeof Se.s=="bigint"){const{r:we,s:oe}=Se;Be=new $(we,oe)}else throw new Error("PARSE");fe=_.fromHex(ge)}catch(we){if(we.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(Pe&&Be.hasHighS())return!1;Ue&&(ae=t.hash(ae));const{r:ye,s:Ce}=Be,Le=de(ae),Fe=u(Ce),Oe=c(Le*Fe),be=c(ye*Fe),Re=_.BASE.multiplyAndAddUnsafe(fe,Oe,be)?.toAffine();return Re?c(Re.x)===ye:!1}return{CURVE:t,getPublicKey:N,getSharedSecret:ie,sign:ne,verify:xe,ProjectivePoint:_,Signature:$,utils:D}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(e){return{hash:e,hmac:(t,...r)=>hmac$1(e,t,concatBytes$1(...r)),randomBytes:randomBytes$1}}function createCurve(e,t){const r=n=>weierstrass({...e,...getHash(n)});return Object.freeze({...r(t),create:r})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(e,t)=>(e+t/_2n)/t;function sqrtMod(e){const t=secp256k1P,r=BigInt(3),n=BigInt(6),o=BigInt(11),a=BigInt(22),l=BigInt(23),c=BigInt(44),u=BigInt(88),_=e*e*e%t,b=_*_*e%t,x=pow2(b,r,t)*b%t,E=pow2(x,r,t)*b%t,I=pow2(E,_2n,t)*_%t,k=pow2(I,o,t)*I%t,T=pow2(k,a,t)*k%t,O=pow2(T,c,t)*T%t,$=pow2(O,u,t)*O%t,D=pow2($,c,t)*T%t,N=pow2(D,r,t)*b%t,H=pow2(N,l,t)*k%t,ie=pow2(H,n,t)*_%t,ue=pow2(ie,_2n,t);if(!Fp.eql(Fp.sqr(ue),e))throw new Error("Cannot find square root");return ue}const Fp=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=secp256k1N,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,l=BigInt("0x100000000000000000000000000000000"),c=divNearest(a*e,t),u=divNearest(-n*e,t);let _=mod(e-c*r-u*o,t),b=mod(-c*n-u*a,t);const x=_>l,E=b>l;if(x&&(_=t-_),E&&(b=t-b),_>l||b>l)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:x,k1:_,k2neg:E,k2:b}}}},sha256$3);BigInt(0);secp256k1.ProjectivePoint;function generateKey(){return secp256k1.utils.randomPrivateKey()}async function hashAndSign(e,t){const{digest:r}=await sha256$1.digest(t);try{return secp256k1.sign(r,e).toDERRawBytes()}catch(n){throw new CodeError(String(n),"ERR_INVALID_INPUT")}}async function hashAndVerify(e,t,r){try{const{digest:n}=await sha256$1.digest(r);return secp256k1.verify(t,n,e)}catch(n){throw new CodeError(String(n),"ERR_INVALID_INPUT")}}function compressPublicKey(e){return secp256k1.ProjectivePoint.fromHex(e).toRawBytes(!0)}function validatePrivateKey(e){try{secp256k1.getPublicKey(e,!0)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PRIVATE_KEY")}}function validatePublicKey(e){try{secp256k1.ProjectivePoint.fromHex(e)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PUBLIC_KEY")}}function computePublicKey(e){try{return secp256k1.getPublicKey(e,!0)}catch(t){throw new CodeError(String(t),"ERR_INVALID_PRIVATE_KEY")}}class Secp256k1PublicKey{constructor(t){Ke(this,"_key");validatePublicKey(t),this._key=t}async verify(t,r){return hashAndVerify(this._key,r,t)}marshal(){return compressPublicKey(this._key)}get bytes(){return PublicKey.encode({Type:KeyType.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}}class Secp256k1PrivateKey{constructor(t,r){Ke(this,"_key");Ke(this,"_publicKey");this._key=t,this._publicKey=r??computePublicKey(t),validatePrivateKey(this._key),validatePublicKey(this._publicKey)}async sign(t){return hashAndSign(this._key,t)}get public(){return new Secp256k1PublicKey(this._publicKey)}marshal(){return this._key}get bytes(){return PrivateKey.encode({Type:KeyType.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return equals$2(this.bytes,t.bytes)}async hash(){const{bytes:t}=await sha256$1.digest(this.bytes);return t}async id(){const t=await this.public.hash();return toString$5(t,"base58btc")}async export(t,r="libp2p-key"){if(r==="libp2p-key")return exporter(this.bytes,t);throw new CodeError(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function unmarshalSecp256k1PrivateKey(e){return new Secp256k1PrivateKey(e)}function unmarshalSecp256k1PublicKey(e){return new Secp256k1PublicKey(e)}async function generateKeyPair$1(){const e=generateKey();return new Secp256k1PrivateKey(e)}const Secp256k1=Object.freeze(Object.defineProperty({__proto__:null,Secp256k1PublicKey,Secp256k1PrivateKey,unmarshalSecp256k1PrivateKey,unmarshalSecp256k1PublicKey,generateKeyPair:generateKeyPair$1},Symbol.toStringTag,{value:"Module"})),supportedKeys={rsa:RSA,ed25519:Ed25519,secp256k1:Secp256k1};function unsupportedKey(e){const t=Object.keys(supportedKeys).join(" / ");return new CodeError(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function typeToKey(e){if(e=e.toLowerCase(),e==="rsa"||e==="ed25519"||e==="secp256k1")return supportedKeys[e];throw unsupportedKey(e)}async function generateKeyPair(e,t){return typeToKey(e).generateKeyPair(t??2048)}function unmarshalPublicKey(e){const t=PublicKey.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case KeyType.RSA:return supportedKeys.rsa.unmarshalRsaPublicKey(r);case KeyType.Ed25519:return supportedKeys.ed25519.unmarshalEd25519PublicKey(r);case KeyType.Secp256k1:return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw unsupportedKey(t.Type??"unknown")}}function marshalPublicKey(e,t){return t=(t??"rsa").toLowerCase(),typeToKey(t),e.bytes}async function unmarshalPrivateKey(e){const t=PrivateKey.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case KeyType.RSA:return supportedKeys.rsa.unmarshalRsaPrivateKey(r);case KeyType.Ed25519:return supportedKeys.ed25519.unmarshalEd25519PrivateKey(r);case KeyType.Secp256k1:return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw unsupportedKey(t.Type??"RSA")}}function marshalPrivateKey(e,t){return t=(t??"rsa").toLowerCase(),typeToKey(t),e.bytes}async function importKey(e,t){try{const o=await importer(e,t);return await unmarshalPrivateKey(o)}catch{}const r=forge$m.pki.decryptRsaPrivateKey(e,t);if(r===null)throw new CodeError("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=forge$m.asn1.toDer(forge$m.pki.privateKeyToAsn1(r));return n=fromString$1(n.getBytes(),"ascii"),supportedKeys.rsa.unmarshalRsaPrivateKey(n)}const symbol$3=Symbol.for("@libp2p/peer-id");function isPeerId(e){return e!=null&&Boolean(e[symbol$3])}const inspect$1=Symbol.for("nodejs.util.inspect.custom"),baseDecoder=Object.values(bases).map(e=>e.decoder).reduce((e,t)=>e.or(t),bases.identity.decoder),LIBP2P_KEY_CODE=114,MARSHALLED_ED225519_PUBLIC_KEY_LENGTH=36,MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH=37;var Zl;class PeerIdImpl{constructor(t){Ke(this,"type");Ke(this,"multihash");Ke(this,"privateKey");Ke(this,"publicKey");Ke(this,"string");Ke(this,Zl,!0);this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}toString(){return this.string==null&&(this.string=base58btc$1.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return CID.createV1(LIBP2P_KEY_CODE,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t instanceof Uint8Array)return equals$2(this.multihash.bytes,t);if(typeof t=="string")return peerIdFromString(t).equals(this);if(t?.multihash?.bytes!=null)return equals$2(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[(Zl=symbol$3,inspect$1)](){return`PeerId(${this.toString()})`}}class RSAPeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"RSA"});Ke(this,"type","RSA");Ke(this,"publicKey");this.publicKey=r.publicKey}}class Ed25519PeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"Ed25519"});Ke(this,"type","Ed25519");Ke(this,"publicKey");this.publicKey=r.multihash.digest}}class Secp256k1PeerIdImpl extends PeerIdImpl{constructor(r){super({...r,type:"secp256k1"});Ke(this,"type","secp256k1");Ke(this,"publicKey");this.publicKey=r.multihash.digest}}function peerIdFromPeerId(e){if(e.type==="RSA")return new RSAPeerIdImpl(e);if(e.type==="Ed25519")return new Ed25519PeerIdImpl(e);if(e.type==="secp256k1")return new Secp256k1PeerIdImpl(e);throw new CodeError("Not a PeerId","ERR_INVALID_PARAMETERS")}function peerIdFromString(e,t){if(e.charAt(0)==="1"||e.charAt(0)==="Q"){const r=decode$5(base58btc$1.decode(`z${e}`));return e.startsWith("12D")?new Ed25519PeerIdImpl({multihash:r}):e.startsWith("16U")?new Secp256k1PeerIdImpl({multihash:r}):new RSAPeerIdImpl({multihash:r})}return peerIdFromBytes(baseDecoder.decode(e))}function peerIdFromBytes(e){try{const t=decode$5(e);if(t.code===identity$4.code){if(t.digest.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH)return new Ed25519PeerIdImpl({multihash:t});if(t.digest.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH)return new Secp256k1PeerIdImpl({multihash:t})}if(t.code===sha256$1.code)return new RSAPeerIdImpl({multihash:t})}catch{return peerIdFromCID(CID.decode(e))}throw new Error("Supplied PeerID CID is invalid")}function peerIdFromCID(e){if(e==null||e.multihash==null||e.version==null||e.version===1&&e.code!==LIBP2P_KEY_CODE)throw new Error("Supplied PeerID CID is invalid");const t=e.multihash;if(t.code===sha256$1.code)return new RSAPeerIdImpl({multihash:e.multihash});if(t.code===identity$4.code){if(t.digest.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH)return new Ed25519PeerIdImpl({multihash:e.multihash});if(t.digest.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH)return new Secp256k1PeerIdImpl({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function peerIdFromKeys(e,t){return e.length===MARSHALLED_ED225519_PUBLIC_KEY_LENGTH?new Ed25519PeerIdImpl({multihash:create$4(identity$4.code,e),privateKey:t}):e.length===MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH?new Secp256k1PeerIdImpl({multihash:create$4(identity$4.code,e),privateKey:t}):new RSAPeerIdImpl({multihash:await sha256$1.digest(e),publicKey:e,privateKey:t})}var NoiseExtensions;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const a of r.webtransportCerthashes)n.uint32(10),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={webtransportCerthashes:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.webtransportCerthashes.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(NoiseExtensions||(NoiseExtensions={}));var NoiseHandshakePayload;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),(o.writeDefaults===!0||r.identityKey!=null&&r.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(r.identityKey??new Uint8Array(0))),(o.writeDefaults===!0||r.identitySig!=null&&r.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(r.identitySig??new Uint8Array(0))),r.extensions!=null&&(n.uint32(34),NoiseExtensions.codec().encode(r.extensions,n,{writeDefaults:!1})),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.identityKey=r.bytes();break;case 2:o.identitySig=r.bytes();break;case 4:o.extensions=NoiseExtensions.codec().decode(r,r.uint32());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(NoiseHandshakePayload||(NoiseHandshakePayload={}));async function getPayload(e,t,r){const n=await signPayload(e,getHandshakePayload(t));if(e.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return createHandshakePayload(e.publicKey,n,r)}function createHandshakePayload(e,t,r){return NoiseHandshakePayload.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function signPayload(e,t){if(e.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await unmarshalPrivateKey(e.privateKey)).sign(t)}async function getPeerIdFromPayload(e){return peerIdFromKeys(e.identityKey)}function decodePayload(e){return NoiseHandshakePayload.decode(e)}function getHandshakePayload(e){const t=fromString$1("noise-libp2p-static-key:");return concat$1([t,e],t.length+e.length)}async function verifySignedPayload(e,t,r){const n=await peerIdFromKeys(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);const o=getHandshakePayload(e);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(t.identitySig==null)throw new Error("Signature was missing from message");if(!await unmarshalPublicKey(n.publicKey).verify(o,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function isValidPublicKey(e){return!(!(e instanceof Uint8Array)||e.length!==32)}var browser$7={exports:{}},ms$4,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms$4;hasRequiredMs=1;var e=1e3,t=e*60,r=t*60,n=r*24,o=n*7,a=n*365.25;ms$4=function(b,x){x=x||{};var E=typeof b;if(E==="string"&&b.length>0)return l(b);if(E==="number"&&isFinite(b))return x.long?u(b):c(b);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(b))};function l(b){if(b=String(b),!(b.length>100)){var x=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(b);if(!!x){var E=parseFloat(x[1]),I=(x[2]||"ms").toLowerCase();switch(I){case"years":case"year":case"yrs":case"yr":case"y":return E*a;case"weeks":case"week":case"w":return E*o;case"days":case"day":case"d":return E*n;case"hours":case"hour":case"hrs":case"hr":case"h":return E*r;case"minutes":case"minute":case"mins":case"min":case"m":return E*t;case"seconds":case"second":case"secs":case"sec":case"s":return E*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}}}function c(b){var x=Math.abs(b);return x>=n?Math.round(b/n)+"d":x>=r?Math.round(b/r)+"h":x>=t?Math.round(b/t)+"m":x>=e?Math.round(b/e)+"s":b+"ms"}function u(b){var x=Math.abs(b);return x>=n?_(b,x,n,"day"):x>=r?_(b,x,r,"hour"):x>=t?_(b,x,t,"minute"):x>=e?_(b,x,e,"second"):b+" ms"}function _(b,x,E,I){var k=x>=E*1.5;return Math.round(b/E)+" "+I+(k?"s":"")}return ms$4}function setup(e){r.debug=r,r.default=r,r.coerce=u,r.disable=a,r.enable=o,r.enabled=l,r.humanize=requireMs(),r.destroy=_,Object.keys(e).forEach(b=>{r[b]=e[b]}),r.names=[],r.skips=[],r.formatters={};function t(b){let x=0;for(let E=0;E{if(ue==="%%")return"%";H++;const le=r.formatters[de];if(typeof le=="function"){const ce=O[H];ue=le.call($,ce),O.splice(H,1),H--}return ue}),r.formatArgs.call($,O),($.log||r.log).apply($,O)}return T.namespace=b,T.useColors=r.useColors(),T.color=r.selectColor(b),T.extend=n,T.destroy=r.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>E!==null?E:(I!==r.namespaces&&(I=r.namespaces,k=r.enabled(b)),k),set:O=>{E=O}}),typeof r.init=="function"&&r.init(T),T}function n(b,x){const E=r(this.namespace+(typeof x>"u"?":":x)+b);return E.log=this.log,E}function o(b){r.save(b),r.namespaces=b,r.names=[],r.skips=[];let x;const E=(typeof b=="string"?b:"").split(/[\s,]+/),I=E.length;for(x=0;x"-"+x)].join(",");return r.enable(""),b}function l(b){if(b[b.length-1]==="*")return!0;let x,E;for(x=0,E=r.skips.length;x{let u=!1;return()=>{u||(u=!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`."))}})(),t.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"];function r(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const _="color: "+this.color;u.splice(1,0,_,"color: inherit");let b=0,x=0;u[0].replace(/%[a-zA-Z%]/g,E=>{E!=="%%"&&(b++,E==="%c"&&(x=b))}),u.splice(x,0,_)}t.log=console.debug||console.log||(()=>{});function o(u){try{u?t.storage.setItem("debug",u):t.storage.removeItem("debug")}catch{}}function a(){let u;try{u=t.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}function l(){try{return localStorage}catch{}}e.exports=common(t);const{formatters:c}=e.exports;c.j=function(u){try{return JSON.stringify(u)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}}})(browser$7,browser$7.exports);const debug$9=browser$7.exports;debug$9.formatters.b=e=>e==null?"undefined":base58btc$1.baseEncode(e);debug$9.formatters.t=e=>e==null?"undefined":base32$2.baseEncode(e);debug$9.formatters.m=e=>e==null?"undefined":base64$4.baseEncode(e);debug$9.formatters.p=e=>e==null?"undefined":e.toString();debug$9.formatters.c=e=>e==null?"undefined":e.toString();debug$9.formatters.k=e=>e==null?"undefined":e.toString();debug$9.formatters.a=e=>e==null?"undefined":e.toString();function createDisabledLogger(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}function logger(e){let t=createDisabledLogger(`${e}:trace`);return debug$9.enabled(`${e}:trace`)&&debug$9.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(t=debug$9(`${e}:trace`)),Object.assign(debug$9(e),{error:debug$9(`${e}:error`),trace:t})}const log$B=logger("libp2p:noise");let keyLogger;DUMP_SESSION_KEYS?keyLogger=log$B:keyLogger=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function logLocalStaticKeys(e){keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${toString$5(e.publicKey,"hex")}`),keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${toString$5(e.privateKey,"hex")}`)}function logLocalEphemeralKeys(e){e?(keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${toString$5(e.publicKey,"hex")}`),keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${toString$5(e.privateKey,"hex")}`)):keyLogger("Missing local ephemeral keys.")}function logRemoteStaticKey(e){keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${toString$5(e,"hex")}`)}function logRemoteEphemeralKey(e){keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${toString$5(e,"hex")}`)}function logCipherState(e){e.cs1&&e.cs2?(keyLogger(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${toString$5(e.cs1.k,"hex")}`),keyLogger(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${toString$5(e.cs2.k,"hex")}`)):keyLogger("Missing cipher state.")}const MIN_NONCE=0,MAX_NONCE=4294967295,ERR_MAX_NONCE="Cipherstate has reached maximum n, a new handshake must be performed";class Nonce{constructor(t=MIN_NONCE){Ke(this,"n");Ke(this,"bytes");Ke(this,"view");this.n=t,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>MAX_NONCE)throw new Error(ERR_MAX_NONCE)}}class AbstractHandshake{constructor(t){Ke(this,"crypto");this.crypto=t}encryptWithAd(t,r,n){const o=this.encrypt(t.k,t.n,r,n);return t.n.increment(),o}decryptWithAd(t,r,n,o){const{plaintext:a,valid:l}=this.decrypt(t.k,t.n,r,n,o);return l&&t.n.increment(),{plaintext:a,valid:l}}hasKey(t){return!this.isEmptyKey(t.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(t){const r=this.createEmptyKey();return equals$2(r,t)}encrypt(t,r,n,o){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(o,r.getBytes(),n,t)}encryptAndHash(t,r){let n;return this.hasKey(t.cs)?n=this.encryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,n),n}decrypt(t,r,n,o,a){r.assertValue();const l=this.crypto.chaCha20Poly1305Decrypt(o,r.getBytes(),n,t,a);return l?{plaintext:l,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(t,r){let n,o=!0;return this.hasKey(t.cs)?{plaintext:n,valid:o}=this.decryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,r),{plaintext:n,valid:o}}dh(t,r){try{const n=this.crypto.generateX25519SharedKey(t,r);return n.length===32?n:n.subarray(0,32)}catch(n){const o=n;return log$B.error(o),new Uint8Array(32)}}mixHash(t,r){t.h=this.getHash(t.h,r)}getHash(t,r){return this.crypto.hashSHA256(concat$1([t,r],t.length+r.length))}mixKey(t,r){const[n,o]=this.crypto.getHKDF(t.ck,r);t.cs=this.initializeKey(o),t.ck=n}initializeKey(t){return{k:t,n:new Nonce}}initializeSymmetric(t){const r=fromString$1(t,"utf-8"),n=this.hashProtocolName(r),o=n,a=this.createEmptyKey();return{cs:this.initializeKey(a),ck:o,h:n}}hashProtocolName(t){if(t.length<=32){const r=new Uint8Array(32);return r.set(t),r}else return this.getHash(t,new Uint8Array(0))}split(t){const[r,n]=this.crypto.getHKDF(t.ck,new Uint8Array(0)),o=this.initializeKey(r),a=this.initializeKey(n);return{cs1:o,cs2:a}}writeMessageRegular(t,r){const n=this.encryptWithAd(t,new Uint8Array(0),r),o=this.createEmptyKey(),a=new Uint8Array(0);return{ne:o,ns:a,ciphertext:n}}readMessageRegular(t,r){return this.decryptWithAd(t,new Uint8Array(0),r.ciphertext)}}class XX extends AbstractHandshake{initializeInitiator(t,r,n,o){const a="Noise_XX_25519_ChaChaPoly_SHA256",l=this.initializeSymmetric(a);this.mixHash(l,t);const c=new Uint8Array(32);return{ss:l,s:r,rs:n,psk:o,re:c}}initializeResponder(t,r,n,o){const a="Noise_XX_25519_ChaChaPoly_SHA256",l=this.initializeSymmetric(a);this.mixHash(l,t);const c=new Uint8Array(32);return{ss:l,s:r,rs:n,psk:o,re:c}}writeMessageA(t,r,n){const o=new Uint8Array(0);n!==void 0?t.e=n:t.e=this.crypto.generateX25519KeyPair();const a=t.e.publicKey;this.mixHash(t.ss,a);const l=this.encryptAndHash(t.ss,r);return{ne:a,ns:o,ciphertext:l}}writeMessageB(t,r){t.e=this.crypto.generateX25519KeyPair();const n=t.e.publicKey;this.mixHash(t.ss,n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));const o=t.s.publicKey,a=this.encryptAndHash(t.ss,o);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));const l=this.encryptAndHash(t.ss,r);return{ne:n,ns:a,ciphertext:l}}writeMessageC(t,r){const n=t.s.publicKey,o=this.encryptAndHash(t.ss,n);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));const a=this.encryptAndHash(t.ss,r),c={ne:this.createEmptyKey(),ns:o,ciphertext:a},{cs1:u,cs2:_}=this.split(t.ss);return{h:t.ss.h,messageBuffer:c,cs1:u,cs2:_}}readMessageA(t,r){return isValidPublicKey(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),this.decryptAndHash(t.ss,r.ciphertext)}readMessageB(t,r){if(isValidPublicKey(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));const{plaintext:n,valid:o}=this.decryptAndHash(t.ss,r.ns);o&&isValidPublicKey(n)&&(t.rs=n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));const{plaintext:a,valid:l}=this.decryptAndHash(t.ss,r.ciphertext);return{plaintext:a,valid:o&&l}}readMessageC(t,r){const{plaintext:n,valid:o}=this.decryptAndHash(t.ss,r.ns);if(o&&isValidPublicKey(n)&&(t.rs=n),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));const{plaintext:a,valid:l}=this.decryptAndHash(t.ss,r.ciphertext),{cs1:c,cs2:u}=this.split(t.ss);return{h:t.ss.h,plaintext:a,valid:o&&l,cs1:c,cs2:u}}initSession(t,r,n){const o=this.createEmptyKey(),a=new Uint8Array(32);let l;return t?l=this.initializeInitiator(r,n,a,o):l=this.initializeResponder(r,n,a,o),{hs:l,i:t,mc:0}}sendMessage(t,r,n){let o;if(t.mc===0)o=this.writeMessageA(t.hs,r,n);else if(t.mc===1)o=this.writeMessageB(t.hs,r);else if(t.mc===2){const{h:a,messageBuffer:l,cs1:c,cs2:u}=this.writeMessageC(t.hs,r);o=l,t.h=a,t.cs1=c,t.cs2=u}else if(t.mc>2)if(t.i){if(!t.cs1)throw new Error("CS1 (cipher state) is not defined");o=this.writeMessageRegular(t.cs1,r)}else{if(!t.cs2)throw new Error("CS2 (cipher state) is not defined");o=this.writeMessageRegular(t.cs2,r)}else throw new Error("Session invalid.");return t.mc++,o}recvMessage(t,r){let n=new Uint8Array(0),o=!1;if(t.mc===0)({plaintext:n,valid:o}=this.readMessageA(t.hs,r));else if(t.mc===1)({plaintext:n,valid:o}=this.readMessageB(t.hs,r));else if(t.mc===2){const{h:a,plaintext:l,valid:c,cs1:u,cs2:_}=this.readMessageC(t.hs,r);n=l,o=c,t.h=a,t.cs1=u,t.cs2=_}return t.mc++,{plaintext:n,valid:o}}}class XXHandshake{constructor(t,r,n,o,a,l,c,u){Ke(this,"isInitiator");Ke(this,"session");Ke(this,"remotePeer");Ke(this,"remoteExtensions",{webtransportCerthashes:[]});Ke(this,"payload");Ke(this,"connection");Ke(this,"xx");Ke(this,"staticKeypair");Ke(this,"prologue");this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=a,this.connection=l,c&&(this.remotePeer=c),this.xx=u??new XX(o),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(logLocalStaticKeys(this.session.hs.s),this.isInitiator){log$B.trace("Stage 0 - Initiator starting to send first message.");const t=this.xx.sendMessage(this.session,new Uint8Array(0));await this.connection.write(encode0(t)),log$B.trace("Stage 0 - Initiator finished sending first message."),logLocalEphemeralKeys(this.session.hs.e)}else{log$B.trace("Stage 0 - Responder waiting to receive first message...");const t=decode0((await this.connection.read()).subarray()),{valid:r}=this.xx.recvMessage(this.session,t);if(!r)throw new InvalidCryptoExchangeError("xx handshake stage 0 validation fail");log$B.trace("Stage 0 - Responder received first message."),logRemoteEphemeralKey(this.session.hs.re)}}async exchange(){if(this.isInitiator){log$B.trace("Stage 1 - Initiator waiting to receive first message from responder...");const t=decode1((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new InvalidCryptoExchangeError("xx handshake stage 1 validation fail");log$B.trace("Stage 1 - Initiator received the message."),logRemoteEphemeralKey(this.session.hs.re),logRemoteStaticKey(this.session.hs.rs),log$B.trace("Initiator going to check remote's signature...");try{const o=decodePayload(r);this.remotePeer=this.remotePeer||await getPeerIdFromPayload(o),await verifySignedPayload(this.session.hs.rs,o,this.remotePeer),this.setRemoteNoiseExtension(o.extensions)}catch(o){const a=o;throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${a.message}`)}log$B.trace("All good with the signature!")}else{log$B.trace("Stage 1 - Responder sending out first message with signed payload and static key.");const t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(encode1(t)),log$B.trace("Stage 1 - Responder sent the second handshake message with signed payload."),logLocalEphemeralKeys(this.session.hs.e)}}async finish(){if(this.isInitiator){log$B.trace("Stage 2 - Initiator sending third handshake message.");const t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(encode2(t)),log$B.trace("Stage 2 - Initiator sent message with signed payload.")}else{log$B.trace("Stage 2 - Responder waiting for third handshake message...");const t=decode2((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new InvalidCryptoExchangeError("xx handshake stage 2 validation fail");log$B.trace("Stage 2 - Responder received the message, finished handshake.");try{const o=decodePayload(r);this.remotePeer=this.remotePeer||await getPeerIdFromPayload(o),await verifySignedPayload(this.session.hs.rs,o,this.remotePeer),this.setRemoteNoiseExtension(o.extensions)}catch(o){const a=o;throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${a.message}`)}}logCipherState(this.session)}encrypt(t,r){const n=this.getCS(r);return this.xx.encryptWithAd(n,new Uint8Array(0),t)}decrypt(t,r,n){const o=this.getCS(r,!1);return this.xx.decryptWithAd(o,new Uint8Array(0),t,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(t,r=!0){if(!t.cs1||!t.cs2)throw new InvalidCryptoExchangeError("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?t.cs1:t.cs2:r?t.cs2:t.cs1}setRemoteNoiseExtension(t){t&&(this.remoteExtensions=t)}}function registerMetrics(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}class Noise{constructor(t={}){Ke(this,"protocol","/noise");Ke(this,"crypto");Ke(this,"prologue");Ke(this,"staticKeys");Ke(this,"extensions");Ke(this,"metrics");const{staticNoiseKey:r,extensions:n,crypto:o,prologueBytes:a,metrics:l}=t;this.crypto=o??pureJsCrypto,this.extensions=n,this.metrics=l?registerMetrics(l):void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=a??new Uint8Array(0)}async secureOutbound(t,r,n){const o=lpStream(r,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),a=await this.performHandshake({connection:o,isInitiator:!0,localPeer:t,remotePeer:n});return{conn:await this.createSecureConnection(o,a),remoteExtensions:a.remoteExtensions,remotePeer:a.remotePeer}}async secureInbound(t,r,n){const o=lpStream(r,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),a=await this.performHandshake({connection:o,isInitiator:!1,localPeer:t,remotePeer:n});return{conn:await this.createSecureConnection(o,a),remotePeer:a.remotePeer,remoteExtensions:a.remoteExtensions}}async performHandshake(t){const r=await getPayload(t.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(t,r)}async performXXHandshake(t,r){const{isInitiator:n,remotePeer:o,connection:a}=t,l=new XXHandshake(n,r,this.prologue,this.crypto,this.staticKeys,a,o);try{await l.propose(),await l.exchange(),await l.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){if(this.metrics?.xxHandshakeErrors.increment(),c instanceof Error)throw c.message=`Error occurred during XX handshake: ${c.message}`,c}return l}async createSecureConnection(t,r){const[n,o]=duplexPair(),a=t.unwrap();return await pipe(n,encryptStream(r,this.metrics),a,l=>decode$a(l,{lengthDecoder:uint16BEDecode}),decryptStream(r,this.metrics),n),o}}function noise(e={}){return()=>new Noise(e)}var jr;class EventEmitter$2 extends EventTarget{constructor(){super(...arguments);_r(this,jr,new Map)}listenerCount(r){const n=Jt(this,jr).get(r);return n==null?0:n.length}addEventListener(r,n,o){super.addEventListener(r,n,o);let a=Jt(this,jr).get(r);a==null&&(a=[],Jt(this,jr).set(r,a)),a.push({callback:n,once:(o!==!0&&o!==!1&&o?.once)??!1})}removeEventListener(r,n,o){super.removeEventListener(r.toString(),n??null,o);let a=Jt(this,jr).get(r);a!=null&&(a=a.filter(({callback:l})=>l!==n),Jt(this,jr).set(r,a))}dispatchEvent(r){const n=super.dispatchEvent(r);let o=Jt(this,jr).get(r.type);return o==null||(o=o.filter(({once:a})=>!a),Jt(this,jr).set(r.type,o)),n}safeDispatchEvent(r,n){return this.dispatchEvent(new CustomEvent$1(r,n))}}jr=new WeakMap;class CustomEventPolyfill extends Event{constructor(r,n){super(r,n);Ke(this,"detail");this.detail=n?.detail}}const CustomEvent$1=globalThis.CustomEvent??CustomEventPolyfill,peerDiscovery=Symbol.for("@libp2p/peer-discovery");class Parser{constructor(){Ke(this,"index",0);Ke(this,"input","")}new(t){return this.index=0,this.input=t,this}readAtomically(t){const r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){const r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{const r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let a=0,l=0;const c=this.peekChar();if(c===void 0)return;const u=c==="0",_=2**(8*o)-1;for(;;){const b=this.readAtomically(()=>{const x=this.readChar();if(x===void 0)return;const E=Number.parseInt(x,t);if(!Number.isNaN(E))return E});if(b===void 0)break;if(a*=t,a+=b,a>_||(l+=1,r!==void 0&&l>r))return}if(l!==0)return!n&&u&&l>1?void 0:a})}readIPv4Addr(){return this.readAtomically(()=>{const t=new Uint8Array(4);for(let r=0;rthis.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){const t=r=>{for(let n=0;nthis.readIPv4Addr());if(l!==void 0)return r[o]=l[0],r[o+1]=l[1],r[o+2]=l[2],r[o+3]=l[3],[o+4,!0]}const a=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(a===void 0)return[o,!1];r[o]=a>>8,r[o+1]=a&255}return[r.length,!1]};return this.readAtomically(()=>{const r=new Uint8Array(16),[n,o]=t(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;const a=new Uint8Array(14),l=16-(n+2),[c]=t(a.subarray(0,l));return r.set(a.subarray(0,c),16-c),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}const MAX_IPV6_LENGTH=45,MAX_IPV4_LENGTH=15,parser$4=new Parser;function parseIPv4(e){if(!(e.length>MAX_IPV4_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPv4Addr())}function parseIPv6(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>MAX_IPV6_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPv6Addr())}function parseIP(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>MAX_IPV6_LENGTH))return parser$4.new(e).parseWith(()=>parser$4.readIPAddr())}function isIPv4(e){return Boolean(parseIPv4(e))}function isIPv6(e){return Boolean(parseIPv6(e))}function isIP(e){return Boolean(parseIP(e))}const isV4=isIPv4,isV6=isIPv6,toBytes=function(e){let t=0;if(e=e.toString().trim(),isV4(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach(n=>{r[t++]=parseInt(n,10)&255}),r}if(isV6(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)a.push("0");r.splice.apply(r,a)}const o=new Uint8Array(t+16);for(n=0;n>8&255,o[t++]=a&255}return o}throw new Error("invalid ip address")},toString$4=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(r===4){const o=[];for(let a=0;a{const t=createProtocol(...e);codes$8[t.code]=t,names$3[t.name]=t});function createProtocol(e,t,r,n,o){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(o)}}function getProtocol(e){if(typeof e=="number"){if(codes$8[e]!=null)return codes$8[e];throw new Error(`no protocol with code: ${e}`)}else if(typeof e=="string"){if(names$3[e]!=null)return names$3[e];throw new Error(`no protocol with name: ${e}`)}throw new Error(`invalid protocol id type: ${typeof e}`)}getProtocol("ip4");getProtocol("ip6");getProtocol("ipcidr");function convertToString(e,t){switch(getProtocol(e).code){case 4:case 41:return bytes2ip(t);case 42:return bytes2str(t);case 6:case 273:case 33:case 132:return bytes2port(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return bytes2str(t);case 421:return bytes2mh(t);case 444:return bytes2onion(t);case 445:return bytes2onion(t);case 466:return bytes2mb(t);default:return toString$5(t,"base16")}}function convertToBytes(e,t){switch(getProtocol(e).code){case 4:return ip2bytes(t);case 41:return ip2bytes(t);case 42:return str2bytes(t);case 6:case 273:case 33:case 132:return port2bytes(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return str2bytes(t);case 421:return mh2bytes(t);case 444:return onion2bytes(t);case 445:return onion32bytes(t);case 466:return mb2bytes(t);default:return fromString$1(t,"base16")}}const decoders=Object.values(bases).map(e=>e.decoder),anybaseDecoder=function(){let e=decoders[0].or(decoders[1]);return decoders.slice(2).forEach(t=>e=e.or(t)),e}();function ip2bytes(e){if(!isIP(e))throw new Error("invalid ip address");return toBytes(e)}function bytes2ip(e){const t=toString$4(e,0,e.length);if(t==null)throw new Error("ipBuff is required");if(!isIP(t))throw new Error("invalid ip address");return t}function port2bytes(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function bytes2port(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function str2bytes(e){const t=fromString$1(e),r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function bytes2str(e){const t=decode$b(e);if(e=e.slice(encodingLength$2(t)),e.length!==t)throw new Error("inconsistent lengths");return toString$5(e)}function mh2bytes(e){let t;e[0]==="Q"||e[0]==="1"?t=decode$5(base58btc$1.decode(`z${e}`)).bytes:t=CID.parse(e).multihash.bytes;const r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function mb2bytes(e){const t=anybaseDecoder.decode(e),r=Uint8Array.from(encode$d(t.length));return concat$1([r,t],r.length+t.length)}function bytes2mb(e){const t=decode$b(e),r=e.slice(encodingLength$2(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+toString$5(r,"base64url")}function bytes2mh(e){const t=decode$b(e),r=e.slice(encodingLength$2(t));if(r.length!==t)throw new Error("inconsistent lengths");return toString$5(r,"base58btc")}function onion2bytes(e){const t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=base32$2.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=port2bytes(n);return concat$1([r,o],r.length+o.length)}function onion32bytes(e){const t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=base32$2.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=port2bytes(n);return concat$1([r,o],r.length+o.length)}function bytes2onion(e){const t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=toString$5(t,"base32"),o=bytes2port(r);return`${n}:${o}`}function stringToMultiaddrParts(e){e=cleanPath(e);const t=[],r=[];let n=null;const o=e.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let a=0;a=o.length)throw ParseError("invalid address: "+e);if(c.path===!0){n=cleanPath(o.slice(a).join("/")),t.push([c.code,convertToBytes(c.code,n)]),r.push([c.code,n]);break}const u=convertToBytes(c.code,o[a]);t.push([c.code,u]),r.push([c.code,convertToString(c.code,u)])}return{string:stringTuplesToString(r),bytes:tuplesToBytes(t),tuples:t,stringTuples:r,path:n}}function bytesToMultiaddrParts(e){const t=[],r=[];let n=null,o=0;for(;oe.length)throw ParseError("Invalid address Uint8Array: "+toString$5(e,"base16"));t.push([a,_]);const b=convertToString(a,_);if(r.push([a,b]),c.path===!0){n=b;break}}return{bytes:Uint8Array.from(e),string:stringTuplesToString(r),tuples:t,stringTuples:r,path:n}}function stringTuplesToString(e){const t=[];return e.map(r=>{const n=getProtocol(r[0]);return t.push(n.name),r.length>1&&r[1]!=null&&t.push(r[1]),null}),cleanPath(t.join("/"))}function tuplesToBytes(e){return concat$1(e.map(t=>{const r=getProtocol(t[0]);let n=Uint8Array.from(encode$d(r.code));return t.length>1&&t[1]!=null&&(n=concat$1([n,t[1]])),n}))}function sizeForAddr(e,t){if(e.size>0)return e.size/8;if(e.size===0)return 0;{const r=decode$b(t instanceof Uint8Array?t:Uint8Array.from(t));return r+encodingLength$2(r)}}function cleanPath(e){return"/"+e.trim().split("/").filter(t=>t).join("/")}function ParseError(e){return new Error("Error parsing address: "+e)}const inspect=Symbol.for("nodejs.util.inspect.custom"),DNS_CODES=[getProtocol("dns").code,getProtocol("dns4").code,getProtocol("dns6").code,getProtocol("dnsaddr").code],resolvers=new Map,symbol$2=Symbol.for("@multiformats/js-multiaddr/multiaddr");function isMultiaddr(e){return Boolean(e?.[symbol$2])}var vi,xn,Ji,es,Ql;const Yn=class{constructor(t){Ke(this,"bytes");_r(this,vi,void 0);_r(this,xn,void 0);_r(this,Ji,void 0);_r(this,es,void 0);Ke(this,Ql,!0);t==null&&(t="");let r;if(t instanceof Uint8Array)r=bytesToMultiaddrParts(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);r=stringToMultiaddrParts(t)}else if(isMultiaddr(t))r=bytesToMultiaddrParts(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,wn(this,vi,r.string),wn(this,xn,r.tuples),wn(this,Ji,r.stringTuples),wn(this,es,r.path)}toString(){return Jt(this,vi)}toJSON(){return this.toString()}toOptions(){let t,r,n,o,a="";const l=getProtocol("tcp"),c=getProtocol("udp"),u=getProtocol("ip4"),_=getProtocol("ip6"),b=getProtocol("dns6"),x=getProtocol("ip6zone");for(const[I,k]of this.stringTuples())I===x.code&&(a=`%${k??""}`),DNS_CODES.includes(I)&&(r=l.name,o=443,n=`${k??""}${a}`,t=I===b.code?6:4),(I===l.code||I===c.code)&&(r=getProtocol(I).name,o=parseInt(k??"")),(I===u.code||I===_.code)&&(r=getProtocol(I).name,n=`${k??""}${a}`,t=I===_.code?6:4);if(t==null||r==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:r,port:o}}protos(){return Jt(this,xn).map(([t])=>Object.assign({},getProtocol(t)))}protoCodes(){return Jt(this,xn).map(([t])=>t)}protoNames(){return Jt(this,xn).map(([t])=>getProtocol(t).name)}tuples(){return Jt(this,xn)}stringTuples(){return Jt(this,Ji)}encapsulate(t){return t=new Yn(t),new Yn(this.toString()+t.toString())}decapsulate(t){const r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new Yn(n.slice(0,o))}decapsulateCode(t){const r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===t)return new Yn(tuplesToBytes(r.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===names$3.p2p.code&&t.push([n,o]),n===names$3["p2p-circuit"].code&&(t=[])});const r=t.pop();if(r?.[1]!=null){const n=r[1];return n[0]==="Q"||n[0]==="1"?toString$5(base58btc$1.decode(`z${n}`),"base58btc"):toString$5(CID.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return Jt(this,es)}equals(t){return equals$2(this.bytes,t.bytes)}async resolve(t){const r=this.protos().find(a=>a.resolvable);if(r==null)return[this];const n=resolvers.get(r.name);if(n==null)throw new CodeError(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(a=>new Yn(a))}nodeAddress(){const t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){const r=(t??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[(Ql=symbol$2,inspect)](){return`Multiaddr(${Jt(this,vi)})`}};let DefaultMultiaddr=Yn;vi=new WeakMap,xn=new WeakMap,Ji=new WeakMap,es=new WeakMap;function multiaddr(e){return new DefaultMultiaddr(e)}const DNS4=base$3("dns4"),DNS6=base$3("dns6"),DNSADDR=base$3("dnsaddr"),DNS=or$2(base$3("dns"),DNSADDR,DNS4,DNS6),IP=or$2(base$3("ip4"),base$3("ip6")),TCP=or$2(and$1(IP,base$3("tcp")),and$1(DNS,base$3("tcp"))),UDP=and$1(IP,base$3("udp")),UTP=and$1(UDP,base$3("utp")),QUIC=and$1(UDP,base$3("quic")),QUICV1=and$1(UDP,base$3("quic-v1")),_WebSockets$1=or$2(and$1(TCP,base$3("ws")),and$1(DNS,base$3("ws"))),WebSockets$1=or$2(and$1(_WebSockets$1,base$3("p2p")),_WebSockets$1),_WebSocketsSecure$1=or$2(and$1(TCP,base$3("wss")),and$1(DNS,base$3("wss")),and$1(TCP,base$3("tls"),base$3("ws")),and$1(DNS,base$3("tls"),base$3("ws"))),WebSocketsSecure=or$2(and$1(_WebSocketsSecure$1,base$3("p2p")),_WebSocketsSecure$1),HTTP=or$2(and$1(TCP,base$3("http")),and$1(IP,base$3("http")),and$1(DNS,base$3("http"))),HTTPS=or$2(and$1(TCP,base$3("https")),and$1(IP,base$3("https")),and$1(DNS,base$3("https"))),_WebRTCDirect$1=and$1(UDP,base$3("webrtc-direct"),base$3("certhash")),WebRTCDirect=or$2(and$1(_WebRTCDirect$1,base$3("p2p")),_WebRTCDirect$1),_WebTransport$1=and$1(QUICV1,base$3("webtransport"),base$3("certhash"),base$3("certhash")),WebTransport=or$2(and$1(_WebTransport$1,base$3("p2p")),_WebTransport$1),P2PWebRTCStar=or$2(and$1(WebSockets$1,base$3("p2p-webrtc-star"),base$3("p2p")),and$1(WebSocketsSecure,base$3("p2p-webrtc-star"),base$3("p2p")),and$1(WebSockets$1,base$3("p2p-webrtc-star")),and$1(WebSocketsSecure,base$3("p2p-webrtc-star"))),P2PWebRTCDirect=or$2(and$1(HTTP,base$3("p2p-webrtc-direct"),base$3("p2p")),and$1(HTTPS,base$3("p2p-webrtc-direct"),base$3("p2p")),and$1(HTTP,base$3("p2p-webrtc-direct")),and$1(HTTPS,base$3("p2p-webrtc-direct"))),Reliable=or$2(_WebSockets$1,_WebSocketsSecure$1,HTTP,HTTPS,P2PWebRTCStar,P2PWebRTCDirect,TCP,UTP,QUIC,DNS,WebRTCDirect,WebTransport),_P2P$1=or$2(and$1(Reliable,base$3("p2p")),P2PWebRTCStar,P2PWebRTCDirect,WebRTCDirect,WebTransport,base$3("p2p")),_Circuit$1=or$2(and$1(_P2P$1,base$3("p2p-circuit"),_P2P$1),and$1(_P2P$1,base$3("p2p-circuit")),and$1(base$3("p2p-circuit"),_P2P$1),and$1(Reliable,base$3("p2p-circuit")),and$1(base$3("p2p-circuit"),Reliable),base$3("p2p-circuit")),CircuitRecursive=()=>or$2(and$1(_Circuit$1,CircuitRecursive),_Circuit$1),Circuit$1=CircuitRecursive(),P2P=or$2(and$1(Circuit$1,_P2P$1,Circuit$1),and$1(_P2P$1,Circuit$1),and$1(Circuit$1,_P2P$1),Circuit$1,_P2P$1);function makeMatchesFunction(e){function t(r){let n;try{n=multiaddr(r)}catch{return!1}const o=e(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function and$1(...e){function t(r){if(r.length(n=typeof o=="function"?o().partialMatch(r):o.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:makeMatchesFunction(t),partialMatch:t}}function or$2(...e){function t(n){let o=null;return e.some(a=>{const l=typeof a=="function"?a().partialMatch(n):a.partialMatch(n);return l!=null?(o=l,!0):!1}),o}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:makeMatchesFunction(t),partialMatch:t}}function base$3(e){const t=e;function r(o){let a;try{a=multiaddr(o)}catch{return!1}const l=a.protoNames();return l.length===1&&l[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:r,partialMatch:n}}const log$A=logger("libp2p:bootstrap"),DEFAULT_BOOTSTRAP_TAG_NAME="bootstrap",DEFAULT_BOOTSTRAP_TAG_VALUE=50,DEFAULT_BOOTSTRAP_TAG_TTL=12e4,DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT=1e3;var Jl,ec;class Bootstrap extends EventEmitter$2{constructor(r,n={list:[]}){if(n.list==null||n.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super();Ke(this,"timer");Ke(this,"list");Ke(this,"timeout");Ke(this,"components");Ke(this,"_init");Ke(this,Jl,this);Ke(this,ec,"@libp2p/bootstrap");this.components=r,this.timeout=n.timeout??DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT,this.list=[];for(const o of n.list){if(!P2P.matches(o)){log$A.error("Invalid multiaddr");continue}const a=multiaddr(o),l=a.getPeerId();if(l==null){log$A.error("Invalid bootstrap multiaddr without peer id");continue}const c={id:peerIdFromString(l),multiaddrs:[a],protocols:[]};this.list.push(c)}this._init=n}isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(log$A("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(r=>{log$A.error(r)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(const r of this.list){if(await this.components.peerStore.merge(r.id,{tags:{[this._init.tagName??DEFAULT_BOOTSTRAP_TAG_NAME]:{value:this._init.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE,ttl:this._init.tagTTL??DEFAULT_BOOTSTRAP_TAG_TTL}}}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:r})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}}Jl=peerDiscovery,ec=Symbol.toStringTag,Ke(Bootstrap,"tag","bootstrap");function bootstrap(e){return t=>new Bootstrap(t,e)}var TopicValidatorResult;(function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"})(TopicValidatorResult||(TopicValidatorResult={}));function mapIterable(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const n=e.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return r}class PeerMap{constructor(t){Ke(this,"map");if(this.map=new Map,t!=null)for(const[r,n]of t.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){this.map.delete(t.toString())}entries(){return mapIterable(this.map.entries(),t=>[peerIdFromString(t[0]),t[1]])}forEach(t){this.map.forEach((r,n)=>{t(r,peerIdFromString(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,r){this.map.set(t.toString(),r)}keys(){return mapIterable(this.map.keys(),t=>peerIdFromString(t))}values(){return this.map.values()}get size(){return this.map.size}}class PeerSet{constructor(t){Ke(this,"set");if(this.set=new Set,t!=null)for(const r of t)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return mapIterable(this.set.entries(),t=>{const r=peerIdFromString(t[0]);return[r,r]})}forEach(t){this.set.forEach(r=>{const n=peerIdFromString(r);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return mapIterable(this.set.values(),t=>peerIdFromString(t))}intersection(t){const r=new PeerSet;for(const n of t)this.has(n)&&r.add(n);return r}difference(t){const r=new PeerSet;for(const n of this)t.has(n)||r.add(n);return r}union(t){const r=new PeerSet;for(const n of t)r.add(n);for(const n of this)r.add(n);return r}}var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function o(u,_,b){this.fn=u,this.context=_,this.once=b||!1}function a(u,_,b,x,E){if(typeof b!="function")throw new TypeError("The listener must be a function");var I=new o(b,x||u,E),k=r?r+_:_;return u._events[k]?u._events[k].fn?u._events[k]=[u._events[k],I]:u._events[k].push(I):(u._events[k]=I,u._eventsCount++),u}function l(u,_){--u._eventsCount===0?u._events=new n:delete u._events[_]}function c(){this._events=new n,this._eventsCount=0}c.prototype.eventNames=function(){var _=[],b,x;if(this._eventsCount===0)return _;for(x in b=this._events)t.call(b,x)&&_.push(r?x.slice(1):x);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(b)):_},c.prototype.listeners=function(_){var b=r?r+_:_,x=this._events[b];if(!x)return[];if(x.fn)return[x.fn];for(var E=0,I=x.length,k=new Array(I);EglobalThis.DOMException===void 0?new AbortError$3(e):new DOMException(e),getAbortedReason$1=e=>{const t=e.reason===void 0?getDOMException$1("This operation was aborted."):e.reason;return t instanceof Error?t:getDOMException$1(t)};function pTimeout$1(e,t,r,n){let o;const a=new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){l(e);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){const{signal:u}=n;u.aborted&&c(getAbortedReason$1(u)),u.addEventListener("abort",()=>{c(getAbortedReason$1(u))})}o=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{l(r())}catch(b){c(b)}return}const u=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,_=r instanceof Error?r:new TimeoutError$1(u);typeof e.cancel=="function"&&e.cancel(),c(_)},t),(async()=>{try{l(await e)}catch(u){c(u)}finally{n.customTimers.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{clearTimeout(o),o=void 0},a}function lowerBound$1(e,t,r){let n=0,o=e.length;for(;o>0;){const a=Math.trunc(o/2);let l=n+a;r(e[l],t)<=0?(n=++l,o-=a+1):o=a}return n}var __classPrivateFieldGet$1=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},_PriorityQueue_queue;class PriorityQueue{constructor(){_PriorityQueue_queue.set(this,[])}enqueue(t,r){r={priority:0,...r};const n={priority:r.priority,run:t};if(this.size&&__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f")[this.size-1].priority>=r.priority){__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").push(n);return}const o=lowerBound$1(__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f"),n,(a,l)=>l.priority-a.priority);__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").splice(o,0,n)}dequeue(){const t=__classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").shift();return t?.run}filter(t){return __classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return __classPrivateFieldGet$1(this,_PriorityQueue_queue,"f").length}}_PriorityQueue_queue=new WeakMap;var __classPrivateFieldSet=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},__classPrivateFieldGet=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},_PQueue_instances,_PQueue_carryoverConcurrencyCount,_PQueue_isIntervalIgnored,_PQueue_intervalCount,_PQueue_intervalCap,_PQueue_interval,_PQueue_intervalEnd,_PQueue_intervalId,_PQueue_timeoutId,_PQueue_queue,_PQueue_queueClass,_PQueue_pending,_PQueue_concurrency,_PQueue_isPaused,_PQueue_throwOnTimeout,_PQueue_doesIntervalAllowAnother_get,_PQueue_doesConcurrentAllowAnother_get,_PQueue_next,_PQueue_onResumeInterval,_PQueue_isIntervalPaused_get,_PQueue_tryToStartAnother,_PQueue_initializeIntervalIfNeeded,_PQueue_onInterval,_PQueue_processQueue,_PQueue_throwOnAbort,_PQueue_onEvent;class AbortError$2 extends Error{}class PQueue extends EventEmitter$1{constructor(t){var r,n,o,a;if(super(),_PQueue_instances.add(this),_PQueue_carryoverConcurrencyCount.set(this,void 0),_PQueue_isIntervalIgnored.set(this,void 0),_PQueue_intervalCount.set(this,0),_PQueue_intervalCap.set(this,void 0),_PQueue_interval.set(this,void 0),_PQueue_intervalEnd.set(this,0),_PQueue_intervalId.set(this,void 0),_PQueue_timeoutId.set(this,void 0),_PQueue_queue.set(this,void 0),_PQueue_queueClass.set(this,void 0),_PQueue_pending.set(this,0),_PQueue_concurrency.set(this,void 0),_PQueue_isPaused.set(this,void 0),_PQueue_throwOnTimeout.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:PriorityQueue,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(o=t.interval)===null||o===void 0?void 0:o.toString())!==null&&a!==void 0?a:""}\` (${typeof t.interval})`);__classPrivateFieldSet(this,_PQueue_carryoverConcurrencyCount,t.carryoverConcurrencyCount,"f"),__classPrivateFieldSet(this,_PQueue_isIntervalIgnored,t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,"f"),__classPrivateFieldSet(this,_PQueue_intervalCap,t.intervalCap,"f"),__classPrivateFieldSet(this,_PQueue_interval,t.interval,"f"),__classPrivateFieldSet(this,_PQueue_queue,new t.queueClass,"f"),__classPrivateFieldSet(this,_PQueue_queueClass,t.queueClass,"f"),this.concurrency=t.concurrency,this.timeout=t.timeout,__classPrivateFieldSet(this,_PQueue_throwOnTimeout,t.throwOnTimeout===!0,"f"),__classPrivateFieldSet(this,_PQueue_isPaused,t.autoStart===!1,"f")}get concurrency(){return __classPrivateFieldGet(this,_PQueue_concurrency,"f")}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);__classPrivateFieldSet(this,_PQueue_concurrency,t,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this)}async add(t,r={}){return r={timeout:this.timeout,throwOnTimeout:__classPrivateFieldGet(this,_PQueue_throwOnTimeout,"f"),...r},new Promise((n,o)=>{__classPrivateFieldGet(this,_PQueue_queue,"f").enqueue(async()=>{var a,l,c;__classPrivateFieldSet(this,_PQueue_pending,(l=__classPrivateFieldGet(this,_PQueue_pending,"f"),l++,l),"f"),__classPrivateFieldSet(this,_PQueue_intervalCount,(c=__classPrivateFieldGet(this,_PQueue_intervalCount,"f"),c++,c),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new AbortError$2("The task was aborted.");let u=t({signal:r.signal});r.timeout&&(u=pTimeout$1(Promise.resolve(u),r.timeout)),r.signal&&(u=Promise.race([u,__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_throwOnAbort).call(this,r.signal)]));const _=await u;n(_),this.emit("completed",_)}catch(u){if(u instanceof TimeoutError$1&&!r.throwOnTimeout){n();return}o(u),this.emit("error",u)}finally{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_next).call(this)}},r),this.emit("add"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_tryToStartAnother).call(this)})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return __classPrivateFieldGet(this,_PQueue_isPaused,"f")?(__classPrivateFieldSet(this,_PQueue_isPaused,!1,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this),this):this}pause(){__classPrivateFieldSet(this,_PQueue_isPaused,!0,"f")}clear(){__classPrivateFieldSet(this,_PQueue_queue,new(__classPrivateFieldGet(this,_PQueue_queueClass,"f")),"f")}async onEmpty(){__classPrivateFieldGet(this,_PQueue_queue,"f").size!==0&&await __classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onEvent).call(this,"empty")}async onSizeLessThan(t){__classPrivateFieldGet(this,_PQueue_queue,"f").size__classPrivateFieldGet(this,_PQueue_queue,"f").size{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onResumeInterval).call(this)},r),"f"),!0}return!1},_PQueue_tryToStartAnother=function e(){if(__classPrivateFieldGet(this,_PQueue_queue,"f").size===0)return __classPrivateFieldGet(this,_PQueue_intervalId,"f")&&clearInterval(__classPrivateFieldGet(this,_PQueue_intervalId,"f")),__classPrivateFieldSet(this,_PQueue_intervalId,void 0,"f"),this.emit("empty"),__classPrivateFieldGet(this,_PQueue_pending,"f")===0&&this.emit("idle"),!1;if(!__classPrivateFieldGet(this,_PQueue_isPaused,"f")){const t=!__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_isIntervalPaused_get);if(__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_doesIntervalAllowAnother_get)&&__classPrivateFieldGet(this,_PQueue_instances,"a",_PQueue_doesConcurrentAllowAnother_get)){const r=__classPrivateFieldGet(this,_PQueue_queue,"f").dequeue();return r?(this.emit("active"),r(),t&&__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_initializeIntervalIfNeeded).call(this),!0):!1}}return!1},_PQueue_initializeIntervalIfNeeded=function e(){__classPrivateFieldGet(this,_PQueue_isIntervalIgnored,"f")||__classPrivateFieldGet(this,_PQueue_intervalId,"f")!==void 0||(__classPrivateFieldSet(this,_PQueue_intervalId,setInterval(()=>{__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_onInterval).call(this)},__classPrivateFieldGet(this,_PQueue_interval,"f")),"f"),__classPrivateFieldSet(this,_PQueue_intervalEnd,Date.now()+__classPrivateFieldGet(this,_PQueue_interval,"f"),"f"))},_PQueue_onInterval=function e(){__classPrivateFieldGet(this,_PQueue_intervalCount,"f")===0&&__classPrivateFieldGet(this,_PQueue_pending,"f")===0&&__classPrivateFieldGet(this,_PQueue_intervalId,"f")&&(clearInterval(__classPrivateFieldGet(this,_PQueue_intervalId,"f")),__classPrivateFieldSet(this,_PQueue_intervalId,void 0,"f")),__classPrivateFieldSet(this,_PQueue_intervalCount,__classPrivateFieldGet(this,_PQueue_carryoverConcurrencyCount,"f")?__classPrivateFieldGet(this,_PQueue_pending,"f"):0,"f"),__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_processQueue).call(this)},_PQueue_processQueue=function e(){for(;__classPrivateFieldGet(this,_PQueue_instances,"m",_PQueue_tryToStartAnother).call(this););},_PQueue_throwOnAbort=async function e(t){return new Promise((r,n)=>{t.addEventListener("abort",()=>{n(new AbortError$2("The task was aborted."))},{once:!0})})},_PQueue_onEvent=async function e(t,r){return new Promise(n=>{const o=()=>{r&&!r()||(this.off(t,o),n())};this.on(t,o)})};const codes$7={ERR_INVALID_SIGNATURE_POLICY:"ERR_INVALID_SIGNATURE_POLICY",ERR_UNHANDLED_SIGNATURE_POLICY:"ERR_UNHANDLED_SIGNATURE_POLICY",ERR_MISSING_SIGNATURE:"ERR_MISSING_SIGNATURE",ERR_MISSING_SEQNO:"ERR_MISSING_SEQNO",ERR_MISSING_KEY:"ERR_MISSING_KEY",ERR_INVALID_SIGNATURE:"ERR_INVALID_SIGNATURE",ERR_MISSING_FROM:"ERR_MISSING_FROM",ERR_UNEXPECTED_FROM:"ERR_UNEXPECTED_FROM",ERR_UNEXPECTED_SIGNATURE:"ERR_UNEXPECTED_SIGNATURE",ERR_UNEXPECTED_KEY:"ERR_UNEXPECTED_KEY",ERR_UNEXPECTED_SEQNO:"ERR_UNEXPECTED_SEQNO",ERR_TOPIC_VALIDATOR_REJECT:"ERR_TOPIC_VALIDATOR_REJECT"};class AbortError$1 extends Error{constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function getIterator(e){if(e!=null){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}function abortableSource(e,t,r){const n=r??{},o=getIterator(e);async function*a(){let l;const c=()=>{l?.()};for(t.addEventListener("abort",c);;){let u;try{if(t.aborted){const{abortMessage:b,abortCode:x}=n;throw new AbortError$1(b,x)}const _=new Promise((b,x)=>{l=()=>{const{abortMessage:E,abortCode:I}=n;x(new AbortError$1(E,I))}});u=await Promise.race([_,o.next()]),l=null}catch(_){t.removeEventListener("abort",c);const b=_.type==="aborted"&&t.aborted;if(b&&n.onAbort!=null&&n.onAbort(e),typeof o.return=="function")try{const x=o.return();x instanceof Promise&&x.catch(E=>{n.onReturnError!=null&&n.onReturnError(E)})}catch(x){n.onReturnError!=null&&n.onReturnError(x)}if(b&&n.returnOnAbort===!0)return;throw _}if(u.done===!0)break;yield u.value}t.removeEventListener("abort",c)}return a()}function abortableSink(e,t,r){return n=>e(abortableSource(n,t,r))}function abortableDuplex(e,t,r){return{sink:abortableSink(e.sink,t,{...r,onAbort:void 0}),source:abortableSource(e.source,t,r)}}const log$z=logger("libp2p-pubsub:peer-streams");class PeerStreams extends EventEmitter$2{constructor(r){super();Ke(this,"id");Ke(this,"protocol");Ke(this,"outboundStream");Ke(this,"inboundStream");Ke(this,"_rawOutboundStream");Ke(this,"_rawInboundStream");Ke(this,"_inboundAbortController");Ke(this,"closed");this.id=r.id,this.protocol=r.protocol,this._inboundAbortController=new AbortController,this.closed=!1}get isReadable(){return Boolean(this.inboundStream)}get isWritable(){return Boolean(this.outboundStream)}write(r){if(this.outboundStream==null){const n=this.id.toString();throw new Error("No writable connection to "+n)}this.outboundStream.push(r instanceof Uint8Array?new Uint8ArrayList(r):r)}attachInboundStream(r){return this._rawInboundStream=r,this.inboundStream=abortableSource(pipe(this._rawInboundStream,n=>decode$a(n)),this._inboundAbortController.signal,{returnOnAbort:!0}),this.dispatchEvent(new CustomEvent$1("stream:inbound")),this.inboundStream}async attachOutboundStream(r){const n=this.outboundStream;return this.outboundStream!=null&&this.outboundStream.end(),this._rawOutboundStream=r,this.outboundStream=pushable({objectMode:!0,onEnd:o=>{this._rawOutboundStream!=null&&this._rawOutboundStream.closeWrite().catch(a=>{log$z("error closing outbound stream",a)}),this._rawOutboundStream=void 0,this.outboundStream=void 0,o!=null&&this.dispatchEvent(new CustomEvent$1("close"))}}),pipe(this.outboundStream,o=>encode$c(o),this._rawOutboundStream).catch(o=>{log$z.error(o)}),n==null&&this.dispatchEvent(new CustomEvent$1("stream:outbound")),this.outboundStream}close(){this.closed||(this.closed=!0,this.outboundStream!=null&&this.outboundStream.end(),this.inboundStream!=null&&this._inboundAbortController.abort(),this._rawOutboundStream=void 0,this.outboundStream=void 0,this._rawInboundStream=void 0,this.inboundStream=void 0,this.dispatchEvent(new CustomEvent$1("close")))}}const hashName={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function pbkdf2(e,t,r,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){const c=Object.keys(hashName).join(" / ");throw new CodeError(`Hash '${o}' is unknown or not supported. Must be ${c}`,"ERR_UNSUPPORTED_HASH_TYPE")}const a=hashName[o],l=pbkdf2$1(e,t,r,n,a);return util$7.exports.encode64(l,null)}function randomSeqno(){return BigInt(`0x${toString$5(randomBytes(8),"base16")}`)}const msgId=(e,t)=>{const r=fromString$1(t.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(e.length+r.length);return n.set(e,0),n.set(r,e.length),n},noSignMsgId=e=>sha256$1.encode(e),ensureArray=function(e){return Array.isArray(e)?e:[e]},isSigned=async e=>{if(e.sequenceNumber==null||e.from==null||e.signature==null)return!1;const t=peerIdFromBytes(e.from);return t.publicKey!=null?!0:e.key!=null?(await peerIdFromKeys(e.key)).equals(t):!1},toMessage=async e=>{if(e.from==null)throw new CodeError("RPC message was missing from",codes$7.ERR_MISSING_FROM);if(!await isSigned(e))return{type:"unsigned",topic:e.topic??"",data:e.data??new Uint8Array(0)};const t=peerIdFromBytes(e.from),r={type:"signed",from:peerIdFromBytes(e.from),topic:e.topic??"",sequenceNumber:bigIntFromBytes(e.sequenceNumber??new Uint8Array(0)),data:e.data??new Uint8Array(0),signature:e.signature??new Uint8Array(0),key:e.key??t.publicKey??new Uint8Array(0)};if(r.key.length===0)throw new CodeError("Signed RPC message was missing key",codes$7.ERR_MISSING_KEY);return r},toRpcMessage=e=>e.type==="signed"?{from:e.from.multihash.bytes,data:e.data,sequenceNumber:bigIntToBytes(e.sequenceNumber),topic:e.topic,signature:e.signature,key:e.key}:{data:e.data,topic:e.topic},bigIntToBytes=e=>{let t=e.toString(16);return t.length%2!==0&&(t=`0${t}`),fromString$1(t,"base16")},bigIntFromBytes=e=>BigInt(`0x${toString$5(e,"base16")}`),SignPrefix=fromString$1("libp2p-pubsub:");async function signMessage(e,t,r){if(e.privateKey==null)throw new Error("Cannot sign message, no private key present");if(e.publicKey==null)throw new Error("Cannot sign message, no public key present");const n={type:"signed",topic:t.topic,data:t.data,sequenceNumber:t.sequenceNumber,from:e},o=concat$1([SignPrefix,r(toRpcMessage(n)).subarray()]),a=await unmarshalPrivateKey(e.privateKey);return n.signature=await a.sign(o),n.key=e.publicKey,n}async function verifySignature(e,t){if(e.type!=="signed")throw new Error('Message type must be "signed" to be verified');if(e.signature==null)throw new Error("Message must contain a signature to be verified");if(e.from==null)throw new Error("Message must contain a from property to be verified");const r=concat$1([SignPrefix,t({...toRpcMessage(e),signature:void 0,key:void 0}).subarray()]),n=await messagePublicKey(e);return unmarshalPublicKey(n).verify(r,e.signature)}async function messagePublicKey(e){if(e.type!=="signed")throw new Error('Message type must be "signed" to have a public key');if(e.from==null)throw new Error("Could not get the public key from the originator id");if(e.key!=null){const t=await peerIdFromKeys(e.key);if(t.publicKey!=null)return t.publicKey}if(e.from.publicKey!=null)return e.from.publicKey;throw new Error("Could not get the public key from the originator id")}const log$y=logger("libp2p:pubsub");class PubSubBaseProtocol extends EventEmitter$2{constructor(r,n){super();Ke(this,"started");Ke(this,"topics");Ke(this,"subscriptions");Ke(this,"peers");Ke(this,"globalSignaturePolicy");Ke(this,"canRelayMessage");Ke(this,"emitSelf");Ke(this,"topicValidators");Ke(this,"queue");Ke(this,"multicodecs");Ke(this,"components");Ke(this,"_registrarTopologyIds");Ke(this,"enabled");Ke(this,"maxInboundStreams");Ke(this,"maxOutboundStreams");const{multicodecs:o=[],globalSignaturePolicy:a="StrictSign",canRelayMessage:l=!1,emitSelf:c=!1,messageProcessingConcurrency:u=10,maxInboundStreams:_=1,maxOutboundStreams:b=1}=n;this.components=r,this.multicodecs=ensureArray(o),this.enabled=n.enabled!==!1,this.started=!1,this.topics=new Map,this.subscriptions=new Set,this.peers=new PeerMap,this.globalSignaturePolicy=a==="StrictNoSign"?"StrictNoSign":"StrictSign",this.canRelayMessage=l,this.emitSelf=c,this.topicValidators=new Map,this.queue=new PQueue({concurrency:u}),this.maxInboundStreams=_,this.maxOutboundStreams=b,this._onIncomingStream=this._onIncomingStream.bind(this),this._onPeerConnected=this._onPeerConnected.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this)}async start(){if(this.started||!this.enabled)return;log$y("starting");const r=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>{await r.handle(o,this._onIncomingStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})}));const n={onConnect:this._onPeerConnected,onDisconnect:this._onPeerDisconnected};this._registrarTopologyIds=await Promise.all(this.multicodecs.map(async o=>r.register(o,n))),log$y("started"),this.started=!0}async stop(){if(!this.started||!this.enabled)return;const r=this.components.registrar;this._registrarTopologyIds!=null&&this._registrarTopologyIds?.forEach(n=>{r.unregister(n)}),await Promise.all(this.multicodecs.map(async n=>{await r.unhandle(n)})),log$y("stopping");for(const n of this.peers.values())n.close();this.peers.clear(),this.subscriptions=new Set,this.started=!1,log$y("stopped")}isStarted(){return this.started}_onIncomingStream(r){const{stream:n,connection:o}=r,a=o.remotePeer;if(n.protocol==null){n.abort(new Error("Stream was not multiplexed"));return}const l=this.addPeer(a,n.protocol),c=l.attachInboundStream(n);this.processMessages(a,c,l).catch(u=>{log$y(u)})}_onPeerConnected(r,n){log$y("connected %p",r),Promise.resolve().then(async()=>{try{const o=await n.newStream(this.multicodecs);if(o.protocol==null){o.abort(new Error("Stream was not multiplexed"));return}await this.addPeer(r,o.protocol).attachOutboundStream(o)}catch(o){log$y.error(o)}this.send(r,{subscriptions:Array.from(this.subscriptions).map(o=>o.toString()),subscribe:!0})}).catch(o=>{log$y.error(o)})}_onPeerDisconnected(r,n){const o=r.toString();log$y("connection ended",o),this._removePeer(r)}addPeer(r,n){const o=this.peers.get(r);if(o!=null)return o;log$y("new peer %p",r);const a=new PeerStreams({id:r,protocol:n});return this.peers.set(r,a),a.addEventListener("close",()=>this._removePeer(r),{once:!0}),a}_removePeer(r){const n=this.peers.get(r);if(n!=null){n.close(),log$y("delete peer %p",r),this.peers.delete(r);for(const o of this.topics.values())o.delete(r);return n}}async processMessages(r,n,o){try{await pipe(n,async a=>{for await(const l of a){const c=this.decodeRpc(l),u=[];for(const _ of c.messages??[]){if(_.from==null||_.data==null||_.topic==null){log$y("message from %p was missing from, data or topic fields, dropping",r);continue}u.push({from:_.from,data:_.data,topic:_.topic,sequenceNumber:_.sequenceNumber??void 0,signature:_.signature??void 0,key:_.key??void 0})}this.processRpc(r,o,{subscriptions:(c.subscriptions??[]).map(_=>({subscribe:Boolean(_.subscribe),topic:_.topic??""})),messages:u}).catch(_=>{log$y(_)})}})}catch(a){this._onPeerDisconnected(o.id,a)}}async processRpc(r,n,o){if(!this.acceptFrom(r))return log$y("received message from unacceptable peer %p",r),!1;log$y("rpc from %p",r);const{subscriptions:a,messages:l}=o;return a!=null&&a.length>0&&(log$y("subscription update from %p",r),a.forEach(c=>{this.processRpcSubOpt(r,c)}),super.dispatchEvent(new CustomEvent$1("subscription-change",{detail:{peerId:n.id,subscriptions:a.map(({topic:c,subscribe:u})=>({topic:`${c??""}`,subscribe:Boolean(u)}))}}))),l!=null&&l.length>0&&(log$y("messages from %p",r),this.queue.addAll(l.map(c=>async()=>{if(c.topic==null||!this.subscriptions.has(c.topic)&&!this.canRelayMessage)return log$y("received message we didn't subscribe to. Dropping."),!1;try{const u=await toMessage(c);await this.processMessage(r,u)}catch(u){log$y.error(u)}})).catch(c=>{log$y(c)})),!0}processRpcSubOpt(r,n){const o=n.topic;if(o==null)return;let a=this.topics.get(o);a==null&&(a=new PeerSet,this.topics.set(o,a)),n.subscribe===!0?a.add(r):a.delete(r)}async processMessage(r,n){if(!(this.components.peerId.equals(r)&&!this.emitSelf)){try{await this.validate(r,n)}catch(o){log$y("Message is invalid, dropping it. %O",o);return}this.subscriptions.has(n.topic)&&(!this.components.peerId.equals(r)||this.emitSelf)&&super.dispatchEvent(new CustomEvent$1("message",{detail:n})),await this.publishMessage(r,n)}}getMsgId(r){switch(this.globalSignaturePolicy){case"StrictSign":if(r.type!=="signed")throw new CodeError('Message type should be "signed" when signature policy is StrictSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(r.sequenceNumber==null)throw new CodeError("Need seqno when signature policy is StrictSign but it was missing",codes$7.ERR_MISSING_SEQNO);if(r.key==null)throw new CodeError("Need key when signature policy is StrictSign but it was missing",codes$7.ERR_MISSING_KEY);return msgId(r.key,r.sequenceNumber);case"StrictNoSign":return noSignMsgId(r.data);default:throw new CodeError("Cannot get message id: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}}acceptFrom(r){return!0}send(r,n){const{messages:o,subscriptions:a,subscribe:l}=n;this.sendRpc(r,{subscriptions:(a??[]).map(c=>({topic:c,subscribe:Boolean(l)})),messages:(o??[]).map(toRpcMessage)})}sendRpc(r,n){const o=this.peers.get(r);if(o==null||!o.isWritable){log$y.error("Cannot send RPC to %p as there is no open stream to it available",r);return}o.write(this.encodeRpc(n))}async validate(r,n){switch(this.globalSignaturePolicy){case"StrictNoSign":if(n.type!=="unsigned")throw new CodeError('Message type should be "unsigned" when signature policy is StrictNoSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(n.signature!=null)throw new CodeError("StrictNoSigning: signature should not be present",codes$7.ERR_UNEXPECTED_SIGNATURE);if(n.key!=null)throw new CodeError("StrictNoSigning: key should not be present",codes$7.ERR_UNEXPECTED_KEY);if(n.sequenceNumber!=null)throw new CodeError("StrictNoSigning: seqno should not be present",codes$7.ERR_UNEXPECTED_SEQNO);break;case"StrictSign":if(n.type!=="signed")throw new CodeError('Message type should be "signed" when signature policy is StrictSign but it was not',codes$7.ERR_MISSING_SIGNATURE);if(n.signature==null)throw new CodeError("StrictSigning: Signing required and no signature was present",codes$7.ERR_MISSING_SIGNATURE);if(n.sequenceNumber==null)throw new CodeError("StrictSigning: Signing required and no sequenceNumber was present",codes$7.ERR_MISSING_SEQNO);if(!await verifySignature(n,this.encodeMessage.bind(this)))throw new CodeError("StrictSigning: Invalid message signature",codes$7.ERR_INVALID_SIGNATURE);break;default:throw new CodeError("Cannot validate message: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}const a=this.topicValidators.get(n.topic);if(a!=null){const l=await a(r,n);if(l===TopicValidatorResult.Reject||l===TopicValidatorResult.Ignore)throw new CodeError("Message validation failed",codes$7.ERR_TOPIC_VALIDATOR_REJECT)}}async buildMessage(r){switch(this.globalSignaturePolicy){case"StrictSign":return signMessage(this.components.peerId,r,this.encodeMessage.bind(this));case"StrictNoSign":return Promise.resolve({type:"unsigned",...r});default:throw new CodeError("Cannot build message: unhandled signature policy",codes$7.ERR_UNHANDLED_SIGNATURE_POLICY)}}getSubscribers(r){if(!this.started)throw new CodeError("not started yet","ERR_NOT_STARTED_YET");if(r==null)throw new CodeError("topic is required","ERR_NOT_VALID_TOPIC");const n=this.topics.get(r.toString());return n==null?[]:Array.from(n.values())}async publish(r,n){if(!this.started)throw new Error("Pubsub has not started");const o={from:this.components.peerId,topic:r,data:n??new Uint8Array(0),sequenceNumber:randomSeqno()};log$y("publish topic: %s from: %p data: %m",r,o.from,o.data);const a=await this.buildMessage(o);let l=!1;this.emitSelf&&this.subscriptions.has(r)&&(l=!0,super.dispatchEvent(new CustomEvent$1("message",{detail:a})));const c=await this.publishMessage(this.components.peerId,a);return l&&(c.recipients=[...c.recipients,this.components.peerId]),c}subscribe(r){if(!this.started)throw new Error("Pubsub has not started");if(log$y("subscribe to topic: %s",r),!this.subscriptions.has(r)){this.subscriptions.add(r);for(const n of this.peers.keys())this.send(n,{subscriptions:[r],subscribe:!0})}}unsubscribe(r){if(!this.started)throw new Error("Pubsub is not started");super.removeEventListener(r);const n=this.subscriptions.has(r);if(log$y("unsubscribe from %s - am subscribed %s",r,n),n){this.subscriptions.delete(r);for(const o of this.peers.keys())this.send(o,{subscriptions:[r],subscribe:!1})}}getTopics(){if(!this.started)throw new Error("Pubsub is not started");return Array.from(this.subscriptions)}getPeers(){if(!this.started)throw new Error("Pubsub is not started");return Array.from(this.peers.keys())}}class SimpleTimeCache{constructor(t){Ke(this,"entries");Ke(this,"validityMs");Ke(this,"lastPruneTime",0);this.entries=new Map,this.validityMs=t.validityMs}put(t,r){this.entries.set(t,{value:r,validUntilMs:Date.now()+this.validityMs}),this.prune()}prune(){const t=Date.now();if(!(t-this.lastPruneTime<200)){this.lastPruneTime=t;for(const[r,n]of this.entries.entries())if(n.validUntilMs=Date.now()?r.value:void 0}clear(){this.entries=new Map,this.lastPruneTime=0}}logger("libp2p:floodsub");const multicodec="/floodsub/1.0.0";var RPC;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.subscribe!=null&&(a.uint32(8),a.bool(o.subscribe)),o.topic!=null&&(a.uint32(18),a.string(o.topic)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.subscribe=o.bool();break;case 2:l.topic=o.string();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.SubOpts||(e.SubOpts={})),function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.from!=null&&(a.uint32(10),a.bytes(o.from)),o.data!=null&&(a.uint32(18),a.bytes(o.data)),o.sequenceNumber!=null&&(a.uint32(26),a.bytes(o.sequenceNumber)),o.topic!=null&&(a.uint32(34),a.string(o.topic)),o.signature!=null&&(a.uint32(42),a.bytes(o.signature)),o.key!=null&&(a.uint32(50),a.bytes(o.key)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.from=o.bytes();break;case 2:l.data=o.bytes();break;case 3:l.sequenceNumber=o.bytes();break;case 4:l.topic=o.string();break;case 5:l.signature=o.bytes();break;case 6:l.key=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())}(e.Message||(e.Message={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.subscriptions!=null)for(const a of r.subscriptions)n.uint32(10),e.SubOpts.codec().encode(a,n);if(r.messages!=null)for(const a of r.messages)n.uint32(18),e.Message.codec().encode(a,n);r.control!=null&&(n.uint32(26),ControlMessage.codec().encode(r.control,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={subscriptions:[],messages:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.subscriptions.push(e.SubOpts.codec().decode(r,r.uint32()));break;case 2:o.messages.push(e.Message.codec().decode(r,r.uint32()));break;case 3:o.control=ControlMessage.codec().decode(r,r.uint32());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(RPC||(RPC={}));var ControlMessage;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.ihave!=null)for(const a of r.ihave)n.uint32(10),ControlIHave.codec().encode(a,n);if(r.iwant!=null)for(const a of r.iwant)n.uint32(18),ControlIWant.codec().encode(a,n);if(r.graft!=null)for(const a of r.graft)n.uint32(26),ControlGraft.codec().encode(a,n);if(r.prune!=null)for(const a of r.prune)n.uint32(34),ControlPrune.codec().encode(a,n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={ihave:[],iwant:[],graft:[],prune:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.ihave.push(ControlIHave.codec().decode(r,r.uint32()));break;case 2:o.iwant.push(ControlIWant.codec().decode(r,r.uint32()));break;case 3:o.graft.push(ControlGraft.codec().decode(r,r.uint32()));break;case 4:o.prune.push(ControlPrune.codec().decode(r,r.uint32()));break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlMessage||(ControlMessage={}));var ControlIHave;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),r.messageIDs!=null)for(const a of r.messageIDs)n.uint32(18),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={messageIDs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;case 2:o.messageIDs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlIHave||(ControlIHave={}));var ControlIWant;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.messageIDs!=null)for(const a of r.messageIDs)n.uint32(10),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={messageIDs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.messageIDs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlIWant||(ControlIWant={}));var ControlGraft;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlGraft||(ControlGraft={}));var ControlPrune;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.topic!=null&&(n.uint32(10),n.string(r.topic)),r.peers!=null)for(const a of r.peers)n.uint32(18),PeerInfo.codec().encode(a,n);r.backoff!=null&&(n.uint32(24),n.uint64(r.backoff)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={peers:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.topic=r.string();break;case 2:o.peers.push(PeerInfo.codec().decode(r,r.uint32()));break;case 3:o.backoff=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ControlPrune||(ControlPrune={}));var PeerInfo;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.peerID!=null&&(n.uint32(10),n.bytes(r.peerID)),r.signedPeerRecord!=null&&(n.uint32(18),n.bytes(r.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.peerID=r.bytes();break;case 2:o.signedPeerRecord=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerInfo||(PeerInfo={}));const log$x=logger("libp2p:floodsub");class FloodSub extends PubSubBaseProtocol{constructor(r,n){super(r,{...n,canRelayMessage:!0,multicodecs:[multicodec]});Ke(this,"seenCache");this.seenCache=new SimpleTimeCache({validityMs:n?.seenTTL??3e4})}decodeRpc(r){return RPC.decode(r)}encodeRpc(r){return RPC.encode(r)}decodeMessage(r){return RPC.Message.decode(r)}encodeMessage(r){return RPC.Message.encode(r)}async processMessage(r,n){const o=await super.getMsgId(n),a=toString$5(o,"base64");this.seenCache.has(a)||(this.seenCache.put(a,!0),await super.processMessage(r,n))}async publishMessage(r,n){const o=this.getSubscribers(n.topic),a=[];return o==null||o.length===0?(log$x("no peers are subscribed to topic %s",n.topic),{recipients:a}):(o.forEach(l=>{if(this.components.peerId.equals(l)){log$x("not sending message on topic %s to myself",n.topic);return}if(l.equals(r)){log$x("not sending message on topic %s to sender %p",n.topic,l);return}log$x("publish msgs on topics %s %p",n.topic,l),a.push(l),this.send(l,{messages:[n]})}),{recipients:a})}}function floodsub(e={}){return t=>new FloodSub(t,e)}var RateLimiterAbstract_1=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){this._points=t>=0?t:4}get duration(){return this._duration}set duration(t){this._duration=typeof t>"u"?1:t}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:Boolean(t)}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=typeof t>"u"?Math.ceil(this.msDuration/this.points):t}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}},BlockedKeys_1$1=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){const t=Date.now();Object.keys(this._keys).forEach(r=>{this._keys[r]<=t&&delete this._keys[r]}),this._addedKeysAmount=Object.keys(this._keys).length}add(t,r){this.addMs(t,r*1e3)}addMs(t,r){this._keys[t]=Date.now()+r,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(t){const r=this._keys[t];if(r&&r>=Date.now()){this.collectExpired();const n=Date.now();return r>=n?r-n:0}return 0}delete(t){t?delete this._keys[t]:Object.keys(this._keys).forEach(r=>{delete this._keys[r]})}};const BlockedKeys$1=BlockedKeys_1$1;var BlockedKeys_1=BlockedKeys$1,RateLimiterRes_1=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=Boolean(t)}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}};const RateLimiterAbstract$3=RateLimiterAbstract_1,BlockedKeys=BlockedKeys_1,RateLimiterRes$b=RateLimiterRes_1;var RateLimiterStoreAbstract_1=class extends RateLimiterAbstract$3{constructor(t={}){super(t),this.inMemoryBlockOnConsumed=t.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=t.inMemoryBlockDuration,this.insuranceLimiter=t.insuranceLimiter,this._inMemoryBlockedKeys=new BlockedKeys}get client(){return this._client}set client(t){if(typeof t>"u")throw new Error("storeClient is not set");this._client=t}_afterConsume(t,r,n,o,a,l={}){const c=this._getRateLimiterRes(n,o,a);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&c.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,c.msBeforeNext),c.consumedPoints>this.points?r(c):t(c);if(c.consumedPoints>this.points){let u=Promise.resolve();this.blockDuration>0&&c.consumedPoints<=this.points+o&&(c.msBeforeNext=this.msBlockDuration,u=this._block(n,c.consumedPoints,this.msBlockDuration,l)),this.inMemoryBlockOnConsumed>0&&c.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),c.msBeforeNext=this.msInMemoryBlockDuration),u.then(()=>{r(c)}).catch(_=>{r(_)})}else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{n(u)}).catch(u=>{o(u)}):o(t)}getInMemoryBlockMsBeforeExpire(t){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(t):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(t){if(this._inMemoryBlockOnConsumed=t?parseInt(t):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(t){if(this._inMemoryBlockDuration=t?parseInt(t):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(t){if(typeof t<"u"&&!(t instanceof RateLimiterAbstract$3))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=t,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(t,r,n={}){const o=r*1e3;return this._block(this.getKey(t),this.points+1,o,n)}set(t,r,n,o={}){const a=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(t),r,a,o)}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=this.getKey(t),c=this.getInMemoryBlockMsBeforeExpire(l);if(c>0)return a(new RateLimiterRes$b(0,c));this._upsert(l,r,this._getKeySecDuration(n)*1e3,!1,n).then(u=>{this._afterConsume(o,a,l,r,u)}).catch(u=>{this._handleError(u,"consume",o,a,t,r,n)})})}penalty(t,r=1,n={}){const o=this.getKey(t);return new Promise((a,l)=>{this._upsert(o,r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{a(this._getRateLimiterRes(o,r,c))}).catch(c=>{this._handleError(c,"penalty",a,l,t,r,n)})})}reward(t,r=1,n={}){const o=this.getKey(t);return new Promise((a,l)=>{this._upsert(o,-r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{a(this._getRateLimiterRes(o,-r,c))}).catch(c=>{this._handleError(c,"reward",a,l,t,r,n)})})}get(t,r={}){const n=this.getKey(t);return new Promise((o,a)=>{this._get(n,r).then(l=>{o(l===null||typeof l>"u"?null:this._getRateLimiterRes(n,0,l))}).catch(l=>{this._handleError(l,"get",o,a,t,r)})})}delete(t,r={}){const n=this.getKey(t);return new Promise((o,a)=>{this._delete(n,r).then(l=>{this._inMemoryBlockedKeys.delete(n),o(l)}).catch(l=>{this._handleError(l,"delete",o,a,t,r)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(t,r,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(t,r,n,o={}){return new Promise((a,l)=>{this._upsert(t,r,n,!0,o).then(()=>{a(new RateLimiterRes$b(0,n>0?n:-1,r))}).catch(c=>{this._handleError(c,"block",a,l,this.parseKey(t),n/1e3,o)})})}_get(t,r={}){throw new Error("You have to implement the method '_get'!")}_delete(t,r={}){throw new Error("You have to implement the method '_delete'!")}_upsert(t,r,n,o=!1,a={}){throw new Error("You have to implement the method '_upsert'!")}};const RateLimiterStoreAbstract$4=RateLimiterStoreAbstract_1,RateLimiterRes$a=RateLimiterRes_1,incrTtlLuaScript="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ";class RateLimiterRedis$1 extends RateLimiterStoreAbstract$4{constructor(t){super(t),this.client=t.storeClient,this._rejectIfRedisNotReady=!!t.rejectIfRedisNotReady,this.useRedisPackage=t.useRedisPackage,this.useRedis3AndLowerPackage=t.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:incrTtlLuaScript})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(t,r,n){let[o,a]=n;Array.isArray(o)&&([,o]=o,[,a]=a);const l=new RateLimiterRes$a;return l.consumedPoints=parseInt(o),l.isFirstInDuration=l.consumedPoints===r,l.remainingPoints=Math.max(this.points-l.consumedPoints,0),l.msBeforeNext=a,l}async _upsert(t,r,n,o=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");const a=Math.floor(n/1e3),l=this.client.multi();return o?(a>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.set(t,r,"EX",a):l.set(t,r,{EX:a}):l.set(t,r),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.pttl(t).exec(!0):l.pTTL(t).exec(!0)):a>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([t].concat([String(r),String(a)])):this.useRedis3AndLowerPackage?new Promise((c,u)=>{const _=function(b,x){return b?u(b):c(x)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(t,r,a,_):this.client.eval(incrTtlLuaScript,1,t,r,a,_)}):this.client.eval(incrTtlLuaScript,{keys:[t],arguments:[String(r),String(a)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?l.incrby(t,r).pttl(t).exec(!0):l.incrBy(t,r).pTTL(t).exec(!0)}async _get(t){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(t).pttl(t).exec().then(r=>{const[[,n]]=r;return n===null?null:r}):this.client.multi().get(t).pTTL(t).exec(!0).then(r=>{const[n]=r;return n===null?null:r})}_delete(t){return this.client.del(t).then(r=>r>0)}}var RateLimiterRedis_1=RateLimiterRedis$1;const RateLimiterStoreAbstract$3=RateLimiterStoreAbstract_1,RateLimiterRes$9=RateLimiterRes_1;function getDriverVersion(e){try{const t=e.client?e.client:e,{version:r}=t.topology.s.options.metadata.driver,n=r.split(".").map(o=>parseInt(o));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}class RateLimiterMongo$1 extends RateLimiterStoreAbstract$3{constructor(t){super(t),this.dbName=t.dbName,this.tableName=t.tableName,this.indexKeyPrefix=t.indexKeyPrefix,t.mongo?this.client=t.mongo:this.client=t.storeClient,typeof this.client.then=="function"?this.client.then(r=>{this.client=r,this._initCollection(),this._driverVersion=getDriverVersion(this.client)}):(this._initCollection(),this._driverVersion=getDriverVersion(this.client))}get dbName(){return this._dbName}set dbName(t){this._dbName=typeof t>"u"?RateLimiterMongo$1.getDbName():t}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(t){this._tableName=typeof t>"u"?this.keyPrefix:t}get client(){return this._client}set client(t){if(typeof t>"u")throw new Error("mongo is not set");this._client=t}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(t){this._indexKeyPrefix=t||{}}_initCollection(){const r=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);r.createIndex({expire:-1},{expireAfterSeconds:0}),r.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=r}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$9;let a;return typeof n.value>"u"?a=n:a=n.value,o.isFirstInDuration=a.points===r,o.consumedPoints=a.points,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=a.expire!==null?Math.max(new Date(a.expire).getTime()-Date.now(),0):-1,o}_upsert(t,r,n,o=!1,a={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const l=a.attrs||{};let c,u;o?(c={key:t},c=Object.assign(c,l),u={$set:{key:t,points:r,expire:n>0?new Date(Date.now()+n):null}},u.$set=Object.assign(u.$set,l)):(c={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:t},c=Object.assign(c,l),u={$setOnInsert:{key:t,expire:n>0?new Date(Date.now()+n):null},$inc:{points:r}},u.$setOnInsert=Object.assign(u.$setOnInsert,l));const _={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?_.returnDocument="after":_.returnOriginal=!1,new Promise((b,x)=>{this._collection.findOneAndUpdate(c,u,_).then(E=>{b(E)}).catch(E=>{if(E&&E.code===11e3){const I=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:t},l),k={$set:Object.assign({key:t,points:r,expire:n>0?new Date(Date.now()+n):null},l)};this._collection.findOneAndUpdate(I,k,_).then(T=>{b(T)}).catch(T=>{T&&T.code===11e3?this._upsert(t,r,n,o).then(O=>b(O)).catch(O=>x(O)):x(T)})}else x(E)})})}_get(t,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const n=r.attrs||{},o=Object.assign({key:t,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(o)}_delete(t,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));const n=r.attrs||{},o=Object.assign({key:t},n);return this._collection.deleteOne(o).then(a=>a.deletedCount>0)}}var RateLimiterMongo_1=RateLimiterMongo$1;const RateLimiterStoreAbstract$2=RateLimiterStoreAbstract_1,RateLimiterRes$8=RateLimiterRes_1;class RateLimiterMySQL$1 extends RateLimiterStoreAbstract$2{constructor(t,r=null){super(t),this.client=t.storeClient,this.clientType=t.storeType,this.dbName=t.dbName,this.tableName=t.tableName,this.clearExpiredByTimeout=t.clearExpiredByTimeout,this.tableCreated=t.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}clearExpired(t){return new Promise(r=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,t],()=>{this._releaseConnection(n),r()})}).catch(()=>{r()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((t,r)=>{this.client.getConnection((n,o)=>{if(n)return r(n);t(o)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(t){switch(this.clientType){case"pool":return t.release();case"sequelize":return this.client.connectionManager.releaseConnection(t);case"knex":return this.client.client.releaseConnection(t);default:return!0}}_createDbAndTable(){return new Promise((t,r)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,o=>{if(o)return this._releaseConnection(n),r(o);n.query(this._getCreateTableStmt(),a=>{if(a)return this._releaseConnection(n),r(a);this._releaseConnection(n),t()})})}).catch(n=>{r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(t){if(typeof t>"u")if(this.client.constructor.name==="Connection")t="connection";else if(this.client.constructor.name==="Pool")t="pool";else if(this.client.constructor.name==="Sequelize")t="sequelize";else throw new Error("storeType is not defined");this._clientType=t.toLowerCase()}get dbName(){return this._dbName}set dbName(t){this._dbName=typeof t>"u"?"rtlmtrflx":t}get tableName(){return this._tableName}set tableName(t){this._tableName=typeof t>"u"?this.keyPrefix:t}get tableCreated(){return this._tableCreated}set tableCreated(t){this._tableCreated=typeof t>"u"?!1:!!t}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(t){this._clearExpiredByTimeout=typeof t>"u"?!0:Boolean(t)}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$8,[a]=n;return o.isFirstInDuration=r===a.points,o.consumedPoints=o.isFirstInDuration?r:a.points,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=a.expire?Math.max(a.expire-Date.now(),0):-1,o}_upsertTransaction(t,r,n,o,a){return new Promise((l,c)=>{t.query("BEGIN",u=>{if(u)return t.rollback(),c(u);const _=Date.now(),b=o>0?_+o:null;let x,E;a?(x=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = ?, expire = ?;`,E=[this.dbName,this.tableName,r,n,b,n,b]):(x=`INSERT INTO ??.?? VALUES (?, ?, ?) @@ -125,8 +125,8 @@ hooks.version="2.29.4";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min END, expire = ${l} RETURNING points, expire;`,values:[t,r,a,Date.now()]})}_get(t){return this.tableCreated?new Promise((r,n)=>{this._query({name:"rlflx-get",text:` - SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[t,Date.now()]}).then(o=>{o.rowCount===0&&(o=null),r(o)}).catch(o=>{n(o)})}):Promise.reject(Error("Table is not created yet"))}_delete(t){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[t]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}}var RateLimiterPostgres_1=RateLimiterPostgres$1,Record_1=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t)}get expiresAt(){return this._expiresAt}set expiresAt(t){!(t instanceof Date)&&Number.isInteger(t)&&(t=new Date(t)),this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}};const Record=Record_1,RateLimiterRes$6=RateLimiterRes_1;var MemoryStorage_1=class{constructor(){this._storage={}}incrby(t,r,n){if(this._storage[t]){const o=this._storage[t].expiresAt?this._storage[t].expiresAt.getTime()-new Date().getTime():-1;return o!==0?(this._storage[t].value=this._storage[t].value+r,new RateLimiterRes$6(0,o,this._storage[t].value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){const o=n*1e3;return this._storage[t]&&this._storage[t].timeoutId&&clearTimeout(this._storage[t].timeoutId),this._storage[t]=new Record(r,o>0?new Date(Date.now()+o):null),o>0&&(this._storage[t].timeoutId=setTimeout(()=>{delete this._storage[t]},o),this._storage[t].timeoutId.unref&&this._storage[t].timeoutId.unref()),new RateLimiterRes$6(0,o===0?-1:o,this._storage[t].value,!0)}get(t){if(this._storage[t]){const r=this._storage[t].expiresAt?this._storage[t].expiresAt.getTime()-new Date().getTime():-1;return new RateLimiterRes$6(0,r,this._storage[t].value,!1)}return null}delete(t){return this._storage[t]?(this._storage[t].timeoutId&&clearTimeout(this._storage[t].timeoutId),delete this._storage[t],!0):!1}};const RateLimiterAbstract$2=RateLimiterAbstract_1,MemoryStorage=MemoryStorage_1,RateLimiterRes$5=RateLimiterRes_1;class RateLimiterMemory$2 extends RateLimiterAbstract$2{constructor(t={}){super(t),this._memoryStorage=new MemoryStorage}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=this.getKey(t),c=this._getKeySecDuration(n);let u=this._memoryStorage.incrby(l,r,c);if(u.remainingPoints=Math.max(this.points-u.consumedPoints,0),u.consumedPoints>this.points)this.blockDuration>0&&u.consumedPoints<=this.points+r&&(u=this._memoryStorage.set(l,u.consumedPoints,this.blockDuration)),a(u);else if(this.execEvenly&&u.msBeforeNext>0&&!u.isFirstInDuration){let _=Math.ceil(u.msBeforeNext/(u.remainingPoints+2));_{const l=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,r,l);c.remainingPoints=Math.max(this.points-c.consumedPoints,0),a(c)})}reward(t,r=1,n={}){const o=this.getKey(t);return new Promise(a=>{const l=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,-r,l);c.remainingPoints=Math.max(this.points-c.consumedPoints,0),a(c)})}block(t,r){const n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new RateLimiterRes$5(0,n===0?-1:n,o))}set(t,r,n){const o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new RateLimiterRes$5(0,o===0?-1:o,r))}get(t){const r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}}var RateLimiterMemory_1=RateLimiterMemory$2;const cluster=require$$6,crypto$1=require$$6,RateLimiterAbstract$1=RateLimiterAbstract_1,RateLimiterMemory$1=RateLimiterMemory_1,RateLimiterRes$4=RateLimiterRes_1,channel="rate_limiter_flexible";let masterInstance=null;const masterSendToWorker=function(e,t,r,n){let o;n===null||n===!0||n===!1?o=n:o={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},e.send({channel,keyPrefix:t.keyPrefix,promiseId:t.promiseId,type:r,data:o})},workerWaitInit=function(e){setTimeout(()=>{this._initiated?process.send(e):typeof this._promises[e.promiseId]<"u"&&workerWaitInit.call(this,e)},30)},workerSendToMaster=function(e,t,r,n,o){const a={channel,keyPrefix:this.keyPrefix,func:e,promiseId:t,data:{key:r,arg:n,opts:o}};this._initiated?process.send(a):workerWaitInit.call(this,a)},masterProcessMsg=function(e,t){if(!t||t.channel!==channel||typeof this._rateLimiters[t.keyPrefix]>"u")return!1;let r;switch(t.func){case"consume":r=this._rateLimiters[t.keyPrefix].consume(t.data.key,t.data.arg,t.data.opts);break;case"penalty":r=this._rateLimiters[t.keyPrefix].penalty(t.data.key,t.data.arg,t.data.opts);break;case"reward":r=this._rateLimiters[t.keyPrefix].reward(t.data.key,t.data.arg,t.data.opts);break;case"block":r=this._rateLimiters[t.keyPrefix].block(t.data.key,t.data.arg,t.data.opts);break;case"get":r=this._rateLimiters[t.keyPrefix].get(t.data.key,t.data.opts);break;case"delete":r=this._rateLimiters[t.keyPrefix].delete(t.data.key,t.data.opts);break;default:return!1}r&&r.then(n=>{masterSendToWorker(e,t,"resolve",n)}).catch(n=>{masterSendToWorker(e,t,"reject",n)})},workerProcessMsg=function(e){if(!e||e.channel!==channel||e.keyPrefix!==this.keyPrefix)return!1;if(this._promises[e.promiseId]){clearTimeout(this._promises[e.promiseId].timeoutId);let t;switch(e.data===null||e.data===!0||e.data===!1?t=e.data:t=new RateLimiterRes$4(e.data.remainingPoints,e.data.msBeforeNext,e.data.consumedPoints,e.data.isFirstInDuration),e.type){case"resolve":this._promises[e.promiseId].resolve(t);break;case"reject":this._promises[e.promiseId].reject(t);break;default:throw new Error(`RateLimiterCluster: no such message type '${e.type}'`)}delete this._promises[e.promiseId]}},getOpts=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},savePromise=function(e,t){const r=process.hrtime();let n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=crypto$1.randomBytes(12).toString("base64")),this._promises[n]={resolve:e,reject:t,timeoutId:setTimeout(()=>{delete this._promises[n],t(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n};class RateLimiterClusterMaster$1{constructor(){if(masterInstance)return masterInstance;this._rateLimiters={},cluster.setMaxListeners(0),cluster.on("message",(t,r)=>{r&&r.channel===channel&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new RateLimiterMemory$1(r.opts)),t.send({channel,type:"init",keyPrefix:r.opts.keyPrefix})):masterProcessMsg.call(this,t,r)}),masterInstance=this}}class RateLimiterClusterMasterPM2$1{constructor(t){if(masterInstance)return masterInstance;this._rateLimiters={},t.launchBus((r,n)=>{n.on("process:msg",o=>{const a=o.raw;if(a&&a.channel===channel&&a.type==="init")typeof this._rateLimiters[a.opts.keyPrefix]>"u"&&(this._rateLimiters[a.opts.keyPrefix]=new RateLimiterMemory$1(a.opts)),t.sendDataToProcessId(o.process.pm_id,{data:{},topic:channel,channel,type:"init",keyPrefix:a.opts.keyPrefix},(l,c)=>{l&&console.log(l,c)});else{const l={send:c=>{const u=c;u.topic=channel,typeof u.data>"u"&&(u.data={}),t.sendDataToProcessId(o.process.pm_id,u,(_,b)=>{_&&console.log(_,b)})}};masterProcessMsg.call(this,l,a)}})}),masterInstance=this}}class RateLimiterClusterWorker extends RateLimiterAbstract$1{get timeoutMs(){return this._timeoutMs}set timeoutMs(t){this._timeoutMs=typeof t>"u"?5e3:Math.abs(parseInt(t))}constructor(t={}){super(t),process.setMaxListeners(0),this.timeoutMs=t.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===channel&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:workerProcessMsg.call(this,r)}),process.send({channel,type:"init",opts:getOpts.call(this)}),this._promises={}}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"consume",l,t,r,n)})}penalty(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"penalty",l,t,r,n)})}reward(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"reward",l,t,r,n)})}block(t,r,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"block",l,t,r,n)})}get(t,r={}){return new Promise((n,o)=>{const a=savePromise.call(this,n,o);workerSendToMaster.call(this,"get",a,t,r)})}delete(t,r={}){return new Promise((n,o)=>{const a=savePromise.call(this,n,o);workerSendToMaster.call(this,"delete",a,t,r)})}}var RateLimiterCluster$1={RateLimiterClusterMaster:RateLimiterClusterMaster$1,RateLimiterClusterMasterPM2:RateLimiterClusterMasterPM2$1,RateLimiterCluster:RateLimiterClusterWorker};const RateLimiterStoreAbstract=RateLimiterStoreAbstract_1,RateLimiterRes$3=RateLimiterRes_1;class RateLimiterMemcache$1 extends RateLimiterStoreAbstract{constructor(t){super(t),this.client=t.storeClient}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$3;return o.consumedPoints=parseInt(n.consumedPoints),o.isFirstInDuration=n.consumedPoints===r,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n.msBeforeNext,o}_upsert(t,r,n,o=!1,a={}){return new Promise((l,c)=>{const u=Date.now(),_=Math.floor(n/1e3);o?this.client.set(t,r,_,b=>{b?c(b):this.client.set(`${t}_expire`,_>0?u+_*1e3:-1,_,()=>{const x={consumedPoints:r,msBeforeNext:_>0?_*1e3:-1};l(x)})}):this.client.incr(t,r,(b,x)=>{b||x===!1?this.client.add(t,r,_,(E,I)=>{if(E||!I)if(typeof a.attemptNumber>"u"||a.attemptNumber<3){const k=Object.assign({},a);k.attemptNumber=k.attemptNumber?k.attemptNumber+1:1,this._upsert(t,r,n,o,k).then(T=>l(T)).catch(T=>c(T))}else c(new Error("Can not add key"));else this.client.add(`${t}_expire`,_>0?u+_*1e3:-1,_,()=>{const k={consumedPoints:r,msBeforeNext:_>0?_*1e3:-1};l(k)})}):this.client.get(`${t}_expire`,(E,I)=>{if(E)c(E);else{const k=I===!1?0:I,T={consumedPoints:x,msBeforeNext:k>=0?Math.max(k-u,0):-1};l(T)}})})})}_get(t){return new Promise((r,n)=>{const o=Date.now();this.client.get(t,(a,l)=>{l?this.client.get(`${t}_expire`,(c,u)=>{if(c)n(c);else{const _=u===!1?0:u,b={consumedPoints:l,msBeforeNext:_>=0?Math.max(_-o,0):-1};r(b)}}):r(null)})})}_delete(t){return new Promise((r,n)=>{this.client.del(t,(o,a)=>{o?n(o):a===!1?r(a):this.client.del(`${t}_expire`,l=>{l?n(l):r(a)})})})}}var RateLimiterMemcache_1=RateLimiterMemcache$1;const RateLimiterRes$2=RateLimiterRes_1;var RLWrapperBlackAndWhite_1=class{constructor(t={}){this.limiter=t.limiter,this.blackList=t.blackList,this.whiteList=t.whiteList,this.isBlackListed=t.isBlackListed,this.isWhiteListed=t.isWhiteListed,this.runActionAnyway=t.runActionAnyway}get limiter(){return this._limiter}set limiter(t){if(typeof t>"u")throw new Error("limiter is not set");this._limiter=t}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(t){this._runActionAnyway=typeof t>"u"?!1:t}get blackList(){return this._blackList}set blackList(t){this._blackList=Array.isArray(t)?t:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(t){if(typeof t>"u"&&(t=()=>!1),typeof t!="function")throw new Error("isBlackListed must be function");this._isBlackListed=t}get whiteList(){return this._whiteList}set whiteList(t){this._whiteList=Array.isArray(t)?t:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(t){if(typeof t>"u"&&(t=()=>!1),typeof t!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=t}isBlackListedSomewhere(t){return this.blackList.indexOf(t)>=0||this.isBlackListed(t)}isWhiteListedSomewhere(t){return this.whiteList.indexOf(t)>=0||this.isWhiteListed(t)}getBlackRes(){return new RateLimiterRes$2(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new RateLimiterRes$2(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(t,r=1){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(t,r):(this.runActionAnyway&&this.limiter.consume(t,r).catch(()=>{}),n)}block(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(t,r):(this.runActionAnyway&&this.limiter.block(t,r).catch(()=>{}),n)}penalty(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(t,r):(this.runActionAnyway&&this.limiter.penalty(t,r).catch(()=>{}),n)}reward(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(t,r):(this.runActionAnyway&&this.limiter.reward(t,r).catch(()=>{}),n)}get(t){let r;return this.isWhiteListedSomewhere(t)?r=this.resolveWhite():this.isBlackListedSomewhere(t)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(t):r}delete(t){return this.limiter.delete(t)}};const RateLimiterAbstract=RateLimiterAbstract_1;var RateLimiterUnion_1=class{constructor(...t){if(t.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");t.forEach(r=>{if(!(r instanceof RateLimiterAbstract))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=t}consume(t,r=1){return new Promise((n,o)=>{const a=[];this._limiters.forEach(l=>{a.push(l.consume(t,r).catch(c=>({rejected:!0,rej:c})))}),Promise.all(a).then(l=>{const c={};let u=!1;l.forEach(_=>{_.rejected===!0&&(u=!0)});for(let _=0;_t!==null?t.remainingPoints:this._limiterFlexible.points)}removeTokens(t){const r=this;return new Promise((n,o)=>{if(t>r._limiterFlexible.points){o(new RateLimiterQueueError(`Requested tokens ${t} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,o,t):r._limiterFlexible.consume(r._key,t).then(a=>{n(a.remainingPoints)}).catch(a=>{a instanceof Error?o(a):(r._queueRequest.call(r,n,o,t),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),a.msBeforeNext)))})})}_queueRequest(t,r,n){const o=this;o._queue.length{r.resolve(n.remainingPoints),t._processFIFO.call(t)}).catch(n=>{n instanceof Error?(r.reject(n),t._processFIFO.call(t)):(t._queue.unshift(r),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),n.msBeforeNext)))})}}const RateLimiterRes$1=RateLimiterRes_1;var BurstyRateLimiter_1=class{constructor(t,r){this._rateLimiter=t,this._burstLimiter=r}_combineRes(t,r){return t?new RateLimiterRes$1(t.remainingPoints,Math.min(t.msBeforeNext,r?r.msBeforeNext:0),t.consumedPoints,t.isFirstInDuration):null}consume(t,r=1,n={}){return this._rateLimiter.consume(t,r,n).catch(o=>o instanceof RateLimiterRes$1?this._burstLimiter.consume(t,r,n).then(a=>Promise.resolve(this._combineRes(o,a))).catch(a=>a instanceof RateLimiterRes$1?Promise.reject(this._combineRes(o,a)):Promise.reject(a)):Promise.reject(o))}get(t){return Promise.all([this._rateLimiter.get(t),this._burstLimiter.get(t)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}};const RateLimiterRedis=RateLimiterRedis_1,RateLimiterMongo=RateLimiterMongo_1,RateLimiterMySQL=RateLimiterMySQL_1,RateLimiterPostgres=RateLimiterPostgres_1,{RateLimiterClusterMaster,RateLimiterClusterMasterPM2,RateLimiterCluster}=RateLimiterCluster$1,RateLimiterMemory=RateLimiterMemory_1,RateLimiterMemcache=RateLimiterMemcache_1,RLWrapperBlackAndWhite=RLWrapperBlackAndWhite_1,RateLimiterUnion=RateLimiterUnion_1,RateLimiterQueue=RateLimiterQueue_1,BurstyRateLimiter=BurstyRateLimiter_1,RateLimiterRes=RateLimiterRes_1;var rateLimiterFlexible={RateLimiterRedis,RateLimiterMongo,RateLimiterMySQL,RateLimiterPostgres,RateLimiterMemory,RateLimiterMemcache,RateLimiterClusterMaster,RateLimiterClusterMasterPM2,RateLimiterCluster,RLWrapperBlackAndWhite,RateLimiterUnion,RateLimiterQueue,BurstyRateLimiter,RateLimiterRes},MessageTypes;(function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(MessageTypes||(MessageTypes={}));const MessageTypeNames=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),InitiatorMessageTypes=Object.freeze({NEW_STREAM:MessageTypes.NEW_STREAM,MESSAGE:MessageTypes.MESSAGE_INITIATOR,CLOSE:MessageTypes.CLOSE_INITIATOR,RESET:MessageTypes.RESET_INITIATOR}),ReceiverMessageTypes=Object.freeze({MESSAGE:MessageTypes.MESSAGE_RECEIVER,CLOSE:MessageTypes.CLOSE_RECEIVER,RESET:MessageTypes.RESET_RECEIVER}),MAX_MSG_SIZE=1<<20,MAX_MSG_QUEUE_SIZE=4<<20;class Decoder$1{constructor(t=MAX_MSG_SIZE,r=MAX_MSG_QUEUE_SIZE){Ye(this,"_buffer");Ye(this,"_headerInfo");Ye(this,"_maxMessageSize");Ye(this,"_maxUnprocessedMessageQueueSize");this._buffer=new Uint8ArrayList,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=r}write(t){if(t==null||t.length===0)return[];if(this._buffer.append(t),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const r=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(_){if(_.code==="ERR_MSG_TOO_BIG")throw _;break}const{id:n,type:o,length:a,offset:l}=this._headerInfo;if(this._buffer.length-lthis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:r>>3,type:l,offset:n+a,length:o}}}const MSB$2=128,REST$2=127;function readVarInt(e,t=0){let r=0,n=0,o=t,a;const l=e.length;do{if(o>=l||n>49)throw t=0,new RangeError("Could not decode varint");a=e.get(o++),r+=n<28?(a&REST$2)<=MSB$2);return t=o-t,{value:r,offset:t}}function isAsyncIterable$7(e){return e[Symbol.asyncIterator]!=null}const DEFAULT_BATCH_SIZE=1024*1024,DEFAULT_SERIALIZE=(e,t)=>{t.append(e)};function batchedBytes(e,t){return isAsyncIterable$7(e)?async function*(){let r=new Uint8ArrayList,n=!1,o=pDefer(),a=Number(t?.size??DEFAULT_BATCH_SIZE);if((isNaN(a)||a===0||a<0)&&(a=DEFAULT_BATCH_SIZE),a!==Math.round(a))throw new Error("Batch size must be an integer");const l=t?.yieldAfter??0,c=t?.serialize??DEFAULT_SERIALIZE;for(Promise.resolve().then(async()=>{try{let u;for await(const _ of e){if(c(_,r),r.byteLength>=a){clearTimeout(u),o.resolve();continue}u=setTimeout(()=>{o.resolve()},l)}clearTimeout(u),o.resolve()}catch(u){o.reject(u)}finally{n=!0}});!n;)if(await o.promise,o=pDefer(),r.byteLength>0){const u=r;r=new Uint8ArrayList,yield u.subarray()}}():function*(){const r=new Uint8ArrayList;let n=Number(t?.size??DEFAULT_BATCH_SIZE);if((isNaN(n)||n===0||n<0)&&(n=DEFAULT_BATCH_SIZE),n!==Math.round(n))throw new Error("Batch size must be an integer");const o=t?.serialize??DEFAULT_SERIALIZE;for(const a of e)o(a,r),r.byteLength>=n&&(yield r.subarray(0,n),r.consume(n));r.byteLength>0&&(yield r.subarray())}()}function allocUnsafe(e){return new Uint8Array(e)}const POOL_SIZE=10*1024;class Encoder$1{constructor(){Ye(this,"_pool");Ye(this,"_poolOffset");this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0}write(t,r){const n=this._pool;let o=this._poolOffset;encode$d(t.id<<3|t.type,n,o),o+=encodingLength$2(t.id<<3|t.type),(t.type===MessageTypes.NEW_STREAM||t.type===MessageTypes.MESSAGE_INITIATOR||t.type===MessageTypes.MESSAGE_RECEIVER)&&t.data!=null?(encode$d(t.data.length,n,o),o+=encodingLength$2(t.data.length)):(encode$d(0,n,o),o+=encodingLength$2(0));const a=n.subarray(this._poolOffset,o);POOL_SIZE-o<100?(this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0):this._poolOffset=o,r.append(a),(t.type===MessageTypes.NEW_STREAM||t.type===MessageTypes.MESSAGE_INITIATOR||t.type===MessageTypes.MESSAGE_RECEIVER)&&t.data!=null&&r.append(t.data)}}const encoder=new Encoder$1;async function*encode$7(e,t=0){if(t==null||t===0){for await(const r of e){const n=new Uint8ArrayList;for(const o of r)encoder.write(o,n);yield n.subarray()}return}yield*batchedBytes(e,{size:t,serialize:(r,n)=>{for(const o of r)encoder.write(o,n)}})}const ERR_STREAM_RESET="ERR_STREAM_RESET",ERR_SINK_INVALID_STATE="ERR_SINK_INVALID_STATE";function isPromise(e){return e!=null&&typeof e.then=="function"}class AbstractStream{constructor(t){Ye(this,"id");Ye(this,"direction");Ye(this,"timeline");Ye(this,"protocol");Ye(this,"metadata");Ye(this,"source");Ye(this,"status");Ye(this,"readStatus");Ye(this,"writeStatus");Ye(this,"sinkController");Ye(this,"sinkEnd");Ye(this,"endErr");Ye(this,"streamSource");Ye(this,"onEnd");Ye(this,"onCloseRead");Ye(this,"onCloseWrite");Ye(this,"onReset");Ye(this,"onAbort");Ye(this,"log");this.sinkController=new AbortController,this.sinkEnd=pDefer(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=pushable({onEnd:r=>{r!=null?this.log.trace("source ended with error",r):this.log.trace("source ended"),this.readStatus="closed",this.onSourceEnd(r)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new CodeError(`writable end state is "${this.writeStatus}" not "ready"`,ERR_SINK_INVALID_STATE);try{this.writeStatus="writing";const r={signal:this.sinkController.signal};if(this.direction==="outbound"){const n=this.sendNewStream(r);isPromise(n)&&await n}t=abortableSource(t,this.sinkController.signal,{returnOnAbort:!0}),this.log.trace("sink reading from source");for await(let n of t){n=n instanceof Uint8Array?new Uint8ArrayList(n):n;const o=this.sendData(n,r);isPromise(o)&&await o}this.log.trace("sink finished reading from source"),this.writeStatus="done",this.log.trace("sink calling closeWrite"),await this.closeWrite(r),this.onSinkEnd()}catch(r){throw this.log.trace("sink ended with error, calling abort with error",r),this.abort(r),r}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(t),this.closeWrite(t)]),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const r=this.readStatus;this.readStatus="closing",r==="ready"&&(this.log.trace("ending internal source queue"),this.streamSource.end()),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),this.log.trace("closed readable end of stream")}async closeWrite(t={}){if(this.writeStatus==="closing"||this.writeStatus==="closed")return;this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus);const r=this.writeStatus;this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await this.sink([])),this.writeStatus="closing",r==="writing"&&await new Promise((n,o)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),this.sinkEnd.promise.then(n,o)})}),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeWrite==null&&(this.log.trace("send close write to remote"),await this.sendCloseWrite(t)),this.writeStatus="closed",this.log.trace("closed writable end of stream")}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");const r=this.sendReset();isPromise(r)&&r.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;const t=new CodeError("stream reset",ERR_STREAM_RESET);this.status="reset",this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("muxer destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}}class MplexStream extends AbstractStream{constructor(r){super(r);Ye(this,"name");Ye(this,"streamId");Ye(this,"send");Ye(this,"types");Ye(this,"maxDataSize");this.types=r.direction==="outbound"?InitiatorMessageTypes:ReceiverMessageTypes,this.send=r.send,this.name=r.name,this.streamId=r.streamId,this.maxDataSize=r.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:InitiatorMessageTypes.NEW_STREAM,data:new Uint8ArrayList(fromString$1(this.name))})}async sendData(r){for(r=r.sublist();r.byteLength>0;){const n=Math.min(r.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:r.sublist(0,n)}),r.consume(n)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function createStream$1(e){const{id:t,name:r,send:n,onEnd:o,type:a="initiator",maxMsgSize:l=MAX_MSG_SIZE}=e;return new MplexStream({id:a==="initiator"?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:a==="initiator"?"outbound":"inbound",maxDataSize:l,onEnd:o,send:n,log:logger(`libp2p:mplex:stream:${a}:${t}`)})}const log$w=logger("libp2p:mplex"),MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAM_BUFFER_SIZE=1024*1024*4,DISCONNECT_THRESHOLD=5,CLOSE_TIMEOUT$2=500;function printMessage(e){const t={...e,type:`${MessageTypeNames[e.type]} (${e.type})`};return e.type===MessageTypes.NEW_STREAM&&(t.data=toString$5(e.data instanceof Uint8Array?e.data:e.data.subarray())),(e.type===MessageTypes.MESSAGE_INITIATOR||e.type===MessageTypes.MESSAGE_RECEIVER)&&(t.data=toString$5(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class MplexStreamMuxer{constructor(t){Ye(this,"protocol","/mplex/6.7.0");Ye(this,"sink");Ye(this,"source");Ye(this,"_streamId");Ye(this,"_streams");Ye(this,"_init");Ye(this,"_source");Ye(this,"closeController");Ye(this,"rateLimiter");Ye(this,"closeTimeout");t=t??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??CLOSE_TIMEOUT$2,this.sink=this._createSink(),this._source=pushableV({objectMode:!0,onEnd:()=>{for(const r of this._streams.initiators.values())r.destroy();for(const r of this._streams.receivers.values())r.destroy()}}),this.source=pipe(this._source,r=>encode$7(r,this._init.minSendBytes)),this.closeController=new AbortController,this.rateLimiter=new rateLimiterFlexible.RateLimiterMemory({points:t.disconnectThreshold??DISCONNECT_THRESHOLD,duration:1})}get streams(){const t=[];for(const r of this._streams.initiators.values())t.push(r);for(const r of this._streams.receivers.values())t.push(r);return t}newStream(t){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const r=this._streamId++;t=t==null?r.toString():t.toString();const n=this._streams.initiators;return this._newStream({id:r,name:t,type:"initiator",registry:n})}async close(t){if(this.closeController.signal.aborted)return;const r=t?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:r}))),this._source.end(),await this._source.onEmpty({signal:r}),this.closeController.abort()}catch(n){this.abort(n)}}abort(t){this.closeController.signal.aborted||(this.streams.forEach(r=>{r.abort(t)}),this.closeController.abort(t))}_newReceiverStream(t){const{id:r,name:n}=t,o=this._streams.receivers;return this._newStream({id:r,name:n,type:"receiver",registry:o})}_newStream(t){const{id:r,name:n,type:o,registry:a}=t;if(log$w("new %s stream %s",o,r),o==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION))throw new CodeError("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(a.has(r))throw new Error(`${o} stream ${r} already exists!`);const u=createStream$1({id:r,name:n,send:async _=>{log$w.enabled&&log$w.trace("%s stream %s send",o,r,printMessage(_)),this._source.push(_)},type:o,onEnd:()=>{log$w("%s stream with id %s and protocol %s ended",o,r,u.protocol),a.delete(r),this._init.onStreamEnd!=null&&this._init.onStreamEnd(u)},maxMsgSize:this._init.maxMsgSize});return a.set(r,u),u}_createSink(){return async r=>{try{r=abortableSource(r,this.closeController.signal,{returnOnAbort:!0});const n=new Decoder$1(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const o of r)for(const a of n.write(o))await this._handleIncoming(a);this._source.end()}catch(n){log$w("error in sink",n),this._source.end(n)}}}async _handleIncoming(t){const{id:r,type:n}=t;if(log$w.enabled&&log$w.trace("incoming message",printMessage(t)),t.type===MessageTypes.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)){log$w("too many inbound streams open"),this._source.push({id:r,type:MessageTypes.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{log$w("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}const c=this._newReceiverStream({id:r,name:toString$5(t.data instanceof Uint8Array?t.data:t.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(c);return}const a=((n&1)===1?this._streams.initiators:this._streams.receivers).get(r);if(a==null){log$w("missing stream %s for message type %s",r,MessageTypeNames[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{log$w("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}const l=this._init.maxStreamBufferSize??MAX_STREAM_BUFFER_SIZE;try{switch(n){case MessageTypes.MESSAGE_INITIATOR:case MessageTypes.MESSAGE_RECEIVER:if(a.sourceReadableLength()>l)throw this._source.push({id:t.id,type:n===MessageTypes.MESSAGE_INITIATOR?MessageTypes.RESET_RECEIVER:MessageTypes.RESET_INITIATOR}),new CodeError("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");a.sourcePush(t.data);break;case MessageTypes.CLOSE_INITIATOR:case MessageTypes.CLOSE_RECEIVER:a.remoteCloseWrite();break;case MessageTypes.RESET_INITIATOR:case MessageTypes.RESET_RECEIVER:a.reset();break;default:log$w("unknown message type %s",n)}}catch(c){log$w.error("error while processing message",c),a.abort(c)}}}class Mplex{constructor(t={}){Ye(this,"protocol","/mplex/6.7.0");Ye(this,"_init");this._init=t}createStreamMuxer(t={}){return new MplexStreamMuxer({...t,...this._init})}}function mplex(e={}){return()=>new Mplex(e)}const symbol$1=Symbol.for("@libp2p/transport");var FaultTolerance;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(FaultTolerance||(FaultTolerance={}));var codes$6;(function(e){e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",e.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",e.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(codes$6||(codes$6={}));var __spreadArray=globalThis&&globalThis.__spreadArray||function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,a;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new ReactNativeInfo:typeof navigator<"u"?parseUserAgent(navigator.userAgent):getNodeVersion()}function matchUserAgent(e){return e!==""&&userAgentRules.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var a=o.exec(e);return!!a&&[n,a]},!1)}function parseUserAgent(e){var t=matchUserAgent(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new BotInfo;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length{},log$v=logger("libp2p:webrtc:connection");class WebRTCMultiaddrConnection{constructor(t){Ye(this,"peerConnection");Ye(this,"remoteAddr");Ye(this,"timeline");Ye(this,"metrics");Ye(this,"source",nopSource());Ye(this,"sink",nopSink);this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection,this.peerConnection.onconnectionstatechange=()=>{(this.peerConnection.connectionState==="closed"||this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed")&&(this.timeline.close=Date.now())}}async close(t){log$v.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){log$v.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}}const RTCPeerConnection=globalThis.RTCPeerConnection,RTCSessionDescription=globalThis.RTCSessionDescription,RTCIceCandidate=globalThis.RTCIceCandidate;function pbStream(e,t){const r=lpStream(e,t),n={read:async(o,a)=>{const l=await r.read(a);return o.decode(l)},write:async(o,a,l)=>{await r.write(a.encode(o),l)},pb:o=>({read:async a=>n.read(o,a),write:async(a,l)=>n.write(a,o,l),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}class TimeoutError extends Error{constructor(t){super(t),this.name="TimeoutError"}}class AbortError extends Error{constructor(t){super(),this.name="AbortError",this.message=t}}const getDOMException=e=>globalThis.DOMException===void 0?new AbortError(e):new DOMException(e),getAbortedReason=e=>{const t=e.reason===void 0?getDOMException("This operation was aborted."):e.reason;return t instanceof Error?t:getDOMException(t)};function pTimeout(e,t){const{milliseconds:r,fallback:n,message:o,customTimers:a={setTimeout,clearTimeout}}=t;let l;const u=new Promise((_,b)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:E}=t;E.aborted&&b(getAbortedReason(E)),E.addEventListener("abort",()=>{b(getAbortedReason(E))})}if(r===Number.POSITIVE_INFINITY){e.then(_,b);return}const x=new TimeoutError;l=a.setTimeout.call(void 0,()=>{if(n){try{_(n())}catch(E){b(E)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?_():o instanceof Error?b(o):(x.message=o??`Promise timed out after ${r} milliseconds`,b(x))},r),(async()=>{try{_(await e)}catch(E){b(E)}})()}).finally(()=>{u.clear()});return u.clear=()=>{a.clearTimeout.call(void 0,l),l=void 0},u}const normalizeEmitter=e=>{const t=e.on||e.addListener||e.addEventListener,r=e.off||e.removeListener||e.removeEventListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function pEventMultiple(e,t,r){let n;const o=new Promise((a,l)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const c=[t].flat(),u=[],{addListener:_,removeListener:b}=normalizeEmitter(e),x=(...I)=>{const k=r.multiArgs?I:I[0];r.filter&&!r.filter(k)||(u.push(k),r.count===u.length&&(n(),a(u)))},E=I=>{n(),l(I)};n=()=>{for(const I of c)b(I,x);for(const I of r.rejectionEvents)b(I,E)};for(const I of c)_(I,x);for(const I of r.rejectionEvents)_(I,E);r.signal&&r.signal.addEventListener("abort",()=>{E(r.signal.reason)},{once:!0}),r.resolveImmediately&&a(u)});if(o.cancel=n,typeof r.timeout=="number"){const a=pTimeout(o,{milliseconds:r.timeout});return a.cancel=n,a}return o}function pEvent(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=pEventMultiple(e,t,r),o=n.then(a=>a[0]);return o.cancel=n.cancel,o}var Message$1;(function(e){(function(n){n.FIN="FIN",n.STOP_SENDING="STOP_SENDING",n.RESET="RESET"})(e.Flag||(e.Flag={}));let t;(function(n){n[n.FIN=0]="FIN",n[n.STOP_SENDING=1]="STOP_SENDING",n[n.RESET=2]="RESET"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Flag||(e.Flag={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.flag!=null&&(o.uint32(8),e.Flag.codec().encode(n.flag,o)),n.message!=null&&(o.uint32(18),o.bytes(n.message)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.flag=e.Flag.codec().decode(n);break;case 2:a.message=n.bytes();break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(Message$1||(Message$1={}));const MAX_MESSAGE_SIZE=16*1024,MAX_BUFFERED_AMOUNT=16*1024*1024,BUFFERED_AMOUNT_LOW_TIMEOUT=30*1e3,PROTOBUF_OVERHEAD=5,VARINT_LENGTH=2;class WebRTCStream extends AbstractStream{constructor(r){super(r);Ye(this,"channel");Ye(this,"dataChannelOptions");Ye(this,"incomingData");Ye(this,"messageQueue");Ye(this,"maxDataSize");switch(this.channel=r.channel,this.channel.binaryType="arraybuffer",this.incomingData=pushable(),this.messageQueue=new Uint8ArrayList,this.dataChannelOptions={bufferedAmountLowEventTimeout:r.dataChannelOptions?.bufferedAmountLowEventTimeout??BUFFERED_AMOUNT_LOW_TIMEOUT,maxBufferedAmount:r.dataChannelOptions?.maxBufferedAmount??MAX_BUFFERED_AMOUNT,maxMessageSize:r.dataChannelOptions?.maxMessageSize??r.maxDataSize},this.maxDataSize=r.maxDataSize,this.channel.readyState){case"open":break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new CodeError("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime(),this.messageQueue!=null&&(this._sendMessage(this.messageQueue).catch(a=>{this.abort(a)}),this.messageQueue=void 0)},this.channel.onclose=o=>{this.close().catch(a=>{this.log.error("error closing stream after channel closed",a)})},this.channel.onerror=o=>{const a=o.error;this.abort(a)};const n=this;this.channel.onmessage=async o=>{const{data:a}=o;a===null||a.byteLength===0||this.incomingData.push(new Uint8Array(a,0,a.byteLength))},Promise.resolve().then(async()=>{for await(const o of decode$a(this.incomingData)){const a=n.processIncomingProtobuf(o.subarray());a!=null&&n.sourcePush(new Uint8ArrayList(a))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(r,n=!0){if(n&&this.channel.bufferedAmount>this.dataChannelOptions.maxBufferedAmount)try{await pEvent(this.channel,"bufferedamountlow",{timeout:this.dataChannelOptions.bufferedAmountLowEventTimeout})}catch(o){throw o instanceof TimeoutError?new Error("Timed out waiting for DataChannel buffer to clear"):o}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new CodeError("Invalid datachannel state - closed or closing","ERR_INVALID_STATE");if(this.channel.readyState==="open")for(const o of r)this.channel.send(o);else if(this.channel.readyState==="connecting")this.messageQueue==null&&(this.messageQueue=new Uint8ArrayList),this.messageQueue.append(r);else throw this.log.error("unknown datachannel state %s",this.channel.readyState),new CodeError("Unknown datachannel state","ERR_INVALID_STATE")}async sendData(r){for(r=r.sublist();r.byteLength>0;){const n=Math.min(r.byteLength,this.maxDataSize),o=r.subarray(0,n),a=Message$1.encode({message:o}),l=encode$c.single(a);await this._sendMessage(l),r.consume(n)}}async sendReset(){await this._sendFlag(Message$1.Flag.RESET)}async sendCloseWrite(){await this._sendFlag(Message$1.Flag.FIN)}async sendCloseRead(){await this._sendFlag(Message$1.Flag.STOP_SENDING)}processIncomingProtobuf(r){const n=Message$1.decode(r);return n.flag!==void 0&&(n.flag===Message$1.Flag.FIN&&(this.incomingData.end(),this.remoteCloseWrite()),n.flag===Message$1.Flag.RESET&&this.reset(),n.flag===Message$1.Flag.STOP_SENDING&&this.remoteCloseRead()),n.message}async _sendFlag(r){this.log.trace("Sending flag: %s",r.toString());const n=Message$1.encode({flag:r}),o=encode$c.single(n);await this._sendMessage(o,!1)}}function createStream(e){const{channel:t,direction:r,onEnd:n,dataChannelOptions:o}=e;return new WebRTCStream({id:r==="inbound"?`i${t.id}`:`r${t.id}`,direction:r,maxDataSize:(o?.maxMessageSize??MAX_MESSAGE_SIZE)-PROTOBUF_OVERHEAD-VARINT_LENGTH,dataChannelOptions:o,onEnd:n,channel:t,log:logger(`libp2p:webrtc:stream:${r}:${t.id}`)})}const PROTOCOL="/webrtc";class DataChannelMuxerFactory{constructor(t){Ye(this,"protocol");Ye(this,"peerConnection");Ye(this,"streamBuffer",[]);Ye(this,"metrics");Ye(this,"dataChannelOptions");this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??PROTOCOL,this.dataChannelOptions=t.dataChannelOptions,this.peerConnection.ondatachannel=({channel:r})=>{const n=createStream({channel:r,direction:"inbound",dataChannelOptions:t.dataChannelOptions,onEnd:()=>{this.streamBuffer=this.streamBuffer.filter(o=>o.id!==n.id)}});this.streamBuffer.push(n)}}createStreamMuxer(t){return new DataChannelMuxer({...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.streamBuffer,protocol:this.protocol})}}class DataChannelMuxer{constructor(t){Ye(this,"init");Ye(this,"streams");Ye(this,"protocol");Ye(this,"peerConnection");Ye(this,"dataChannelOptions");Ye(this,"metrics");Ye(this,"close",async()=>{});Ye(this,"abort",()=>{});Ye(this,"source",nopSource());Ye(this,"sink",nopSink);this.init=t,this.streams=t.streams,this.peerConnection=t.peerConnection,this.protocol=t.protocol??PROTOCOL,this.metrics=t.metrics,this.peerConnection.ondatachannel=({channel:n})=>{const o=createStream({channel:n,direction:"inbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(a=>a.id!==o.id),this.metrics?.increment({stream_end:!0}),t?.onStreamEnd?.(o)}});this.streams.push(o),t?.onIncomingStream!=null&&(this.metrics?.increment({incoming_stream:!0}),t.onIncomingStream(o))};const r=t?.onIncomingStream;r!=null&&this.streams.forEach(n=>{r(n)})}newStream(){const t=this.peerConnection.createDataChannel(""),r=createStream({channel:t,direction:"outbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{t.close(),this.streams=this.streams.filter(n=>n.id!==r.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(r)}});return this.streams.push(r),this.metrics?.increment({outgoing_stream:!0}),r}}var Message;(function(e){(function(n){n.SDP_OFFER="SDP_OFFER",n.SDP_ANSWER="SDP_ANSWER",n.ICE_CANDIDATE="ICE_CANDIDATE"})(e.Type||(e.Type={}));let t;(function(n){n[n.SDP_OFFER=0]="SDP_OFFER",n[n.SDP_ANSWER=1]="SDP_ANSWER",n[n.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.data!=null&&(o.uint32(18),o.string(n.data)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.data=n.string();break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(Message||(Message={}));const log$u=logger("libp2p:webrtc:peer:util"),readCandidatesUntilConnected=async(e,t,r)=>{for(;;){const n=await Promise.race([e.promise,r.read()]);if(n instanceof Object){const o=n;if(o.type!==Message.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(o.data==null||o.data===""){log$u.trace("end-of-candidates received");break}log$u.trace("received new ICE candidate: %s",o.data);try{await t.addIceCandidate(new RTCIceCandidate(JSON.parse(o.data)))}catch(a){throw log$u.error("bad candidate received: ",a),new Error("bad candidate received")}}else break}await e.promise};function resolveOnConnected(e,t){e[isFirefox?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(log$u.trace("receiver peerConnectionState state: ",e.connectionState),isFirefox?e.iceConnectionState:e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Error("RTCPeerConnection was closed"));break}}}const DEFAULT_TIMEOUT=30*1e3,log$t=logger("libp2p:webrtc:peer");async function handleIncomingStream({rtcConfiguration:e,dataChannelOptions:t,stream:r}){const n=AbortSignal.timeout(DEFAULT_TIMEOUT),o=pbStream(abortableDuplex(r,n)).pb(Message),a=new RTCPeerConnection(e);try{const l=new DataChannelMuxerFactory({peerConnection:a,dataChannelOptions:t}),c=pDefer(),u=pDefer();n.onabort=()=>{c.reject(new CodeError("Timed out while trying to connect","ERR_TIMEOUT"))},a.onicecandidate=({candidate:I})=>{u.promise.then(async()=>{await o.write({type:Message.Type.ICE_CANDIDATE,data:I!=null?JSON.stringify(I.toJSON()):""})},k=>{log$t.error("cannot set candidate since sending answer failed",k),c.reject(k)})},resolveOnConnected(a,c);const _=await o.read();if(_.type!==Message.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${_.type??"undefined"} `);const b=new RTCSessionDescription({type:"offer",sdp:_.data});await a.setRemoteDescription(b).catch(I=>{throw log$t.error("could not execute setRemoteDescription",I),new Error("Failed to set remoteDescription")});const x=await a.createAnswer().catch(I=>{throw log$t.error("could not execute createAnswer",I),u.reject(I),new Error("Failed to create answer")});await o.write({type:Message.Type.SDP_ANSWER,data:x.sdp}),await a.setLocalDescription(x).catch(I=>{throw log$t.error("could not execute setLocalDescription",I),u.reject(I),new Error("Failed to set localDescription")}),u.resolve(),await readCandidatesUntilConnected(c,a,o);const E=parseRemoteAddress(a.currentRemoteDescription?.sdp??"");return{pc:a,muxerFactory:l,remoteAddress:E}}catch(l){throw a.close(),l}}async function initiateConnection({rtcConfiguration:e,dataChannelOptions:t,signal:r,stream:n}){const o=pbStream(abortableDuplex(n,r)).pb(Message),a=new RTCPeerConnection(e);try{const l=new DataChannelMuxerFactory({peerConnection:a,dataChannelOptions:t}),c=pDefer();resolveOnConnected(a,c),r.onabort=c.reject;const u=a.createDataChannel("init");a.onicecandidate=({candidate:I})=>{o.write({type:Message.Type.ICE_CANDIDATE,data:I!=null?JSON.stringify(I.toJSON()):""}).catch(k=>{log$t.error("error sending ICE candidate",k)})};const _=await a.createOffer();await o.write({type:Message.Type.SDP_OFFER,data:_.sdp}),await a.setLocalDescription(_).catch(I=>{throw log$t.error("could not execute setLocalDescription",I),new Error("Failed to set localDescription")});const b=await o.read();if(b.type!==Message.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");const x=new RTCSessionDescription({type:"answer",sdp:b.data});await a.setRemoteDescription(x).catch(I=>{throw log$t.error("could not execute setRemoteDescription",I),new Error("Failed to set remoteDescription")}),await readCandidatesUntilConnected(c,a,o),u.close();const E=parseRemoteAddress(a.currentRemoteDescription?.sdp??"");return{pc:a,muxerFactory:l,remoteAddress:E}}catch(l){throw a.close(),l}}function parseRemoteAddress(e){const t=e.split(`\r -`).filter(n=>n.startsWith("a=candidate")).pop(),r=t?.split(" ");return t==null||r==null||r.length<5?(log$t("could not parse remote address from",t),"/webrtc"):`/dnsaddr/${r[4]}/${r[2].toLowerCase()}/${r[5]}/webrtc`}class WebRTCPeerListener extends EventEmitter$2{constructor(r){super();Ye(this,"peerId");Ye(this,"transportManager");this.peerId=r.peerId,this.transportManager=r.transportManager}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(r=>r!==this).map(r=>r.getAddrs().filter(n=>Circuit$1.matches(n)).map(n=>n.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.safeDispatchEvent("close",{})}}const log$s=logger("libp2p:webrtc:peer"),WEBRTC_TRANSPORT="/webrtc",CIRCUIT_RELAY_TRANSPORT="/p2p-circuit",SIGNALING_PROTO_ID="/webrtc-signaling/0.0.1",WEBRTC_CODE=getProtocol("webrtc").code;var tc,rc;class WebRTCTransport{constructor(t,r={}){Ye(this,"components");Ye(this,"init");Ye(this,"_started",!1);Ye(this,"metrics");Ye(this,tc,"@libp2p/webrtc");Ye(this,rc,!0);this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}isStarted(){return this._started}async start(){await this.components.registrar.handle(SIGNALING_PROTO_ID,t=>{this._onProtocol(t).catch(r=>{log$s.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(SIGNALING_PROTO_ID),this._started=!1}createListener(t){return new WebRTCPeerListener(this.components)}filter(t){return t.filter(r=>r.protoCodes().includes(WEBRTC_CODE))}async dial(t,r){log$s.trace("dialing address: ",t);const{baseAddr:n,peerId:o}=splitAddr(t);if(r.signal==null){const c=new AbortController;r.signal=c.signal}this.metrics?.dialerEvents.increment({open:!0});const a=await this.components.transportManager.dial(n,r),l=await a.newStream(SIGNALING_PROTO_ID,{...r,runOnTransientConnection:!0});try{const{pc:c,muxerFactory:u,remoteAddress:_}=await initiateConnection({stream:l,rtcConfiguration:this.init.rtcConfiguration,dataChannelOptions:this.init.dataChannel,signal:r.signal}),b=await r.upgrader.upgradeOutbound(new WebRTCMultiaddrConnection({peerConnection:c,timeline:{open:Date.now()},remoteAddr:multiaddr(_).encapsulate(`/p2p/${o.toString()}`),metrics:this.metrics?.dialerEvents}),{skipProtection:!0,skipEncryption:!0,muxerFactory:u});return await l.close(),b}catch(c){throw this.metrics?.dialerEvents.increment({error:!0}),l.abort(c),c}finally{await a.close()}}async _onProtocol({connection:t,stream:r}){try{const{pc:n,muxerFactory:o,remoteAddress:a}=await handleIncomingStream({rtcConfiguration:this.init.rtcConfiguration,connection:t,stream:r,dataChannelOptions:this.init.dataChannel});await this.components.upgrader.upgradeInbound(new WebRTCMultiaddrConnection({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:multiaddr(a).encapsulate(`/p2p/${t.remotePeer.toString()}`),metrics:this.metrics?.listenerEvents}),{skipEncryption:!0,skipProtection:!0,muxerFactory:o})}catch(n){throw r.abort(n),n}finally{await t.close()}}}tc=Symbol.toStringTag,rc=symbol$1;function splitAddr(e){const t=e.toString().split(WEBRTC_TRANSPORT+"/");if(t.length!==2)throw new CodeError("webrtc protocol was not present in multiaddr",codes$6.ERR_INVALID_MULTIADDR);if(!t[0].includes(CIRCUIT_RELAY_TRANSPORT))throw new CodeError("p2p-circuit protocol was not present in multiaddr",codes$6.ERR_INVALID_MULTIADDR);let r=multiaddr(t[0]);const o=multiaddr("/"+t[1]).getPeerId();if(o==null)throw new CodeError("destination peer id was missing",codes$6.ERR_INVALID_MULTIADDR);const a=r.protos().pop();if(a===void 0)throw new CodeError("invalid multiaddr",codes$6.ERR_INVALID_MULTIADDR);return a.name!=="p2p"&&(r=r.encapsulate(`/p2p/${o}`)),{baseAddr:r,peerId:peerIdFromString(o)}}var src$2={exports:{}};function base$2(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,N=new Uint8Array(D);O!==$;){for(var H=I[O],ie=0,ue=D-1;(H!==0||ie>>0,N[ue]=H%l>>>0,H=H/l>>>0;if(H!==0)throw new Error("Non-zero carry");T=ie,O++}for(var de=D-T;de!==D&&N[de]===0;)de++;for(var le=c.repeat(k);de>>0,D=new Uint8Array($);I[k];){var N=t[I.charCodeAt(k)];if(N===255)return;for(var H=0,ie=$-1;(N!==0||H>>0,D[ie]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");O=H,k++}if(I[k]!==" "){for(var ue=$-O;ue!==$&&D[ue]===0;)ue++;for(var de=new Uint8Array(T+($-ue)),le=T;ue!==$;)de[le++]=D[ue++];return de}}}function E(I){var k=x(I);if(k)return k;throw new Error("Non-base"+l+" character")}return{encode:b,decodeUnsafe:x,decode:E}}var src$1=base$2;const textDecoder=new TextDecoder,decodeText$1=e=>textDecoder.decode(e),textEncoder=new TextEncoder,encodeText$2=e=>textEncoder.encode(e);function concat(e,t){const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}var util={decodeText:decodeText$1,encodeText:encodeText$2,concat};const{encodeText:encodeText$1}=util;class Base$1{constructor(t,r,n,o){this.name=t,this.code=r,this.codeBuf=encodeText$1(this.code),this.alphabet=o,this.codec=n(o)}encode(t){return this.codec.encode(t)}decode(t){for(const r of t)if(this.alphabet&&this.alphabet.indexOf(r)<0)throw new Error(`invalid character '${r}' in '${t}'`);return this.codec.decode(t)}}var base$1=Base$1;const decode$4=(e,t,r)=>{const n={};for(let _=0;_=8&&(l-=8,a[u++]=255&c>>l)}if(l>=r||255&c<<8-l)throw new SyntaxError("Unexpected end of data");return a},encode$6=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<t=>({encode(r){return encode$6(r,t,e)},decode(r){return decode$4(r,t,e)}});var rfc4648_1={rfc4648:rfc4648$2};const baseX$1=src$1,Base=base$1,{rfc4648:rfc4648$1}=rfc4648_1,{decodeText,encodeText}=util,identity$3=()=>({encode:decodeText,decode:encodeText}),constants$1=[["identity","\0",identity$3,""],["base2","0",rfc4648$1(1),"01"],["base8","7",rfc4648$1(3),"01234567"],["base10","9",baseX$1,"0123456789"],["base16","f",rfc4648$1(4),"0123456789abcdef"],["base16upper","F",rfc4648$1(4),"0123456789ABCDEF"],["base32hex","v",rfc4648$1(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",rfc4648$1(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",rfc4648$1(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",rfc4648$1(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",rfc4648$1(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",rfc4648$1(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",rfc4648$1(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",rfc4648$1(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",rfc4648$1(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",baseX$1,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",baseX$1,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",baseX$1,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",baseX$1,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],names$2=constants$1.reduce((e,t)=>(e[t[0]]=new Base(t[0],t[1],t[2],t[3]),e),{}),codes$5=constants$1.reduce((e,t)=>(e[t[1]]=names$2[t[0]],e),{});var constants_1={names:names$2,codes:codes$5};(function(e,t){const r=constants_1,{encodeText:n,decodeText:o,concat:a}=util;function l(T,O){if(!O)throw new Error("requires an encoded Uint8Array");const{name:$,codeBuf:D}=x(T);return b($,O),a([D,O],D.length+O.length)}function c(T,O){const $=x(T),D=n($.encode(O));return a([$.codeBuf,D],$.codeBuf.length+D.length)}function u(T){T instanceof Uint8Array&&(T=o(T));const O=T[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(O)&&(T=T.toLowerCase()),x(T[0]).decode(T.substring(1))}function _(T){if(T instanceof Uint8Array&&(T=o(T)),Object.prototype.toString.call(T)!=="[object String]")return!1;try{return x(T[0]).name}catch{return!1}}function b(T,O){x(T).decode(o(O))}function x(T){if(Object.prototype.hasOwnProperty.call(r.names,T))return r.names[T];if(Object.prototype.hasOwnProperty.call(r.codes,T))return r.codes[T];throw new Error(`Unsupported encoding: ${T}`)}function E(T){return T instanceof Uint8Array&&(T=o(T)),x(T[0])}t=e.exports=l,t.encode=c,t.decode=u,t.isEncoded=_,t.encoding=x,t.encodingFromData=E;const I=Object.freeze(r.names),k=Object.freeze(r.codes);t.names=I,t.codes=k})(src$2,src$2.exports);const names$1=Object.freeze({identity:0,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,"murmur3-128":34,"murmur3-32":35,"dbl-sha2-256":86,md4:212,md5:213,bmt:214,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082});var constants={names:names$1};function base(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,H=new Uint8Array(N);$!==D;){for(var ie=k[$],ue=0,de=N-1;(ie!==0||ue>>0,H[de]=ie%c>>>0,ie=ie/c>>>0;if(ie!==0)throw new Error("Non-zero carry");O=ue,$++}for(var le=N-O;le!==N&&H[le]===0;)le++;for(var ce=u.repeat(T);le>>0,N=new Uint8Array(D);k[T];){var H=r[k.charCodeAt(T)];if(H===255)return;for(var ie=0,ue=D-1;(H!==0||ie<$)&&ue!==-1;ue--,ie++)H+=c*N[ue]>>>0,N[ue]=H%256>>>0,H=H/256>>>0;if(H!==0)throw new Error("Non-zero carry");$=ie,T++}if(k[T]!==" "){for(var de=D-$;de!==D&&N[de]===0;)de++;for(var le=new Uint8Array(O+(D-de)),ce=O;de!==D;)le[ce++]=N[de++];return le}}}function I(k){var T=E(k);if(T)return T;throw new Error(`Non-${t} character`)}return{encode:x,decodeUnsafe:E,decode:I}}var src=base,_brrp__multiformats_scope_baseX=src;const coerce$1=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},fromString=e=>new TextEncoder().encode(e),toString$3=e=>new TextDecoder().decode(e);class Encoder{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return or$1(this,t)}}class ComposedDecoder{constructor(t){this.decoders=t}or(t){return or$1(this,t)}decode(t){const r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$1=(e,t)=>new ComposedDecoder({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Codec{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Encoder(t,r,n),this.decoder=new Decoder(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const from$1=({name:e,prefix:t,encode:r,decode:n})=>new Codec(e,t,r,n),baseX=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=_brrp__multiformats_scope_baseX(r,t);return from$1({prefix:e,name:t,encode:n,decode:a=>coerce$1(o(a))})},decode$3=(e,t,r,n)=>{const o={};for(let b=0;b=8&&(c-=8,l[_++]=255&u>>c)}if(c>=r||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return l},encode$5=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<from$1({prefix:t,name:e,encode(o){return encode$5(o,n,r)},decode(o){return decode$3(o,n,r,e)}}),identity$2=from$1({prefix:"\0",name:"identity",encode:e=>toString$3(e),decode:e=>fromString(e)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$2},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32upper,base32pad,base32padupper,base32hex,base32hexupper,base32hexpad,base32hexpadupper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$1=Object.freeze(Object.defineProperty({__proto__:null,base64,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),alphabet$1=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),alphabetBytesToChars=alphabet$1.reduce((e,t,r)=>(e[r]=t,e),[]),alphabetCharsToBytes=alphabet$1.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function encode$4(e){return e.reduce((t,r)=>(t+=alphabetBytesToChars[r],t),"")}function decode$2(e){const t=[];for(const r of e){const n=alphabetCharsToBytes[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}const base256emoji=from$1({prefix:"\u{1F680}",name:"base256emoji",encode:encode$4,decode:decode$2}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"}));var encode_1=encode$3,MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31);function encode$3(e,t,r){t=t||[],r=r||0;for(var n=r;e>=INT;)t[r++]=e&255|MSB,e/=128;for(;e&MSBALL;)t[r++]=e&255|MSB,e>>>=7;return t[r]=e|0,encode$3.bytes=r-n+1,t}var decode$1=read$1,MSB$1=128,REST$1=127;function read$1(e,n){var r=0,n=n||0,o=0,a=n,l,c=e.length;do{if(a>=c)throw read$1.bytes=0,new RangeError("Could not decode varint");l=e[a++],r+=o<28?(l&REST$1)<=MSB$1);return read$1.bytes=a-n,r}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length$1=function(e){return e(_brrp_varint.encode(e,t,r),t),encodingLength=e=>_brrp_varint.encodingLength(e),create=(e,t)=>{const r=t.byteLength,n=encodingLength(e),o=n+encodingLength(r),a=new Uint8Array(o+r);return encodeTo(e,a,0),encodeTo(r,a,n),a.set(t,o),new Digest(e,r,t,a)};class Digest{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}const from=({name:e,code:t,encode:r})=>new Hasher(e,t,r);class Hasher{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?create(this.code,r):r.then(n=>create(this.code,n))}else throw Error("Unknown type, must be binary type")}}const sha=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),sha256=from({name:"sha2-256",code:18,encode:sha("SHA-256")}),sha512=from({name:"sha2-512",code:19,encode:sha("SHA-512")}),sha2=Object.freeze(Object.defineProperty({__proto__:null,sha256,sha512},Symbol.toStringTag,{value:"Module"})),code$2=0,name="identity",encode$2=coerce$1,digest=e=>create(code$2,encode$2(e)),identity={code:code$2,name,encode:encode$2,digest},identity$1=Object.freeze(Object.defineProperty({__proto__:null,identity},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;({...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$1,...base256emoji$1});({...sha2,...identity$1});const{names}=constants,codes$4={};for(const e in names){const t=e;codes$4[names[t]]=t}Object.freeze(codes$4);logger("libp2p:webrtc:sdp");Object.values(bases).map(e=>e.decoder).reduce((e,t)=>e.or(t));Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");logger("libp2p:webrtc:transport");getProtocol("webrtc-direct").code;getProtocol("certhash").code;function webRTC(e){return t=>new WebRTCTransport(t,e)}function extractSNI(e){let t;try{t=getProtocol("sni").code}catch{return null}for(const[r,n]of e)if(r===t&&n!==void 0)return n;return null}function hasTLS(e){return e.some(([t,r])=>t===getProtocol("tls").code)}function interpretNext(e,t,r){const n=interpreters[getProtocol(e).name];if(n===void 0)throw new Error(`Can't interpret protocol ${getProtocol(e).name}`);const o=n(t,r);return e===getProtocol("ip6").code?`[${o}]`:o}const interpreters={ip4:(e,t)=>e,ip6:(e,t)=>t.length===0?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${interpretNext(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${interpretNext(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=hasTLS(t),n=extractSNI(t);if(r&&n!==null)return`https://${n}`;const o=r?"https://":"http://",a=t.pop();if(a===void 0)throw new Error("Unexpected end of multiaddr");let l=interpretNext(a[0],a[1]??"",t);return l=l.replace("tcp://",""),`${o}${l}`},tls:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");let n=interpretNext(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=hasTLS(t),n=extractSNI(t);if(r&&n!==null)return`wss://${n}`;const o=r?"wss://":"ws://",a=t.pop();if(a===void 0)throw new Error("Unexpected end of multiaddr");let l=interpretNext(a[0],a[1]??"",t);return l=l.replace("tcp://",""),`${o}${l}`},wss:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");let n=interpretNext(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-webrtc-direct`}};function multiaddrToUri(e,t){const n=multiaddr(e).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");const a=getProtocol(o[0]),l=interpreters[a.name];if(l==null)throw new Error(`No interpreter found for ${a.name}`);let c=l(o[1]??"",n);return t?.assumeHttp!==!1&&o[0]===getProtocol("tcp").code&&(c=c.replace("tcp://","http://"),(o[1]==="443"||o[1]==="80")&&(o[1]==="443"&&(c=c.replace("http://","https://")),c=c.substring(0,c.lastIndexOf(":")))),c}const ready=async e=>{if(e.readyState>=2)throw new Error("socket closed");e.readyState!==1&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",o),e.removeEventListener("error",a)}function o(){n(),t()}function a(l){n(),r(l.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",o),e.addEventListener("error",a)})},sink=(e,t)=>(t=t??{},t.closeOnEnd=t.closeOnEnd!==!1,async n=>{for await(const o of n){try{await ready(e)}catch(a){if(a.message==="socket closed")break;throw a}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(o)}t.closeOnEnd!=null&&e.readyState<=1&&await new Promise((o,a)=>{e.addEventListener("close",l=>{if(l.wasClean||l.code===1006)o();else{const c=Object.assign(new Error("ws error"),{event:l});a(c)}}),setTimeout(()=>{e.close()})})});var dom$1={},eventIterator={};Object.defineProperty(eventIterator,"__esModule",{value:!0});class EventQueue{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(t){if(this.isStopped)return;const r={value:t,done:!1};if(this.pullQueue.length){const n=this.pullQueue.shift();n&&n.resolve(r)}else this.pushQueue.push(Promise.resolve(r)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const t of this.pullQueue)t.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(t){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const r of this.pullQueue)r.reject(t);this.pullQueue.length=0}else{const r=Promise.reject(t);r.catch(()=>{}),this.pushQueue.push(r)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:t=>{const r=this.pushQueue.shift();return r?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),r):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,o)=>{this.pullQueue.push({resolve:n,reject:o})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class EventIterator$1{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const o=new EventQueue;o.highWaterMark=r,o.lowWaterMark=n,o.removeCallback=t({push:a=>o.push(a),stop:()=>o.stop(),fail:a=>o.fail(a),on:(a,l)=>{o.eventHandlers[a]=l}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}}eventIterator.EventIterator=EventIterator$1;eventIterator.default=EventIterator$1;Object.defineProperty(dom$1,"__esModule",{value:!0});const event_iterator_1=eventIterator;var EventIterator=dom$1.EventIterator=event_iterator_1.EventIterator;function subscribe(e,t,r){return new event_iterator_1.EventIterator(({push:n})=>(this.addEventListener(e,n,t),()=>this.removeEventListener(e,n,t)),r)}dom$1.subscribe=subscribe;dom$1.default=event_iterator_1.EventIterator;function isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&typeof e?.byteLength=="number"}const source=e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise((a,l)=>{if(n){a();return}if(o!=null){l(o);return}const c=b=>{e.removeEventListener("open",u),e.removeEventListener("error",_),b()},u=()=>{c(a)},_=b=>{c(()=>{l(b.error??new Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",u),e.addEventListener("error",_)})},r=async function*(){const a=new EventIterator(({push:l,stop:c,fail:u})=>{const _=x=>{let E=null;typeof x.data=="string"&&(E=fromString$1(x.data)),isArrayBuffer(x.data)&&(E=new Uint8Array(x.data)),x.data instanceof Uint8Array&&(E=x.data),E!=null&&l(E)},b=x=>{u(x.error??new Error("Socket error"))};return e.addEventListener("message",_),e.addEventListener("error",b),e.addEventListener("close",c),()=>{e.removeEventListener("message",_),e.removeEventListener("error",b),e.removeEventListener("close",c)}},{highWaterMark:1/0});await t();for await(const l of a)yield isArrayBuffer(l)?new Uint8Array(l):l}();let n=e.readyState===1,o;return e.addEventListener("open",()=>{n=!0,o=null}),e.addEventListener("close",()=>{n=!1,o=null}),e.addEventListener("error",a=>{n||(o=a.error??new Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(r,{connected:t})},duplex=(e,t)=>{t=t??{};const r=source(e);let n=t.remoteAddress,o=t.remotePort;if(e.url!=null)try{const l=new URL(e.url);n=l.hostname,o=parseInt(l.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:sink(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(l=>{e.addEventListener("close",()=>{l()}),e.close()})},destroy:()=>{e.terminate!=null?e.terminate():e.close()},remoteAddress:n,remotePort:o,socket:e}},WebSocket$1=WebSocket,isReactNative$1=typeof navigator<"u"&&navigator.product==="ReactNative";function getDefaultBase(){return isReactNative$1?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}const URL$1=self.URL,defaultBase$1=getDefaultBase();class URLWithLegacySupport$2{constructor(t="",r=defaultBase$1){this.super=new URL$1(t,r),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(t){this.super.hash=t}set host(t){this.super.host=t}set hostname(t){this.super.hostname=t}set href(t){this.super.href=t}set password(t){this.super.password=t}set pathname(t){this.super.pathname=t}set port(t){this.super.port=t}set protocol(t){this.super.protocol=t}set search(t){this.super.search=t}set username(t){this.super.username=t}static createObjectURL(t){return URL$1.createObjectURL(t)}static revokeObjectURL(t){URL$1.revokeObjectURL(t)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}}function format$2(e){if(typeof e=="string")return new URL$1(e).toString();if(!(e instanceof URL$1)){const t=e.username&&e.password?`${e.username}:${e.password}@`:"",r=e.auth?e.auth+"@":"",n=e.port?":"+e.port:"",o=e.protocol?e.protocol+"//":"",a=e.host||"",l=e.hostname||"",c=e.search||(e.query?"?"+e.query:""),u=e.hash||"",_=e.pathname||"",b=e.path||_+c;return`${o}${t||r}${a||l+n}${b}${u}`}}var urlBrowser={URLWithLegacySupport:URLWithLegacySupport$2,URLSearchParams:self.URLSearchParams,defaultBase:defaultBase$1,format:format$2};const{URLWithLegacySupport:URLWithLegacySupport$1,format:format$1}=urlBrowser;var relative$1=(e,t={},r={},n)=>{let o=t.protocol?t.protocol.replace(":",""):"http";o=(r[o]||n||o)+":";let a;try{a=new URLWithLegacySupport$1(e)}catch{a={}}const l=Object.assign({},t,{protocol:o||a.protocol,host:t.host||a.host});return new URLWithLegacySupport$1(e,format$1(l)).toString()};const{URLWithLegacySupport,format,URLSearchParams:URLSearchParams$1,defaultBase}=urlBrowser,relative=relative$1;var isoUrl={URL:URLWithLegacySupport,URLSearchParams:URLSearchParams$1,format,relative,defaultBase};const map$2={http:"ws",https:"wss"},def="ws",wsurl=(e,t)=>isoUrl.relative(e,t,map$2,def);function connect(e,t){const r=typeof window>"u"?"":window.location;t=t??{};const n=wsurl(e,r.toString()),o=new WebSocket$1(n,t.websocket);return duplex(o,t)}function isElectron$1(){return typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&!!process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0}var isElectron_1=isElectron$1;const isEnvWithDom=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,isElectron=isElectron_1(),isBrowser=isEnvWithDom&&!isElectron,isElectronMain=isElectron&&!isEnvWithDom,isElectronRenderer=isElectron&&isEnvWithDom,isNode=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!isElectron,isWebWorker=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope;typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"];const isReactNative=typeof navigator<"u"&&navigator.product==="ReactNative",CODE_P2P=421,CODE_CIRCUIT=290,CLOSE_TIMEOUT$1=500;function all$1(e){return e.filter(t=>{if(t.protoCodes().includes(CODE_CIRCUIT))return!1;const r=t.decapsulateCode(CODE_P2P);return WebSockets$1.matches(r)||WebSocketsSecure.matches(r)})}function wss(e){return e.filter(t=>{if(t.protoCodes().includes(CODE_CIRCUIT))return!1;const r=t.decapsulateCode(CODE_P2P);return WebSocketsSecure.matches(r)})}function createListener$1(){throw new Error("WebSocket Servers can not be created in the browser!")}const log$r=logger("libp2p:websockets:socket");function socketToMaConn(e,t,r){r=r??{};const n={async sink(o){r?.signal!=null&&(o=abortableSource(o,r.signal));try{await e.sink(o)}catch(a){a.type!=="aborted"&&log$r.error(a)}},source:r.signal!=null?abortableSource(e.source,r.signal):e.source,remoteAddr:t,timeline:{open:Date.now()},async close(o={}){const a=Date.now();o.signal=o.signal??AbortSignal.timeout(CLOSE_TIMEOUT$1);const l=()=>{const{host:c,port:u}=n.remoteAddr.toOptions();log$r("timeout closing stream to %s:%s after %dms, destroying it manually",c,u,Date.now()-a),this.abort(new CodeError("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};o.signal.addEventListener("abort",l);try{await e.close()}catch(c){this.abort(c)}finally{o.signal.removeEventListener("abort",l),n.timeline.close=Date.now()}},abort(o){const{host:a,port:l}=n.remoteAddr.toOptions();log$r("timeout closing stream to %s:%s due to error",a,l,o),e.destroy(),n.timeline.close=Date.now()}};return e.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}const log$q=logger("libp2p:websockets");var nc,ic;class WebSockets{constructor(t){Ye(this,"init");Ye(this,nc,"@libp2p/websockets");Ye(this,ic,!0);this.init=t}async dial(t,r){log$q("dialing %s",t),r=r??{};const n=await this._connect(t,r),o=socketToMaConn(n,t);log$q("new outbound connection %s",o.remoteAddr);const a=await r.upgrader.upgradeOutbound(o);return log$q("outbound connection %s upgraded",o.remoteAddr),a}async _connect(t,r){if(r?.signal?.aborted===!0)throw new AbortError$4;const n=t.toOptions();log$q("dialing %s:%s",n.host,n.port);const o=pDefer(),a=connect(multiaddrToUri(t),this.init);if(a.socket.addEventListener("error",()=>{const u=new CodeError(`Could not connect to ${t.toString()}`,"ERR_CONNECTION_FAILED");log$q.error("connection error:",u),o.reject(u)}),r.signal==null)return await Promise.race([a.connected(),o.promise]),log$q("connected %s",t),a;let l;const c=new Promise((u,_)=>{if(l=()=>{_(new AbortError$4),a.close().catch(b=>{log$q.error("error closing raw socket",b)})},r?.signal?.aborted===!0){l();return}r?.signal?.addEventListener("abort",l)});try{await Promise.race([c,o.promise,a.connected()])}finally{l!=null&&r?.signal?.removeEventListener("abort",l)}return log$q("connected %s",t),a}createListener(t){return createListener$1({...this.init,...t})}filter(t){return t=Array.isArray(t)?t:[t],this.init?.filter!=null?this.init?.filter(t):isBrowser||isWebWorker?wss(t):all$1(t)}}nc=Symbol.toStringTag,ic=symbol$1;function webSockets(e={}){return()=>new WebSockets(e)}var events$1={exports:{}},R$1=typeof Reflect=="object"?Reflect:null,ReflectApply=R$1&&typeof R$1.apply=="function"?R$1.apply:function e(t,r,n){return Function.prototype.apply.call(t,r,n)},ReflectOwnKeys;R$1&&typeof R$1.ownKeys=="function"?ReflectOwnKeys=R$1.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var NumberIsNaN=Number.isNaN||function e(t){return t!==t};function EventEmitter(){EventEmitter.init.call(this)}events$1.exports=EventEmitter;events$1.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=void 0;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(e){if(typeof e!="number"||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}});EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};EventEmitter.prototype.setMaxListeners=function e(t){if(typeof t!="number"||t<0||NumberIsNaN(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function e(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function e(t){for(var r=[],n=1;n0&&(l=r[0]),l instanceof Error)throw l;var c=new Error("Unhandled error."+(l?" ("+l.message+")":""));throw c.context=l,c}var u=a[t];if(u===void 0)return!1;if(typeof u=="function")ReflectApply(u,this,r);else for(var _=u.length,b=arrayClone(u,_),n=0;n<_;++n)ReflectApply(b[n],this,r);return!0};function _addListener(e,t,r,n){var o,a,l;if(checkListener(r),a=e._events,a===void 0?(a=e._events=Object.create(null),e._eventsCount=0):(a.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),l=a[t]),l===void 0)l=a[t]=r,++e._eventsCount;else if(typeof l=="function"?l=a[t]=n?[r,l]:[l,r]:n?l.unshift(r):l.push(r),o=_getMaxListeners(e),o>0&&l.length>o&&!l.warned){l.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=l.length,ProcessEmitWarning(c)}return e}EventEmitter.prototype.addListener=function e(t,r){return _addListener(this,t,r,!1)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function e(t,r){return _addListener(this,t,r,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=onceWrapper.bind(n);return o.listener=r,n.wrapFn=o,o}EventEmitter.prototype.once=function e(t,r){return checkListener(r),this.on(t,_onceWrap(this,t,r)),this};EventEmitter.prototype.prependOnceListener=function e(t,r){return checkListener(r),this.prependListener(t,_onceWrap(this,t,r)),this};EventEmitter.prototype.removeListener=function e(t,r){var n,o,a,l,c;if(checkListener(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,l=n.length-1;l>=0;l--)if(n[l]===r||n[l].listener===r){c=n[l].listener,a=l;break}if(a<0)return this;a===0?n.shift():spliceOne(n,a),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,c||r)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function e(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var a=Object.keys(n),l;for(o=0;o=0;o--)this.removeListener(t,r[o]);return this};function _listeners(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?unwrapListeners(o):arrayClone(o,o.length)}EventEmitter.prototype.listeners=function e(t){return _listeners(this,t,!0)};EventEmitter.prototype.rawListeners=function e(t){return _listeners(this,t,!1)};EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount.call(e,t)};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}EventEmitter.prototype.eventNames=function e(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(e,t){for(var r=new Array(t),n=0;ncrypto.getRandomValues(new Uint8Array(e)).reduce((t,r)=>(r&=63,r<36?t+=r.toString(36):r<62?t+=(r-26).toString(36).toUpperCase():r>62?t+="-":t+="_",t),"");const pathSepS="/",pathSepB=new TextEncoder().encode(pathSepS),pathSep=pathSepB[0];class Key{constructor(t,r){Ye(this,"_buf");if(typeof t=="string")this._buf=fromString$1(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==pathSep)throw new Error("Invalid key")}toString(t="utf8"){return toString$5(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new Key(t.join(pathSepS))}static random(){return new Key(nanoid().replace(/-/g,""))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new Key(t):typeof t.uint8Array=="function"?new Key(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=pathSepB),this._buf[0]!==pathSep){const t=new Uint8Array(this._buf.byteLength+1);t.fill(pathSep,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===pathSep;)this._buf=this._buf.subarray(0,-1)}less(t){const r=this.list(),n=t.list();for(let o=0;ol)return!1}return r.lengthr.namespaces()))])}}function namespaceType(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function namespaceValue(e){const t=e.split(":");return t[t.length-1]}function flatten(e){return[].concat(...e)}var isPlainObj=e=>{if(Object.prototype.toString.call(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype};const isOptionObject=isPlainObj,{hasOwnProperty:hasOwnProperty$1}=Object.prototype,{propertyIsEnumerable}=Object,defineProperty=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),globalThis$4=commonjsGlobal$2,defaultMergeOptions={concatArrays:!1,ignoreUndefined:!1},getEnumerableOwnPropertyKeys=e=>{const t=[];for(const r in e)hasOwnProperty$1.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)propertyIsEnumerable.call(e,n)&&t.push(n)}return t};function clone$1(e){return Array.isArray(e)?cloneArray(e):isOptionObject(e)?cloneOptionObject(e):e}function cloneArray(e){const t=e.slice(0,0);return getEnumerableOwnPropertyKeys(e).forEach(r=>{defineProperty(t,r,clone$1(e[r]))}),t}function cloneOptionObject(e){const t=Object.getPrototypeOf(e)===null?Object.create(null):{};return getEnumerableOwnPropertyKeys(e).forEach(r=>{defineProperty(t,r,clone$1(e[r]))}),t}const mergeKeys=(e,t,r,n)=>(r.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in e&&e[o]!==Object.getPrototypeOf(e)?defineProperty(e,o,merge(e[o],t[o],n)):defineProperty(e,o,clone$1(t[o])))}),e),concatArrays=(e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach(a=>{const l=[];for(let c=0;c!l.includes(c)),r)}),n};function merge(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?concatArrays(e,t,r):!isOptionObject(t)||!isOptionObject(e)?clone$1(t):mergeKeys(e,t,getEnumerableOwnPropertyKeys(t),r)}var mergeOptions=function(...e){const t=merge(clone$1(defaultMergeOptions),this!==globalThis$4&&this||{},defaultMergeOptions);let r={_:{}};for(const n of e)if(n!==void 0){if(!isOptionObject(n))throw new TypeError("`"+n+"` is not an Option Object");r=merge(r,{_:n},t)}return r._};function isHighSurrogate$1(e){return e>=55296&&e<=56319}function isLowSurrogate$1(e){return e>=56320&&e<=57343}var truncate$2=function e(t,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var o=r.length,a=0,l,c,u=0;un)return r.slice(0,u-c.length+1)}return r};function isHighSurrogate(e){return e>=55296&&e<=56319}function isLowSurrogate(e){return e>=56320&&e<=57343}var browser$5=function e(t){if(typeof t!="string")throw new Error("Input must be string");for(var r=t.length,n=0,o=null,a=null,l=0;l=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),a=o;return n},truncate$1=truncate$2,getLength=browser$5,browser$4=truncate$1.bind(null,getLength),truncate=browser$4,illegalRe=/[\/\?<>\\:\*\|"]/g,controlRe=/[\x00-\x1f\x80-\x9f]/g,reservedRe=/^\.+$/,windowsReservedRe=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,windowsTrailingRe=/[\. ]+$/;function sanitize(e,t){if(typeof e!="string")throw new Error("Input must be string");var r=e.replace(illegalRe,t).replace(controlRe,t).replace(reservedRe,t).replace(windowsReservedRe,t).replace(windowsTrailingRe,t);return truncate(r,255)}var sanitizeFilename=function(e,t){var r=t&&t.replacement||"",n=sanitize(e,r);return r===""?n:sanitize(n,"")},codes$3;(function(e){e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(codes$3||(codes$3={}));const log$p=logger("libp2p:keychain"),keyPrefix="/pkcs8/",infoPrefix="/info/",privates=new WeakMap,NIST={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},defaultOptions$6={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function validateKeyName(e){return e==null||typeof e!="string"?!1:e===sanitizeFilename(e.trim())&&e.length>0}async function randomDelay(){const r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function DsName(e){return new Key(keyPrefix+e)}function DsInfoName(e){return new Key(infoPrefix+e)}class DefaultKeyChain{constructor(t,r){Ye(this,"components");Ye(this,"init");if(this.components=t,this.init=mergeOptions(defaultOptions$6,r),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLengtho.id===t);if(n==null)throw new CodeError(`Key with id '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND);return n}catch(r){throw await randomDelay(),r}}async findKeyByName(t){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);const r=DsInfoName(t);try{const n=await this.components.datastore.get(r);return JSON.parse(toString$5(n))}catch(n){throw await randomDelay(),log$p.error(n),new CodeError(`Key '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND)}}async removeKey(t){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);const r=DsName(t),n=await this.findKeyByName(t),o=this.components.datastore.batch();return o.delete(r),o.delete(DsInfoName(t)),await o.commit(),n}async renameKey(t,r){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid old key name '${t}'`,codes$3.ERR_OLD_KEY_NAME_INVALID);if(!validateKeyName(r)||r==="self")throw await randomDelay(),new CodeError(`Invalid new key name '${r}'`,codes$3.ERR_NEW_KEY_NAME_INVALID);const n=DsName(t),o=DsName(r),a=DsInfoName(t),l=DsInfoName(r);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${r}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);try{const u=await this.components.datastore.get(n),_=await this.components.datastore.get(a),b=JSON.parse(toString$5(_));b.name=r;const x=this.components.datastore.batch();return x.put(o,u),x.put(l,fromString$1(JSON.stringify(b))),x.delete(n),x.delete(a),await x.commit(),b}catch(u){throw await randomDelay(),u}}async exportKey(t,r){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw await randomDelay(),new CodeError("Password is required",codes$3.ERR_PASSWORD_REQUIRED);const n=DsName(t);try{const o=await this.components.datastore.get(n),a=toString$5(o),l=privates.get(this);if(l==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const c=l.dek;return await(await importKey(a,c)).export(r)}catch(o){throw await randomDelay(),o}}async exportPeerId(t){const r="temporary-password",n=await this.exportKey(t,r),o=await importKey(n,r);return peerIdFromKeys(o.public.bytes,o.bytes)}async importKey(t,r,n){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw await randomDelay(),new CodeError("PEM encoded key is required",codes$3.ERR_PEM_REQUIRED);const o=DsName(t);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${t}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);let l;try{l=await importKey(r,n)}catch{throw await randomDelay(),new CodeError("Cannot read the key, most likely the password is wrong",codes$3.ERR_CANNOT_READ_KEY)}let c;try{c=await l.id();const b=privates.get(this);if(b==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const x=b.dek;r=await l.export(x)}catch(b){throw await randomDelay(),b}const u={name:t,id:c},_=this.components.datastore.batch();return _.put(o,fromString$1(r)),_.put(DsInfoName(t),fromString$1(JSON.stringify(u))),await _.commit(),u}async importPeer(t,r){try{if(!validateKeyName(t))throw new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw new CodeError("PeerId is required",codes$3.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new CodeError("PeerId.privKey is required",codes$3.ERR_MISSING_PRIVATE_KEY);const n=await unmarshalPrivateKey(r.privateKey),o=DsName(t);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${t}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);const l=privates.get(this);if(l==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const c=l.dek,u=await n.export(c),_={name:t,id:r.toString()},b=this.components.datastore.batch();return b.put(o,fromString$1(u)),b.put(DsInfoName(t),fromString$1(JSON.stringify(_))),await b.commit(),_}catch(n){throw await randomDelay(),n}}async getPrivateKey(t){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);try{const r=DsName(t),n=await this.components.datastore.get(r);return toString$5(n)}catch(r){throw await randomDelay(),log$p.error(r),new CodeError(`Key '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(t,r){if(typeof t!="string")throw await randomDelay(),new CodeError(`Invalid old pass type '${typeof t}'`,codes$3.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await randomDelay(),new CodeError(`Invalid new pass type '${typeof r}'`,codes$3.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await randomDelay(),new CodeError(`Invalid pass length ${r.length}`,codes$3.ERR_INVALID_PASS_LENGTH);log$p("recreating keychain");const n=privates.get(this);if(n==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const o=n.dek;this.init.pass=r;const a=r!=null&&this.init.dek?.salt!=null?pbkdf2(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";privates.set(this,{dek:a});const l=await this.listKeys();for(const c of l){const u=await this.components.datastore.get(DsName(c.name)),_=toString$5(u),b=await importKey(_,o),x=a.toString(),E=await b.export(x),I=this.components.datastore.batch(),k={name:c.name,id:c.id};I.put(DsName(c.name),fromString$1(E)),I.put(DsInfoName(c.name),fromString$1(JSON.stringify(k))),await I.commit()}log$p("keychain reconstructed")}}var PeerIdProto;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.id!=null&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.id=r.bytes();break;case 2:o.pubKey=r.bytes();break;case 3:o.privKey=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerIdProto||(PeerIdProto={}));const createEd25519PeerId=async()=>{const e=await generateKeyPair("Ed25519"),t=await createFromPrivKey(e);if(t.type==="Ed25519")return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function createFromPrivKey(e){return peerIdFromKeys(marshalPublicKey(e.public),marshalPrivateKey(e))}const codes$2={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Envelope;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.publicKey!=null&&r.publicKey.byteLength>0&&(n.uint32(10),n.bytes(r.publicKey)),r.payloadType!=null&&r.payloadType.byteLength>0&&(n.uint32(18),n.bytes(r.payloadType)),r.payload!=null&&r.payload.byteLength>0&&(n.uint32(26),n.bytes(r.payload)),r.signature!=null&&r.signature.byteLength>0&&(n.uint32(42),n.bytes(r.signature)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.publicKey=r.bytes();break;case 2:o.payloadType=r.bytes();break;case 3:o.payload=r.bytes();break;case 5:o.signature=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Envelope||(Envelope={}));const Qi=class{constructor(t){Ye(this,"peerId");Ye(this,"payloadType");Ye(this,"payload");Ye(this,"signature");Ye(this,"marshaled");const{peerId:r,payloadType:n,payload:o,signature:a}=t;this.peerId=r,this.payloadType=n,this.payload=o,this.signature=a}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Envelope.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return equals$2(this.marshal(),t.marshal())}async validate(t){const r=formatSignaturePayload(t,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return unmarshalPublicKey(this.peerId.publicKey).verify(r.subarray(),this.signature)}};let RecordEnvelope=Qi;Ye(RecordEnvelope,"createFromProtobuf",async t=>{const r=Envelope.decode(t),n=await peerIdFromKeys(r.publicKey);return new Qi({peerId:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})}),Ye(RecordEnvelope,"seal",async(t,r)=>{if(r.privateKey==null)throw new Error("Missing private key");const n=t.domain,o=t.codec,a=t.marshal(),l=formatSignaturePayload(n,o,a),u=await(await unmarshalPrivateKey(r.privateKey)).sign(l.subarray());return new Qi({peerId:r,payloadType:o,payload:a,signature:u})}),Ye(RecordEnvelope,"openAndCertify",async(t,r)=>{const n=await Qi.createFromProtobuf(t);if(!await n.validate(r))throw new CodeError("envelope signature is not valid for the given domain",codes$2.ERR_SIGNATURE_NOT_VALID);return n});const formatSignaturePayload=(e,t,r)=>{const n=fromString$1(e),o=encode$d(n.byteLength),a=encode$d(t.length),l=encode$d(r.length);return new Uint8ArrayList(o,n,a,t,l,r)};function arrayEquals(e,t){const r=(n,o)=>n.toString().localeCompare(o.toString());return e.length!==t.length?!1:(t.sort(r),e.sort(r).every((n,o)=>t[o].equals(n)))}const ENVELOPE_DOMAIN_PEER_RECORD="libp2p-peer-record",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD=Uint8Array.from([3,1]);var PeerRecord$1;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(a.uint32(10),a.bytes(o.multiaddr)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={multiaddr:new Uint8Array(0)},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.AddressInfo||(e.AddressInfo={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.peerId!=null&&r.peerId.byteLength>0&&(n.uint32(10),n.bytes(r.peerId)),r.seq!=null&&r.seq!==0n&&(n.uint32(16),n.uint64(r.seq)),r.addresses!=null)for(const a of r.addresses)n.uint32(26),e.AddressInfo.codec().encode(a,n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={peerId:new Uint8Array(0),seq:0n,addresses:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.peerId=r.bytes();break;case 2:o.seq=r.uint64();break;case 3:o.addresses.push(e.AddressInfo.codec().decode(r,r.uint32()));break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerRecord$1||(PeerRecord$1={}));const yi=class{constructor(t){Ye(this,"peerId");Ye(this,"multiaddrs");Ye(this,"seqNumber");Ye(this,"domain",yi.DOMAIN);Ye(this,"codec",yi.CODEC);Ye(this,"marshaled");const{peerId:r,multiaddrs:n,seqNumber:o}=t;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=PeerRecord$1.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof yi)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!arrayEquals(this.multiaddrs,t.multiaddrs))}};let PeerRecord=yi;Ye(PeerRecord,"createFromProtobuf",t=>{const r=PeerRecord$1.decode(t),n=peerIdFromBytes(r.peerId),o=(r.addresses??[]).map(l=>multiaddr(l.multiaddr)),a=r.seq;return new yi({peerId:n,multiaddrs:o,seqNumber:a})}),Ye(PeerRecord,"DOMAIN",ENVELOPE_DOMAIN_PEER_RECORD),Ye(PeerRecord,"CODEC",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD);function isAsyncIterable$6(e){return e[Symbol.asyncIterator]!=null}function all(e){if(isAsyncIterable$6(e))return(async()=>{const r=[];for await(const n of e)r.push(n);return r})();const t=[];for(const r of e)t.push(r);return t}const WORKER_REQUEST_READ_LOCK="lock:worker:request-read",WORKER_RELEASE_READ_LOCK="lock:worker:release-read",MASTER_GRANT_READ_LOCK="lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK="lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK="lock:worker:release-write",MASTER_GRANT_WRITE_LOCK="lock:master:grant-write",events={},observable=e=>{e.addEventListener("message",t=>{observable.dispatchEvent("message",e,t)}),e.port!=null&&e.port.addEventListener("message",t=>{observable.dispatchEvent("message",e,t)})};observable.addEventListener=(e,t)=>{events[e]==null&&(events[e]=[]),events[e].push(t)};observable.removeEventListener=(e,t)=>{events[e]!=null&&(events[e]=events[e].filter(r=>r===t))};observable.dispatchEvent=function(e,t,r){events[e]!=null&&events[e].forEach(n=>n(t,r))};const handleWorkerLockRequest=(e,t,r,n,o)=>(a,l)=>{if(l.data.type!==r)return;const c={type:l.data.type,name:l.data.name,identifier:l.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:c.name,handler:async()=>(a.postMessage({type:o,name:c.name,identifier:c.identifier}),await new Promise(u=>{const _=b=>{if(b==null||b.data==null)return;const x={type:b.data.type,name:b.data.name,identifier:b.data.identifier};x.type===n&&x.identifier===c.identifier&&(a.removeEventListener("message",_),u())};a.addEventListener("message",_)}))}}))},makeWorkerLockRequest=(e,t,r,n)=>async()=>{const o=nanoid();return globalThis.postMessage({type:t,identifier:o,name:e}),await new Promise(a=>{const l=c=>{if(c==null||c.data==null)return;const u={type:c.data.type,identifier:c.data.identifier};u.type===r&&u.identifier===o&&(globalThis.removeEventListener("message",l),a(()=>{globalThis.postMessage({type:n,identifier:o,name:e})}))};globalThis.addEventListener("message",l)})},defaultOptions$5={singleProcess:!1},impl=e=>{if(e=Object.assign({},defaultOptions$5,e),Boolean(globalThis.document)||e.singleProcess){const r=new EventTarget;return observable.addEventListener("message",handleWorkerLockRequest(r,"requestReadLock",WORKER_REQUEST_READ_LOCK,WORKER_RELEASE_READ_LOCK,MASTER_GRANT_READ_LOCK)),observable.addEventListener("message",handleWorkerLockRequest(r,"requestWriteLock",WORKER_REQUEST_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK)),r}return{isWorker:!0,readLock:r=>makeWorkerLockRequest(r,WORKER_REQUEST_READ_LOCK,MASTER_GRANT_READ_LOCK,WORKER_RELEASE_READ_LOCK),writeLock:r=>makeWorkerLockRequest(r,WORKER_REQUEST_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK)}},mutexes={};let implementation;async function createReleaseable(e,t){let r;const n=new Promise(o=>{r=o});return e.add(async()=>await pTimeout((async()=>await new Promise(o=>{r(()=>{o()})}))(),{milliseconds:t.timeout})),await n}const createMutex=(e,t)=>{if(implementation.isWorker===!0)return{readLock:implementation.readLock(e,t),writeLock:implementation.writeLock(e,t)};const r=new PQueue({concurrency:1});let n;return{async readLock(){if(n!=null)return await createReleaseable(n,t);n=new PQueue({concurrency:t.concurrency,autoStart:!1});const o=n,a=createReleaseable(n,t);return r.add(async()=>(o.start(),await o.onIdle().then(()=>{n===o&&(n=null)}))),await a},async writeLock(){return n=null,await createReleaseable(r,t)}}},defaultOptions$4={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function createMortice(e){const t=Object.assign({},defaultOptions$4,e);return implementation==null&&(implementation=impl(t),implementation.isWorker!==!0&&(implementation.addEventListener("requestReadLock",r=>{mutexes[r.data.name]!=null&&mutexes[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),implementation.addEventListener("requestWriteLock",async r=>{mutexes[r.data.name]!=null&&mutexes[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),mutexes[t.name]==null&&(mutexes[t.name]=createMutex(t.name,t)),mutexes[t.name]}const codes$1={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Peer$1;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={key:"",value:new Uint8Array(0)},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.key=o.string();break;case 2:l.value=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),Tag.codec().encode(o.value,a)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={key:""},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.key=o.string();break;case 2:l.value=Tag.codec().decode(o,o.uint32());break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())}(e.Peer$tagsEntry||(e.Peer$tagsEntry={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.addresses!=null)for(const a of r.addresses)n.uint32(10),Address.codec().encode(a,n);if(r.protocols!=null)for(const a of r.protocols)n.uint32(18),n.string(a);if(r.publicKey!=null&&(n.uint32(34),n.bytes(r.publicKey)),r.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(r.peerRecordEnvelope)),r.metadata!=null&&r.metadata.size!==0)for(const[a,l]of r.metadata.entries())n.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:l},n);if(r.tags!=null&&r.tags.size!==0)for(const[a,l]of r.tags.entries())n.uint32(58),e.Peer$tagsEntry.codec().encode({key:a,value:l},n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.addresses.push(Address.codec().decode(r,r.uint32()));break;case 2:o.protocols.push(r.string());break;case 4:o.publicKey=r.bytes();break;case 5:o.peerRecordEnvelope=r.bytes();break;case 6:{const c=e.Peer$metadataEntry.codec().decode(r,r.uint32());o.metadata.set(c.key,c.value);break}case 7:{const c=e.Peer$tagsEntry.codec().decode(r,r.uint32());o.tags.set(c.key,c.value);break}default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Peer$1||(Peer$1={}));var Address;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.multiaddr!=null&&r.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={multiaddr:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.multiaddr=r.bytes();break;case 2:o.isCertified=r.bool();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Address||(Address={}));var Tag;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.value!=null&&r.value!==0&&(n.uint32(8),n.uint32(r.value)),r.expiry!=null&&(n.uint32(16),n.uint64(r.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={value:0},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.value=r.uint32();break;case 2:o.expiry=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Tag||(Tag={}));function bytesToPeer(e,t){const r=Peer$1.decode(t);r.publicKey!=null&&e.publicKey==null&&(e=peerIdFromPeerId({...e,publicKey:e.publicKey}));const n=new Map,o=BigInt(Date.now());for(const[a,l]of r.tags.entries())l.expiry!=null&&l.expiry({multiaddr:multiaddr(a),isCertified:l??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}const NAMESPACE_COMMON="/peers/";function peerIdToDatastoreKey(e){if(!isPeerId(e)||e.type==null)throw new CodeError("Invalid PeerId",codes$1.ERR_INVALID_PARAMETERS);const t=e.toCID().toString();return new Key(`${NAMESPACE_COMMON}${t}`)}async function dedupeFilterAndSortAddresses(e,t,r){const n=new Map;for(const o of r){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=multiaddr(o.multiaddr)),!isMultiaddr(o.multiaddr))throw new CodeError("Multiaddr was invalid",codes$1.ERR_INVALID_PARAMETERS);if(!await t(e,o.multiaddr))continue;const a=o.isCertified??!1,l=o.multiaddr.toString(),c=n.get(l);c!=null?o.isCertified=c.isCertified||a:n.set(l,{multiaddr:o.multiaddr,isCertified:a})}return[...n.values()].sort((o,a)=>o.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:o,multiaddr:a})=>({isCertified:o,multiaddr:a.bytes}))}async function toPeerPB(e,t,r,n){if(t==null)throw new CodeError("Invalid PeerData",codes$1.ERR_INVALID_PARAMETERS);if(t.publicKey!=null&&e.publicKey!=null&&!equals$2(t.publicKey,e.publicKey))throw new CodeError("publicKey bytes do not match peer id publicKey bytes",codes$1.ERR_INVALID_PARAMETERS);const o=n.existingPeer;if(o!=null&&!e.equals(o.id))throw new CodeError("peer id did not match existing peer id",codes$1.ERR_INVALID_PARAMETERS);let a=o?.addresses??[],l=new Set(o?.protocols??[]),c=o?.metadata??new Map,u=o?.tags??new Map,_=o?.peerRecordEnvelope;if(r==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(a=[],t.multiaddrs!=null&&a.push(...t.multiaddrs.map(x=>({isCertified:!1,multiaddr:x}))),t.addresses!=null&&a.push(...t.addresses)),t.protocols!=null&&(l=new Set(t.protocols)),t.metadata!=null){const x=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);c=createSortedMap(x,{validate:validateMetadata})}if(t.tags!=null){const x=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);u=createSortedMap(x,{validate:validateTag,map:mapTag})}t.peerRecordEnvelope!=null&&(_=t.peerRecordEnvelope)}if(r==="merge"){if(t.multiaddrs!=null&&a.push(...t.multiaddrs.map(x=>({isCertified:!1,multiaddr:x}))),t.addresses!=null&&a.push(...t.addresses),t.protocols!=null&&(l=new Set([...l,...t.protocols])),t.metadata!=null){const x=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[E,I]of x)I==null?c.delete(E):c.set(E,I);c=createSortedMap([...c.entries()],{validate:validateMetadata})}if(t.tags!=null){const x=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),E=new Map(u);for(const[I,k]of x)k==null?E.delete(I):E.set(I,k);u=createSortedMap([...E.entries()],{validate:validateTag,map:mapTag})}t.peerRecordEnvelope!=null&&(_=t.peerRecordEnvelope)}const b={addresses:await dedupeFilterAndSortAddresses(e,n.addressFilter??(async()=>!0),a),protocols:[...l.values()].sort((x,E)=>x.localeCompare(E)),metadata:c,tags:u,publicKey:o?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:_};return e.type!=="RSA"&&delete b.publicKey,b}function createSortedMap(e,t){const r=new Map;for(const[n,o]of e)o!=null&&t.validate(n,o);for(const[n,o]of e.sort(([a],[l])=>a.localeCompare(l)))o!=null&&r.set(n,t.map?.(n,o)??o);return r}function validateMetadata(e,t){if(typeof e!="string")throw new CodeError("Metadata key must be a string",codes$1.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new CodeError("Metadata value must be a Uint8Array",codes$1.ERR_INVALID_PARAMETERS)}function validateTag(e,t){if(typeof e!="string")throw new CodeError("Tag name must be a string",codes$1.ERR_INVALID_PARAMETERS);if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new CodeError("Tag value must be an integer",codes$1.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new CodeError("Tag value must be between 0-100",codes$1.ERR_INVALID_PARAMETERS)}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new CodeError("Tag ttl must be an integer",codes$1.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new CodeError("Tag ttl must be between greater than 0",codes$1.ERR_INVALID_PARAMETERS)}}function mapTag(e,t){let r;return t.expiry!=null&&(r=t.expiry),t.ttl!=null&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function decodePeer(e,t,r){const n=e.toString().split("/")[2],o=base32$2.decode(n),a=peerIdFromBytes(o),l=r.get(a);if(l!=null)return l;const c=bytesToPeer(a,t);return r.set(a,c),c}function mapQuery(e,t){return e==null?{}:{prefix:NAMESPACE_COMMON,filters:(e.filters??[]).map(r=>({key:n,value:o})=>r(decodePeer(n,o,t))),orders:(e.orders??[]).map(r=>(n,o)=>r(decodePeer(n.key,n.value,t),decodePeer(o.key,o.value,t)))}}var _i,so,bi,oo;class PersistentStore{constructor(t,r={}){_r(this,_i);_r(this,bi);Ye(this,"peerId");Ye(this,"datastore");Ye(this,"lock");Ye(this,"addressFilter");this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=r.addressFilter,this.lock=createMortice({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(peerIdToDatastoreKey(t))}async delete(t){if(this.peerId.equals(t))throw new CodeError("Cannot delete self peer",codes$1.ERR_INVALID_PARAMETERS);await this.datastore.delete(peerIdToDatastoreKey(t))}async load(t){const r=await this.datastore.get(peerIdToDatastoreKey(t));return bytesToPeer(t,r)}async save(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"patch",{addressFilter:this.addressFilter});return vr(this,bi,oo).call(this,t,a,n,o)}async patch(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"patch",{addressFilter:this.addressFilter,existingPeer:o});return vr(this,bi,oo).call(this,t,a,n,o)}async merge(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"merge",{addressFilter:this.addressFilter,existingPeer:o});return vr(this,bi,oo).call(this,t,a,n,o)}async*all(t){const r=new PeerMap;for await(const{key:n,value:o}of this.datastore.query(mapQuery(t??{},r))){const a=decodePeer(n,o,r);a.id.equals(this.peerId)||(yield a)}}}_i=new WeakSet,so=async function(t){try{const r=await this.datastore.get(peerIdToDatastoreKey(t)),n=bytesToPeer(t,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}},bi=new WeakSet,oo=async function(t,r,n,o){const a=Peer$1.encode(r);return n!=null&&equals$2(a,n)?{peer:bytesToPeer(t,a),previous:o,updated:!1}:(await this.datastore.put(peerIdToDatastoreKey(t),a),{peer:bytesToPeer(t,a),previous:o,updated:!0})};const log$o=logger("libp2p:peer-store");var wi,ao;class PersistentPeerStore{constructor(t,r={}){_r(this,wi);Ye(this,"store");Ye(this,"events");Ye(this,"peerId");this.events=t.events,this.peerId=t.peerId,this.store=new PersistentStore(t,r)}async forEach(t,r){log$o.trace("forEach await read lock");const n=await this.store.lock.readLock();log$o.trace("forEach got read lock");try{for await(const o of this.store.all(r))t(o)}finally{log$o.trace("forEach release read lock"),n()}}async all(t){log$o.trace("all await read lock");const r=await this.store.lock.readLock();log$o.trace("all got read lock");try{return await all(this.store.all(t))}finally{log$o.trace("all release read lock"),r()}}async delete(t){log$o.trace("delete await write lock");const r=await this.store.lock.writeLock();log$o.trace("delete got write lock");try{await this.store.delete(t)}finally{log$o.trace("delete release write lock"),r()}}async has(t){log$o.trace("has await read lock");const r=await this.store.lock.readLock();log$o.trace("has got read lock");try{return await this.store.has(t)}finally{log$o.trace("has release read lock"),r()}}async get(t){log$o.trace("get await read lock");const r=await this.store.lock.readLock();log$o.trace("get got read lock");try{return await this.store.load(t)}finally{log$o.trace("get release read lock"),r()}}async save(t,r){log$o.trace("save await write lock");const n=await this.store.lock.writeLock();log$o.trace("save got write lock");try{const o=await this.store.save(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("save release write lock"),n()}}async patch(t,r){log$o.trace("patch await write lock");const n=await this.store.lock.writeLock();log$o.trace("patch got write lock");try{const o=await this.store.patch(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("patch release write lock"),n()}}async merge(t,r){log$o.trace("merge await write lock");const n=await this.store.lock.writeLock();log$o.trace("merge got write lock");try{const o=await this.store.merge(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("merge release write lock"),n()}}async consumePeerRecord(t,r){const n=await RecordEnvelope.openAndCertify(t,PeerRecord.DOMAIN);if(r?.equals(n.peerId)===!1)return log$o("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;const o=PeerRecord.createFromProtobuf(n.payload);let a;try{a=await this.get(n.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(a?.peerRecordEnvelope!=null){const l=await RecordEnvelope.createFromProtobuf(a.peerRecordEnvelope),c=PeerRecord.createFromProtobuf(l.payload);if(c.seqNumber>=o.seqNumber)return log$o("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:t,addresses:o.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))}),!0}}wi=new WeakSet,ao=function(t,r){!r.updated||(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))};function isAsyncIterable$5(e){return e[Symbol.asyncIterator]!=null}function drain(e){if(isAsyncIterable$5(e))return(async()=>{for await(const t of e);})();for(const t of e);}function peekable(e){const[t,r]=e[Symbol.asyncIterator]!=null?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}function isAsyncIterable$4(e){return e[Symbol.asyncIterator]!=null}function filter(e,t){if(isAsyncIterable$4(e))return async function*(){for await(const c of e)await t(c)&&(yield c)}();const r=peekable(e),{value:n,done:o}=r.next();if(o===!0)return function*(){}();const a=t(n);if(typeof a.then=="function")return async function*(){await a&&(yield n);for await(const c of r)await t(c)&&(yield c)}();const l=t;return function*(){a===!0&&(yield n);for(const c of r)l(c)&&(yield c)}()}function isAsyncIterable$3(e){return e[Symbol.asyncIterator]!=null}function sort(e,t){return isAsyncIterable$3(e)?async function*(){yield*(await all(e)).sort(t)}():function*(){yield*all(e).sort(t)}()}function isAsyncIterable$2(e){return e[Symbol.asyncIterator]!=null}function take(e,t){return isAsyncIterable$2(e)?async function*(){let r=0;if(!(t<1)){for await(const n of e)if(yield n,r++,r===t)return}}():function*(){let r=0;if(!(t<1)){for(const n of e)if(yield n,r++,r===t)return}}()}class BaseDatastore{put(t,r,n){return Promise.reject(new Error(".put is not implemented"))}get(t,r){return Promise.reject(new Error(".get is not implemented"))}has(t,r){return Promise.reject(new Error(".has is not implemented"))}delete(t,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,r={}){for await(const{key:n,value:o}of t)await this.put(n,o,r),yield n}async*getMany(t,r={}){for await(const n of t)yield{key:n,value:await this.get(n,r)}}async*deleteMany(t,r={}){for await(const n of t)await this.delete(n,r),yield n}batch(){let t=[],r=[];return{put(n,o){t.push({key:n,value:o})},delete(n){r.push(n)},commit:async n=>{await drain(this.putMany(t,n)),t=[],await drain(this.deleteMany(r,n)),r=[]}}}async*_all(t,r){throw new Error("._all is not implemented")}async*_allKeys(t,r){throw new Error("._allKeys is not implemented")}query(t,r){let n=this._all(t,r);if(t.prefix!=null){const o=t.prefix;n=filter(n,a=>a.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,a)=>filter(o,a),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,a)=>sort(o,a),n)),t.offset!=null){let o=0;const a=t.offset;n=filter(n,()=>o++>=a)}return t.limit!=null&&(n=take(n,t.limit)),n}queryKeys(t,r){let n=this._allKeys(t,r);if(t.prefix!=null){const o=t.prefix;n=filter(n,a=>a.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,a)=>filter(o,a),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,a)=>sort(o,a),n)),t.offset!=null){const o=t.offset;let a=0;n=filter(n,()=>a++>=o)}return t.limit!=null&&(n=take(n,t.limit)),n}}function notFoundError(e){return e=e??new Error("Not Found"),errCode(e,"ERR_NOT_FOUND")}class MemoryDatastore extends BaseDatastore{constructor(){super();Ye(this,"data");this.data=new Map}put(r,n){return this.data.set(r.toString(),n),r}get(r){const n=this.data.get(r.toString());if(n==null)throw notFoundError();return n}has(r){return this.data.has(r.toString())}delete(r){this.data.delete(r.toString())}*_all(){for(const[r,n]of this.data.entries())yield{key:new Key(r),value:n}}*_allKeys(){for(const r of this.data.keys())yield new Key(r)}}function debounce(e,t){let r;return function(){const n=function(){r=void 0,e()};clearTimeout(r),r=setTimeout(n,t)}}const log$n=logger("libp2p:address-manager"),defaultAddressFilter=e=>e;function stripPeerId(e,t){const r=e.getPeerId();return r!=null&&peerIdFromString(r).equals(t)&&(e=e.decapsulate(multiaddr(`/p2p/${t.toString()}`))),e}class DefaultAddressManager{constructor(t,r={}){Ye(this,"components");Ye(this,"listen");Ye(this,"announce");Ye(this,"observed");Ye(this,"announceFilter");const{listen:n=[],announce:o=[]}=r;this.components=t,this.listen=n.map(a=>a.toString()),this.announce=new Set(o.map(a=>a.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??defaultAddressFilter,this._updatePeerStoreAddresses=debounce(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){const t=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>multiaddr(r))).map(r=>r.getPeerId()===this.components.peerId.toString()?r.decapsulate(`/p2p/${this.components.peerId.toString()}`):r);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(r=>{log$n.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(t=>multiaddr(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>multiaddr(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>multiaddr(t))}addObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString(),o=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString();this.observed.delete(r)}getAddresses(){let t=this.getAnnounceAddrs().map(n=>n.toString());t.length===0&&(t=this.components.transportManager.getAddrs().map(n=>n.toString())),t=t.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));const r=new Set(t);return this.announceFilter(Array.from(r).map(n=>multiaddr(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}}function isStartable(e){return e!=null&&typeof e.start=="function"&&typeof e.stop=="function"}class DefaultComponents{constructor(t={}){Ye(this,"components",{});Ye(this,"_started",!1);this.components={};for(const[r,n]of Object.entries(t))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(r=>isStartable(r)).map(async r=>{await r[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const OPTIONAL_SERVICES=["metrics","connectionProtector"],NON_SERVICE_PROPERTIES=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function defaultComponents(e={}){const t=new DefaultComponents(e);return new Proxy(t,{get(n,o,a){if(typeof o=="string"&&!NON_SERVICE_PROPERTIES.includes(o)){const l=t.components[o];if(l==null&&!OPTIONAL_SERVICES.includes(o))throw new CodeError(`${o} not set`,"ERR_SERVICE_MISSING");return l}return Reflect.get(n,o,a)},set(n,o,a){return typeof o=="string"?t.components[o]=a:Reflect.set(n,o,a),!0}})}var Netmask_1;(function(){var e,t,r,n,o,a,l,c;c=function(u){var _,b,x,E;return _=(u&255<<24)>>>24,b=(u&255<<16)>>>16,x=(u&255<<8)>>>8,E=u&255,[_,b,x,E].join(".")},l=function(u){var _,b,x,E,I,k;for(_=[],x=E=0;E<=3&&u.length!==0;x=++E){if(x>0){if(u[0]!==".")throw new Error("Invalid IP");u=u.substring(1)}k=t(u),I=k[0],b=k[1],u=u.substring(b),_.push(I)}if(u.length!==0)throw new Error("Invalid IP");switch(_.length){case 1:if(_[0]>4294967295)throw new Error("Invalid IP");return _[0]>>>0;case 2:if(_[0]>255||_[1]>16777215)throw new Error("Invalid IP");return(_[0]<<24|_[1])>>>0;case 3:if(_[0]>255||_[1]>255||_[2]>65535)throw new Error("Invalid IP");return(_[0]<<24|_[1]<<16|_[2])>>>0;case 4:if(_[0]>255||_[1]>255||_[2]>255||_[3]>255)throw new Error("Invalid IP");return(_[0]<<24|_[1]<<16|_[2]<<8|_[3])>>>0;default:throw new Error("Invalid IP")}},r=function(u){return u.charCodeAt(0)},n=r("0"),a=r("a"),o=r("A"),t=function(u){var _,b,x,E,I;for(E=0,_=10,b="9",x=0,u.length>1&&u[x]==="0"&&(u[x+1]==="x"||u[x+1]==="X"?(x+=2,_=16):"0"<=u[x+1]&&u[x+1]<="9"&&(x++,_=8,b="7")),I=x;x>>0;else if(_===16)if("a"<=u[x]&&u[x]<="f")E=E*_+(10+r(u[x])-a)>>>0;else if("A"<=u[x]&&u[x]<="F")E=E*_+(10+r(u[x])-o)>>>0;else break;else break;if(E>4294967295)throw new Error("too large");x++}if(x===I)throw new Error("empty octet");return[E,x]},e=function(){function u(_,b){var x,E,I;if(typeof _!="string")throw new Error("Missing `net' parameter");if(b||(I=_.split("/",2),_=I[0],b=I[1]),b||(b=32),typeof b=="string"&&b.indexOf(".")>-1){try{this.maskLong=l(b)}catch{throw new Error("Invalid mask: "+b)}for(x=E=32;E>=0;x=--E)if(this.maskLong===4294967295<<32-x>>>0){this.bitmask=x;break}}else if(b||b===0)this.bitmask=parseInt(b,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(l(_)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+_)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+b);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return u.prototype.contains=function(_){return typeof _=="string"&&(_.indexOf("/")>0||_.split(".").length!==4)&&(_=new u(_)),_ instanceof u?this.contains(_.base)&&this.contains(_.broadcast||_.last):(l(_)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},u.prototype.next=function(_){return _==null&&(_=1),new u(c(this.netLong+this.size*_),this.mask)},u.prototype.forEach=function(_){var b,x,E;for(E=l(this.first),x=l(this.last),b=0;E<=x;)_(c(E),E,b),b++,E++},u.prototype.toString=function(){return this.base+"/"+this.bitmask},u}(),Netmask_1=e}).call(commonjsGlobal$2);const word="[a-fA-F\\d:]",boundry=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))`:"",v4="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",v6segment="[a-fA-F\\d]{1,4}",v6=` + SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[t,Date.now()]}).then(o=>{o.rowCount===0&&(o=null),r(o)}).catch(o=>{n(o)})}):Promise.reject(Error("Table is not created yet"))}_delete(t){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[t]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}}var RateLimiterPostgres_1=RateLimiterPostgres$1,Record_1=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t)}get expiresAt(){return this._expiresAt}set expiresAt(t){!(t instanceof Date)&&Number.isInteger(t)&&(t=new Date(t)),this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}};const Record=Record_1,RateLimiterRes$6=RateLimiterRes_1;var MemoryStorage_1=class{constructor(){this._storage={}}incrby(t,r,n){if(this._storage[t]){const o=this._storage[t].expiresAt?this._storage[t].expiresAt.getTime()-new Date().getTime():-1;return o!==0?(this._storage[t].value=this._storage[t].value+r,new RateLimiterRes$6(0,o,this._storage[t].value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){const o=n*1e3;return this._storage[t]&&this._storage[t].timeoutId&&clearTimeout(this._storage[t].timeoutId),this._storage[t]=new Record(r,o>0?new Date(Date.now()+o):null),o>0&&(this._storage[t].timeoutId=setTimeout(()=>{delete this._storage[t]},o),this._storage[t].timeoutId.unref&&this._storage[t].timeoutId.unref()),new RateLimiterRes$6(0,o===0?-1:o,this._storage[t].value,!0)}get(t){if(this._storage[t]){const r=this._storage[t].expiresAt?this._storage[t].expiresAt.getTime()-new Date().getTime():-1;return new RateLimiterRes$6(0,r,this._storage[t].value,!1)}return null}delete(t){return this._storage[t]?(this._storage[t].timeoutId&&clearTimeout(this._storage[t].timeoutId),delete this._storage[t],!0):!1}};const RateLimiterAbstract$2=RateLimiterAbstract_1,MemoryStorage=MemoryStorage_1,RateLimiterRes$5=RateLimiterRes_1;class RateLimiterMemory$2 extends RateLimiterAbstract$2{constructor(t={}){super(t),this._memoryStorage=new MemoryStorage}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=this.getKey(t),c=this._getKeySecDuration(n);let u=this._memoryStorage.incrby(l,r,c);if(u.remainingPoints=Math.max(this.points-u.consumedPoints,0),u.consumedPoints>this.points)this.blockDuration>0&&u.consumedPoints<=this.points+r&&(u=this._memoryStorage.set(l,u.consumedPoints,this.blockDuration)),a(u);else if(this.execEvenly&&u.msBeforeNext>0&&!u.isFirstInDuration){let _=Math.ceil(u.msBeforeNext/(u.remainingPoints+2));_{const l=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,r,l);c.remainingPoints=Math.max(this.points-c.consumedPoints,0),a(c)})}reward(t,r=1,n={}){const o=this.getKey(t);return new Promise(a=>{const l=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,-r,l);c.remainingPoints=Math.max(this.points-c.consumedPoints,0),a(c)})}block(t,r){const n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new RateLimiterRes$5(0,n===0?-1:n,o))}set(t,r,n){const o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new RateLimiterRes$5(0,o===0?-1:o,r))}get(t){const r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}}var RateLimiterMemory_1=RateLimiterMemory$2;const cluster=require$$6,crypto$1=require$$6,RateLimiterAbstract$1=RateLimiterAbstract_1,RateLimiterMemory$1=RateLimiterMemory_1,RateLimiterRes$4=RateLimiterRes_1,channel="rate_limiter_flexible";let masterInstance=null;const masterSendToWorker=function(e,t,r,n){let o;n===null||n===!0||n===!1?o=n:o={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},e.send({channel,keyPrefix:t.keyPrefix,promiseId:t.promiseId,type:r,data:o})},workerWaitInit=function(e){setTimeout(()=>{this._initiated?process.send(e):typeof this._promises[e.promiseId]<"u"&&workerWaitInit.call(this,e)},30)},workerSendToMaster=function(e,t,r,n,o){const a={channel,keyPrefix:this.keyPrefix,func:e,promiseId:t,data:{key:r,arg:n,opts:o}};this._initiated?process.send(a):workerWaitInit.call(this,a)},masterProcessMsg=function(e,t){if(!t||t.channel!==channel||typeof this._rateLimiters[t.keyPrefix]>"u")return!1;let r;switch(t.func){case"consume":r=this._rateLimiters[t.keyPrefix].consume(t.data.key,t.data.arg,t.data.opts);break;case"penalty":r=this._rateLimiters[t.keyPrefix].penalty(t.data.key,t.data.arg,t.data.opts);break;case"reward":r=this._rateLimiters[t.keyPrefix].reward(t.data.key,t.data.arg,t.data.opts);break;case"block":r=this._rateLimiters[t.keyPrefix].block(t.data.key,t.data.arg,t.data.opts);break;case"get":r=this._rateLimiters[t.keyPrefix].get(t.data.key,t.data.opts);break;case"delete":r=this._rateLimiters[t.keyPrefix].delete(t.data.key,t.data.opts);break;default:return!1}r&&r.then(n=>{masterSendToWorker(e,t,"resolve",n)}).catch(n=>{masterSendToWorker(e,t,"reject",n)})},workerProcessMsg=function(e){if(!e||e.channel!==channel||e.keyPrefix!==this.keyPrefix)return!1;if(this._promises[e.promiseId]){clearTimeout(this._promises[e.promiseId].timeoutId);let t;switch(e.data===null||e.data===!0||e.data===!1?t=e.data:t=new RateLimiterRes$4(e.data.remainingPoints,e.data.msBeforeNext,e.data.consumedPoints,e.data.isFirstInDuration),e.type){case"resolve":this._promises[e.promiseId].resolve(t);break;case"reject":this._promises[e.promiseId].reject(t);break;default:throw new Error(`RateLimiterCluster: no such message type '${e.type}'`)}delete this._promises[e.promiseId]}},getOpts=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},savePromise=function(e,t){const r=process.hrtime();let n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=crypto$1.randomBytes(12).toString("base64")),this._promises[n]={resolve:e,reject:t,timeoutId:setTimeout(()=>{delete this._promises[n],t(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n};class RateLimiterClusterMaster$1{constructor(){if(masterInstance)return masterInstance;this._rateLimiters={},cluster.setMaxListeners(0),cluster.on("message",(t,r)=>{r&&r.channel===channel&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new RateLimiterMemory$1(r.opts)),t.send({channel,type:"init",keyPrefix:r.opts.keyPrefix})):masterProcessMsg.call(this,t,r)}),masterInstance=this}}class RateLimiterClusterMasterPM2$1{constructor(t){if(masterInstance)return masterInstance;this._rateLimiters={},t.launchBus((r,n)=>{n.on("process:msg",o=>{const a=o.raw;if(a&&a.channel===channel&&a.type==="init")typeof this._rateLimiters[a.opts.keyPrefix]>"u"&&(this._rateLimiters[a.opts.keyPrefix]=new RateLimiterMemory$1(a.opts)),t.sendDataToProcessId(o.process.pm_id,{data:{},topic:channel,channel,type:"init",keyPrefix:a.opts.keyPrefix},(l,c)=>{l&&console.log(l,c)});else{const l={send:c=>{const u=c;u.topic=channel,typeof u.data>"u"&&(u.data={}),t.sendDataToProcessId(o.process.pm_id,u,(_,b)=>{_&&console.log(_,b)})}};masterProcessMsg.call(this,l,a)}})}),masterInstance=this}}class RateLimiterClusterWorker extends RateLimiterAbstract$1{get timeoutMs(){return this._timeoutMs}set timeoutMs(t){this._timeoutMs=typeof t>"u"?5e3:Math.abs(parseInt(t))}constructor(t={}){super(t),process.setMaxListeners(0),this.timeoutMs=t.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===channel&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:workerProcessMsg.call(this,r)}),process.send({channel,type:"init",opts:getOpts.call(this)}),this._promises={}}consume(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"consume",l,t,r,n)})}penalty(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"penalty",l,t,r,n)})}reward(t,r=1,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"reward",l,t,r,n)})}block(t,r,n={}){return new Promise((o,a)=>{const l=savePromise.call(this,o,a);workerSendToMaster.call(this,"block",l,t,r,n)})}get(t,r={}){return new Promise((n,o)=>{const a=savePromise.call(this,n,o);workerSendToMaster.call(this,"get",a,t,r)})}delete(t,r={}){return new Promise((n,o)=>{const a=savePromise.call(this,n,o);workerSendToMaster.call(this,"delete",a,t,r)})}}var RateLimiterCluster$1={RateLimiterClusterMaster:RateLimiterClusterMaster$1,RateLimiterClusterMasterPM2:RateLimiterClusterMasterPM2$1,RateLimiterCluster:RateLimiterClusterWorker};const RateLimiterStoreAbstract=RateLimiterStoreAbstract_1,RateLimiterRes$3=RateLimiterRes_1;class RateLimiterMemcache$1 extends RateLimiterStoreAbstract{constructor(t){super(t),this.client=t.storeClient}_getRateLimiterRes(t,r,n){const o=new RateLimiterRes$3;return o.consumedPoints=parseInt(n.consumedPoints),o.isFirstInDuration=n.consumedPoints===r,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n.msBeforeNext,o}_upsert(t,r,n,o=!1,a={}){return new Promise((l,c)=>{const u=Date.now(),_=Math.floor(n/1e3);o?this.client.set(t,r,_,b=>{b?c(b):this.client.set(`${t}_expire`,_>0?u+_*1e3:-1,_,()=>{const x={consumedPoints:r,msBeforeNext:_>0?_*1e3:-1};l(x)})}):this.client.incr(t,r,(b,x)=>{b||x===!1?this.client.add(t,r,_,(E,I)=>{if(E||!I)if(typeof a.attemptNumber>"u"||a.attemptNumber<3){const k=Object.assign({},a);k.attemptNumber=k.attemptNumber?k.attemptNumber+1:1,this._upsert(t,r,n,o,k).then(T=>l(T)).catch(T=>c(T))}else c(new Error("Can not add key"));else this.client.add(`${t}_expire`,_>0?u+_*1e3:-1,_,()=>{const k={consumedPoints:r,msBeforeNext:_>0?_*1e3:-1};l(k)})}):this.client.get(`${t}_expire`,(E,I)=>{if(E)c(E);else{const k=I===!1?0:I,T={consumedPoints:x,msBeforeNext:k>=0?Math.max(k-u,0):-1};l(T)}})})})}_get(t){return new Promise((r,n)=>{const o=Date.now();this.client.get(t,(a,l)=>{l?this.client.get(`${t}_expire`,(c,u)=>{if(c)n(c);else{const _=u===!1?0:u,b={consumedPoints:l,msBeforeNext:_>=0?Math.max(_-o,0):-1};r(b)}}):r(null)})})}_delete(t){return new Promise((r,n)=>{this.client.del(t,(o,a)=>{o?n(o):a===!1?r(a):this.client.del(`${t}_expire`,l=>{l?n(l):r(a)})})})}}var RateLimiterMemcache_1=RateLimiterMemcache$1;const RateLimiterRes$2=RateLimiterRes_1;var RLWrapperBlackAndWhite_1=class{constructor(t={}){this.limiter=t.limiter,this.blackList=t.blackList,this.whiteList=t.whiteList,this.isBlackListed=t.isBlackListed,this.isWhiteListed=t.isWhiteListed,this.runActionAnyway=t.runActionAnyway}get limiter(){return this._limiter}set limiter(t){if(typeof t>"u")throw new Error("limiter is not set");this._limiter=t}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(t){this._runActionAnyway=typeof t>"u"?!1:t}get blackList(){return this._blackList}set blackList(t){this._blackList=Array.isArray(t)?t:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(t){if(typeof t>"u"&&(t=()=>!1),typeof t!="function")throw new Error("isBlackListed must be function");this._isBlackListed=t}get whiteList(){return this._whiteList}set whiteList(t){this._whiteList=Array.isArray(t)?t:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(t){if(typeof t>"u"&&(t=()=>!1),typeof t!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=t}isBlackListedSomewhere(t){return this.blackList.indexOf(t)>=0||this.isBlackListed(t)}isWhiteListedSomewhere(t){return this.whiteList.indexOf(t)>=0||this.isWhiteListed(t)}getBlackRes(){return new RateLimiterRes$2(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new RateLimiterRes$2(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(t,r=1){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(t,r):(this.runActionAnyway&&this.limiter.consume(t,r).catch(()=>{}),n)}block(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(t,r):(this.runActionAnyway&&this.limiter.block(t,r).catch(()=>{}),n)}penalty(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(t,r):(this.runActionAnyway&&this.limiter.penalty(t,r).catch(()=>{}),n)}reward(t,r){let n;return this.isWhiteListedSomewhere(t)?n=this.resolveWhite():this.isBlackListedSomewhere(t)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(t,r):(this.runActionAnyway&&this.limiter.reward(t,r).catch(()=>{}),n)}get(t){let r;return this.isWhiteListedSomewhere(t)?r=this.resolveWhite():this.isBlackListedSomewhere(t)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(t):r}delete(t){return this.limiter.delete(t)}};const RateLimiterAbstract=RateLimiterAbstract_1;var RateLimiterUnion_1=class{constructor(...t){if(t.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");t.forEach(r=>{if(!(r instanceof RateLimiterAbstract))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=t}consume(t,r=1){return new Promise((n,o)=>{const a=[];this._limiters.forEach(l=>{a.push(l.consume(t,r).catch(c=>({rejected:!0,rej:c})))}),Promise.all(a).then(l=>{const c={};let u=!1;l.forEach(_=>{_.rejected===!0&&(u=!0)});for(let _=0;_t!==null?t.remainingPoints:this._limiterFlexible.points)}removeTokens(t){const r=this;return new Promise((n,o)=>{if(t>r._limiterFlexible.points){o(new RateLimiterQueueError(`Requested tokens ${t} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,o,t):r._limiterFlexible.consume(r._key,t).then(a=>{n(a.remainingPoints)}).catch(a=>{a instanceof Error?o(a):(r._queueRequest.call(r,n,o,t),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),a.msBeforeNext)))})})}_queueRequest(t,r,n){const o=this;o._queue.length{r.resolve(n.remainingPoints),t._processFIFO.call(t)}).catch(n=>{n instanceof Error?(r.reject(n),t._processFIFO.call(t)):(t._queue.unshift(r),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),n.msBeforeNext)))})}}const RateLimiterRes$1=RateLimiterRes_1;var BurstyRateLimiter_1=class{constructor(t,r){this._rateLimiter=t,this._burstLimiter=r}_combineRes(t,r){return t?new RateLimiterRes$1(t.remainingPoints,Math.min(t.msBeforeNext,r?r.msBeforeNext:0),t.consumedPoints,t.isFirstInDuration):null}consume(t,r=1,n={}){return this._rateLimiter.consume(t,r,n).catch(o=>o instanceof RateLimiterRes$1?this._burstLimiter.consume(t,r,n).then(a=>Promise.resolve(this._combineRes(o,a))).catch(a=>a instanceof RateLimiterRes$1?Promise.reject(this._combineRes(o,a)):Promise.reject(a)):Promise.reject(o))}get(t){return Promise.all([this._rateLimiter.get(t),this._burstLimiter.get(t)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}};const RateLimiterRedis=RateLimiterRedis_1,RateLimiterMongo=RateLimiterMongo_1,RateLimiterMySQL=RateLimiterMySQL_1,RateLimiterPostgres=RateLimiterPostgres_1,{RateLimiterClusterMaster,RateLimiterClusterMasterPM2,RateLimiterCluster}=RateLimiterCluster$1,RateLimiterMemory=RateLimiterMemory_1,RateLimiterMemcache=RateLimiterMemcache_1,RLWrapperBlackAndWhite=RLWrapperBlackAndWhite_1,RateLimiterUnion=RateLimiterUnion_1,RateLimiterQueue=RateLimiterQueue_1,BurstyRateLimiter=BurstyRateLimiter_1,RateLimiterRes=RateLimiterRes_1;var rateLimiterFlexible={RateLimiterRedis,RateLimiterMongo,RateLimiterMySQL,RateLimiterPostgres,RateLimiterMemory,RateLimiterMemcache,RateLimiterClusterMaster,RateLimiterClusterMasterPM2,RateLimiterCluster,RLWrapperBlackAndWhite,RateLimiterUnion,RateLimiterQueue,BurstyRateLimiter,RateLimiterRes},MessageTypes;(function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(MessageTypes||(MessageTypes={}));const MessageTypeNames=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),InitiatorMessageTypes=Object.freeze({NEW_STREAM:MessageTypes.NEW_STREAM,MESSAGE:MessageTypes.MESSAGE_INITIATOR,CLOSE:MessageTypes.CLOSE_INITIATOR,RESET:MessageTypes.RESET_INITIATOR}),ReceiverMessageTypes=Object.freeze({MESSAGE:MessageTypes.MESSAGE_RECEIVER,CLOSE:MessageTypes.CLOSE_RECEIVER,RESET:MessageTypes.RESET_RECEIVER}),MAX_MSG_SIZE=1<<20,MAX_MSG_QUEUE_SIZE=4<<20;class Decoder$1{constructor(t=MAX_MSG_SIZE,r=MAX_MSG_QUEUE_SIZE){Ke(this,"_buffer");Ke(this,"_headerInfo");Ke(this,"_maxMessageSize");Ke(this,"_maxUnprocessedMessageQueueSize");this._buffer=new Uint8ArrayList,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=r}write(t){if(t==null||t.length===0)return[];if(this._buffer.append(t),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const r=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(_){if(_.code==="ERR_MSG_TOO_BIG")throw _;break}const{id:n,type:o,length:a,offset:l}=this._headerInfo;if(this._buffer.length-lthis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:r>>3,type:l,offset:n+a,length:o}}}const MSB$2=128,REST$2=127;function readVarInt(e,t=0){let r=0,n=0,o=t,a;const l=e.length;do{if(o>=l||n>49)throw t=0,new RangeError("Could not decode varint");a=e.get(o++),r+=n<28?(a&REST$2)<=MSB$2);return t=o-t,{value:r,offset:t}}function isAsyncIterable$7(e){return e[Symbol.asyncIterator]!=null}const DEFAULT_BATCH_SIZE=1024*1024,DEFAULT_SERIALIZE=(e,t)=>{t.append(e)};function batchedBytes(e,t){return isAsyncIterable$7(e)?async function*(){let r=new Uint8ArrayList,n=!1,o=pDefer(),a=Number(t?.size??DEFAULT_BATCH_SIZE);if((isNaN(a)||a===0||a<0)&&(a=DEFAULT_BATCH_SIZE),a!==Math.round(a))throw new Error("Batch size must be an integer");const l=t?.yieldAfter??0,c=t?.serialize??DEFAULT_SERIALIZE;for(Promise.resolve().then(async()=>{try{let u;for await(const _ of e){if(c(_,r),r.byteLength>=a){clearTimeout(u),o.resolve();continue}u=setTimeout(()=>{o.resolve()},l)}clearTimeout(u),o.resolve()}catch(u){o.reject(u)}finally{n=!0}});!n;)if(await o.promise,o=pDefer(),r.byteLength>0){const u=r;r=new Uint8ArrayList,yield u.subarray()}}():function*(){const r=new Uint8ArrayList;let n=Number(t?.size??DEFAULT_BATCH_SIZE);if((isNaN(n)||n===0||n<0)&&(n=DEFAULT_BATCH_SIZE),n!==Math.round(n))throw new Error("Batch size must be an integer");const o=t?.serialize??DEFAULT_SERIALIZE;for(const a of e)o(a,r),r.byteLength>=n&&(yield r.subarray(0,n),r.consume(n));r.byteLength>0&&(yield r.subarray())}()}function allocUnsafe(e){return new Uint8Array(e)}const POOL_SIZE=10*1024;class Encoder$1{constructor(){Ke(this,"_pool");Ke(this,"_poolOffset");this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0}write(t,r){const n=this._pool;let o=this._poolOffset;encode$d(t.id<<3|t.type,n,o),o+=encodingLength$2(t.id<<3|t.type),(t.type===MessageTypes.NEW_STREAM||t.type===MessageTypes.MESSAGE_INITIATOR||t.type===MessageTypes.MESSAGE_RECEIVER)&&t.data!=null?(encode$d(t.data.length,n,o),o+=encodingLength$2(t.data.length)):(encode$d(0,n,o),o+=encodingLength$2(0));const a=n.subarray(this._poolOffset,o);POOL_SIZE-o<100?(this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0):this._poolOffset=o,r.append(a),(t.type===MessageTypes.NEW_STREAM||t.type===MessageTypes.MESSAGE_INITIATOR||t.type===MessageTypes.MESSAGE_RECEIVER)&&t.data!=null&&r.append(t.data)}}const encoder=new Encoder$1;async function*encode$7(e,t=0){if(t==null||t===0){for await(const r of e){const n=new Uint8ArrayList;for(const o of r)encoder.write(o,n);yield n.subarray()}return}yield*batchedBytes(e,{size:t,serialize:(r,n)=>{for(const o of r)encoder.write(o,n)}})}const ERR_STREAM_RESET="ERR_STREAM_RESET",ERR_SINK_INVALID_STATE="ERR_SINK_INVALID_STATE";function isPromise(e){return e!=null&&typeof e.then=="function"}class AbstractStream{constructor(t){Ke(this,"id");Ke(this,"direction");Ke(this,"timeline");Ke(this,"protocol");Ke(this,"metadata");Ke(this,"source");Ke(this,"status");Ke(this,"readStatus");Ke(this,"writeStatus");Ke(this,"sinkController");Ke(this,"sinkEnd");Ke(this,"endErr");Ke(this,"streamSource");Ke(this,"onEnd");Ke(this,"onCloseRead");Ke(this,"onCloseWrite");Ke(this,"onReset");Ke(this,"onAbort");Ke(this,"log");this.sinkController=new AbortController,this.sinkEnd=pDefer(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=pushable({onEnd:r=>{r!=null?this.log.trace("source ended with error",r):this.log.trace("source ended"),this.readStatus="closed",this.onSourceEnd(r)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new CodeError(`writable end state is "${this.writeStatus}" not "ready"`,ERR_SINK_INVALID_STATE);try{this.writeStatus="writing";const r={signal:this.sinkController.signal};if(this.direction==="outbound"){const n=this.sendNewStream(r);isPromise(n)&&await n}t=abortableSource(t,this.sinkController.signal,{returnOnAbort:!0}),this.log.trace("sink reading from source");for await(let n of t){n=n instanceof Uint8Array?new Uint8ArrayList(n):n;const o=this.sendData(n,r);isPromise(o)&&await o}this.log.trace("sink finished reading from source"),this.writeStatus="done",this.log.trace("sink calling closeWrite"),await this.closeWrite(r),this.onSinkEnd()}catch(r){throw this.log.trace("sink ended with error, calling abort with error",r),this.abort(r),r}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(t),this.closeWrite(t)]),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const r=this.readStatus;this.readStatus="closing",r==="ready"&&(this.log.trace("ending internal source queue"),this.streamSource.end()),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),this.log.trace("closed readable end of stream")}async closeWrite(t={}){if(this.writeStatus==="closing"||this.writeStatus==="closed")return;this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus);const r=this.writeStatus;this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await this.sink([])),this.writeStatus="closing",r==="writing"&&await new Promise((n,o)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),this.sinkEnd.promise.then(n,o)})}),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeWrite==null&&(this.log.trace("send close write to remote"),await this.sendCloseWrite(t)),this.writeStatus="closed",this.log.trace("closed writable end of stream")}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");const r=this.sendReset();isPromise(r)&&r.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;const t=new CodeError("stream reset",ERR_STREAM_RESET);this.status="reset",this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("muxer destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}}class MplexStream extends AbstractStream{constructor(r){super(r);Ke(this,"name");Ke(this,"streamId");Ke(this,"send");Ke(this,"types");Ke(this,"maxDataSize");this.types=r.direction==="outbound"?InitiatorMessageTypes:ReceiverMessageTypes,this.send=r.send,this.name=r.name,this.streamId=r.streamId,this.maxDataSize=r.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:InitiatorMessageTypes.NEW_STREAM,data:new Uint8ArrayList(fromString$1(this.name))})}async sendData(r){for(r=r.sublist();r.byteLength>0;){const n=Math.min(r.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:r.sublist(0,n)}),r.consume(n)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function createStream$1(e){const{id:t,name:r,send:n,onEnd:o,type:a="initiator",maxMsgSize:l=MAX_MSG_SIZE}=e;return new MplexStream({id:a==="initiator"?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:a==="initiator"?"outbound":"inbound",maxDataSize:l,onEnd:o,send:n,log:logger(`libp2p:mplex:stream:${a}:${t}`)})}const log$w=logger("libp2p:mplex"),MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAM_BUFFER_SIZE=1024*1024*4,DISCONNECT_THRESHOLD=5,CLOSE_TIMEOUT$2=500;function printMessage(e){const t={...e,type:`${MessageTypeNames[e.type]} (${e.type})`};return e.type===MessageTypes.NEW_STREAM&&(t.data=toString$5(e.data instanceof Uint8Array?e.data:e.data.subarray())),(e.type===MessageTypes.MESSAGE_INITIATOR||e.type===MessageTypes.MESSAGE_RECEIVER)&&(t.data=toString$5(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class MplexStreamMuxer{constructor(t){Ke(this,"protocol","/mplex/6.7.0");Ke(this,"sink");Ke(this,"source");Ke(this,"_streamId");Ke(this,"_streams");Ke(this,"_init");Ke(this,"_source");Ke(this,"closeController");Ke(this,"rateLimiter");Ke(this,"closeTimeout");t=t??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??CLOSE_TIMEOUT$2,this.sink=this._createSink(),this._source=pushableV({objectMode:!0,onEnd:()=>{for(const r of this._streams.initiators.values())r.destroy();for(const r of this._streams.receivers.values())r.destroy()}}),this.source=pipe(this._source,r=>encode$7(r,this._init.minSendBytes)),this.closeController=new AbortController,this.rateLimiter=new rateLimiterFlexible.RateLimiterMemory({points:t.disconnectThreshold??DISCONNECT_THRESHOLD,duration:1})}get streams(){const t=[];for(const r of this._streams.initiators.values())t.push(r);for(const r of this._streams.receivers.values())t.push(r);return t}newStream(t){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const r=this._streamId++;t=t==null?r.toString():t.toString();const n=this._streams.initiators;return this._newStream({id:r,name:t,type:"initiator",registry:n})}async close(t){if(this.closeController.signal.aborted)return;const r=t?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:r}))),this._source.end(),await this._source.onEmpty({signal:r}),this.closeController.abort()}catch(n){this.abort(n)}}abort(t){this.closeController.signal.aborted||(this.streams.forEach(r=>{r.abort(t)}),this.closeController.abort(t))}_newReceiverStream(t){const{id:r,name:n}=t,o=this._streams.receivers;return this._newStream({id:r,name:n,type:"receiver",registry:o})}_newStream(t){const{id:r,name:n,type:o,registry:a}=t;if(log$w("new %s stream %s",o,r),o==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION))throw new CodeError("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(a.has(r))throw new Error(`${o} stream ${r} already exists!`);const u=createStream$1({id:r,name:n,send:async _=>{log$w.enabled&&log$w.trace("%s stream %s send",o,r,printMessage(_)),this._source.push(_)},type:o,onEnd:()=>{log$w("%s stream with id %s and protocol %s ended",o,r,u.protocol),a.delete(r),this._init.onStreamEnd!=null&&this._init.onStreamEnd(u)},maxMsgSize:this._init.maxMsgSize});return a.set(r,u),u}_createSink(){return async r=>{try{r=abortableSource(r,this.closeController.signal,{returnOnAbort:!0});const n=new Decoder$1(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const o of r)for(const a of n.write(o))await this._handleIncoming(a);this._source.end()}catch(n){log$w("error in sink",n),this._source.end(n)}}}async _handleIncoming(t){const{id:r,type:n}=t;if(log$w.enabled&&log$w.trace("incoming message",printMessage(t)),t.type===MessageTypes.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)){log$w("too many inbound streams open"),this._source.push({id:r,type:MessageTypes.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{log$w("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}const c=this._newReceiverStream({id:r,name:toString$5(t.data instanceof Uint8Array?t.data:t.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(c);return}const a=((n&1)===1?this._streams.initiators:this._streams.receivers).get(r);if(a==null){log$w("missing stream %s for message type %s",r,MessageTypeNames[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{log$w("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}const l=this._init.maxStreamBufferSize??MAX_STREAM_BUFFER_SIZE;try{switch(n){case MessageTypes.MESSAGE_INITIATOR:case MessageTypes.MESSAGE_RECEIVER:if(a.sourceReadableLength()>l)throw this._source.push({id:t.id,type:n===MessageTypes.MESSAGE_INITIATOR?MessageTypes.RESET_RECEIVER:MessageTypes.RESET_INITIATOR}),new CodeError("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");a.sourcePush(t.data);break;case MessageTypes.CLOSE_INITIATOR:case MessageTypes.CLOSE_RECEIVER:a.remoteCloseWrite();break;case MessageTypes.RESET_INITIATOR:case MessageTypes.RESET_RECEIVER:a.reset();break;default:log$w("unknown message type %s",n)}}catch(c){log$w.error("error while processing message",c),a.abort(c)}}}class Mplex{constructor(t={}){Ke(this,"protocol","/mplex/6.7.0");Ke(this,"_init");this._init=t}createStreamMuxer(t={}){return new MplexStreamMuxer({...t,...this._init})}}function mplex(e={}){return()=>new Mplex(e)}const symbol$1=Symbol.for("@libp2p/transport");var FaultTolerance;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(FaultTolerance||(FaultTolerance={}));var codes$6;(function(e){e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",e.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",e.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(codes$6||(codes$6={}));var __spreadArray=globalThis&&globalThis.__spreadArray||function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,a;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new ReactNativeInfo:typeof navigator<"u"?parseUserAgent(navigator.userAgent):getNodeVersion()}function matchUserAgent(e){return e!==""&&userAgentRules.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var a=o.exec(e);return!!a&&[n,a]},!1)}function parseUserAgent(e){var t=matchUserAgent(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new BotInfo;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length{},log$v=logger("libp2p:webrtc:connection");class WebRTCMultiaddrConnection{constructor(t){Ke(this,"peerConnection");Ke(this,"remoteAddr");Ke(this,"timeline");Ke(this,"metrics");Ke(this,"source",nopSource());Ke(this,"sink",nopSink);this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection,this.peerConnection.onconnectionstatechange=()=>{(this.peerConnection.connectionState==="closed"||this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed")&&(this.timeline.close=Date.now())}}async close(t){log$v.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){log$v.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}}const RTCPeerConnection=globalThis.RTCPeerConnection,RTCSessionDescription=globalThis.RTCSessionDescription,RTCIceCandidate=globalThis.RTCIceCandidate;function pbStream(e,t){const r=lpStream(e,t),n={read:async(o,a)=>{const l=await r.read(a);return o.decode(l)},write:async(o,a,l)=>{await r.write(a.encode(o),l)},pb:o=>({read:async a=>n.read(o,a),write:async(a,l)=>n.write(a,o,l),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}class TimeoutError extends Error{constructor(t){super(t),this.name="TimeoutError"}}class AbortError extends Error{constructor(t){super(),this.name="AbortError",this.message=t}}const getDOMException=e=>globalThis.DOMException===void 0?new AbortError(e):new DOMException(e),getAbortedReason=e=>{const t=e.reason===void 0?getDOMException("This operation was aborted."):e.reason;return t instanceof Error?t:getDOMException(t)};function pTimeout(e,t){const{milliseconds:r,fallback:n,message:o,customTimers:a={setTimeout,clearTimeout}}=t;let l;const u=new Promise((_,b)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:E}=t;E.aborted&&b(getAbortedReason(E)),E.addEventListener("abort",()=>{b(getAbortedReason(E))})}if(r===Number.POSITIVE_INFINITY){e.then(_,b);return}const x=new TimeoutError;l=a.setTimeout.call(void 0,()=>{if(n){try{_(n())}catch(E){b(E)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?_():o instanceof Error?b(o):(x.message=o??`Promise timed out after ${r} milliseconds`,b(x))},r),(async()=>{try{_(await e)}catch(E){b(E)}})()}).finally(()=>{u.clear()});return u.clear=()=>{a.clearTimeout.call(void 0,l),l=void 0},u}const normalizeEmitter=e=>{const t=e.on||e.addListener||e.addEventListener,r=e.off||e.removeListener||e.removeEventListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function pEventMultiple(e,t,r){let n;const o=new Promise((a,l)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const c=[t].flat(),u=[],{addListener:_,removeListener:b}=normalizeEmitter(e),x=(...I)=>{const k=r.multiArgs?I:I[0];r.filter&&!r.filter(k)||(u.push(k),r.count===u.length&&(n(),a(u)))},E=I=>{n(),l(I)};n=()=>{for(const I of c)b(I,x);for(const I of r.rejectionEvents)b(I,E)};for(const I of c)_(I,x);for(const I of r.rejectionEvents)_(I,E);r.signal&&r.signal.addEventListener("abort",()=>{E(r.signal.reason)},{once:!0}),r.resolveImmediately&&a(u)});if(o.cancel=n,typeof r.timeout=="number"){const a=pTimeout(o,{milliseconds:r.timeout});return a.cancel=n,a}return o}function pEvent(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=pEventMultiple(e,t,r),o=n.then(a=>a[0]);return o.cancel=n.cancel,o}var Message$1;(function(e){(function(n){n.FIN="FIN",n.STOP_SENDING="STOP_SENDING",n.RESET="RESET"})(e.Flag||(e.Flag={}));let t;(function(n){n[n.FIN=0]="FIN",n[n.STOP_SENDING=1]="STOP_SENDING",n[n.RESET=2]="RESET"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Flag||(e.Flag={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.flag!=null&&(o.uint32(8),e.Flag.codec().encode(n.flag,o)),n.message!=null&&(o.uint32(18),o.bytes(n.message)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.flag=e.Flag.codec().decode(n);break;case 2:a.message=n.bytes();break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(Message$1||(Message$1={}));const MAX_MESSAGE_SIZE=16*1024,MAX_BUFFERED_AMOUNT=16*1024*1024,BUFFERED_AMOUNT_LOW_TIMEOUT=30*1e3,PROTOBUF_OVERHEAD=5,VARINT_LENGTH=2;class WebRTCStream extends AbstractStream{constructor(r){super(r);Ke(this,"channel");Ke(this,"dataChannelOptions");Ke(this,"incomingData");Ke(this,"messageQueue");Ke(this,"maxDataSize");switch(this.channel=r.channel,this.channel.binaryType="arraybuffer",this.incomingData=pushable(),this.messageQueue=new Uint8ArrayList,this.dataChannelOptions={bufferedAmountLowEventTimeout:r.dataChannelOptions?.bufferedAmountLowEventTimeout??BUFFERED_AMOUNT_LOW_TIMEOUT,maxBufferedAmount:r.dataChannelOptions?.maxBufferedAmount??MAX_BUFFERED_AMOUNT,maxMessageSize:r.dataChannelOptions?.maxMessageSize??r.maxDataSize},this.maxDataSize=r.maxDataSize,this.channel.readyState){case"open":break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new CodeError("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime(),this.messageQueue!=null&&(this._sendMessage(this.messageQueue).catch(a=>{this.abort(a)}),this.messageQueue=void 0)},this.channel.onclose=o=>{this.close().catch(a=>{this.log.error("error closing stream after channel closed",a)})},this.channel.onerror=o=>{const a=o.error;this.abort(a)};const n=this;this.channel.onmessage=async o=>{const{data:a}=o;a===null||a.byteLength===0||this.incomingData.push(new Uint8Array(a,0,a.byteLength))},Promise.resolve().then(async()=>{for await(const o of decode$a(this.incomingData)){const a=n.processIncomingProtobuf(o.subarray());a!=null&&n.sourcePush(new Uint8ArrayList(a))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(r,n=!0){if(n&&this.channel.bufferedAmount>this.dataChannelOptions.maxBufferedAmount)try{await pEvent(this.channel,"bufferedamountlow",{timeout:this.dataChannelOptions.bufferedAmountLowEventTimeout})}catch(o){throw o instanceof TimeoutError?new Error("Timed out waiting for DataChannel buffer to clear"):o}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new CodeError("Invalid datachannel state - closed or closing","ERR_INVALID_STATE");if(this.channel.readyState==="open")for(const o of r)this.channel.send(o);else if(this.channel.readyState==="connecting")this.messageQueue==null&&(this.messageQueue=new Uint8ArrayList),this.messageQueue.append(r);else throw this.log.error("unknown datachannel state %s",this.channel.readyState),new CodeError("Unknown datachannel state","ERR_INVALID_STATE")}async sendData(r){for(r=r.sublist();r.byteLength>0;){const n=Math.min(r.byteLength,this.maxDataSize),o=r.subarray(0,n),a=Message$1.encode({message:o}),l=encode$c.single(a);await this._sendMessage(l),r.consume(n)}}async sendReset(){await this._sendFlag(Message$1.Flag.RESET)}async sendCloseWrite(){await this._sendFlag(Message$1.Flag.FIN)}async sendCloseRead(){await this._sendFlag(Message$1.Flag.STOP_SENDING)}processIncomingProtobuf(r){const n=Message$1.decode(r);return n.flag!==void 0&&(n.flag===Message$1.Flag.FIN&&(this.incomingData.end(),this.remoteCloseWrite()),n.flag===Message$1.Flag.RESET&&this.reset(),n.flag===Message$1.Flag.STOP_SENDING&&this.remoteCloseRead()),n.message}async _sendFlag(r){this.log.trace("Sending flag: %s",r.toString());const n=Message$1.encode({flag:r}),o=encode$c.single(n);await this._sendMessage(o,!1)}}function createStream(e){const{channel:t,direction:r,onEnd:n,dataChannelOptions:o}=e;return new WebRTCStream({id:r==="inbound"?`i${t.id}`:`r${t.id}`,direction:r,maxDataSize:(o?.maxMessageSize??MAX_MESSAGE_SIZE)-PROTOBUF_OVERHEAD-VARINT_LENGTH,dataChannelOptions:o,onEnd:n,channel:t,log:logger(`libp2p:webrtc:stream:${r}:${t.id}`)})}const PROTOCOL="/webrtc";class DataChannelMuxerFactory{constructor(t){Ke(this,"protocol");Ke(this,"peerConnection");Ke(this,"streamBuffer",[]);Ke(this,"metrics");Ke(this,"dataChannelOptions");this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??PROTOCOL,this.dataChannelOptions=t.dataChannelOptions,this.peerConnection.ondatachannel=({channel:r})=>{const n=createStream({channel:r,direction:"inbound",dataChannelOptions:t.dataChannelOptions,onEnd:()=>{this.streamBuffer=this.streamBuffer.filter(o=>o.id!==n.id)}});this.streamBuffer.push(n)}}createStreamMuxer(t){return new DataChannelMuxer({...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.streamBuffer,protocol:this.protocol})}}class DataChannelMuxer{constructor(t){Ke(this,"init");Ke(this,"streams");Ke(this,"protocol");Ke(this,"peerConnection");Ke(this,"dataChannelOptions");Ke(this,"metrics");Ke(this,"close",async()=>{});Ke(this,"abort",()=>{});Ke(this,"source",nopSource());Ke(this,"sink",nopSink);this.init=t,this.streams=t.streams,this.peerConnection=t.peerConnection,this.protocol=t.protocol??PROTOCOL,this.metrics=t.metrics,this.peerConnection.ondatachannel=({channel:n})=>{const o=createStream({channel:n,direction:"inbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(a=>a.id!==o.id),this.metrics?.increment({stream_end:!0}),t?.onStreamEnd?.(o)}});this.streams.push(o),t?.onIncomingStream!=null&&(this.metrics?.increment({incoming_stream:!0}),t.onIncomingStream(o))};const r=t?.onIncomingStream;r!=null&&this.streams.forEach(n=>{r(n)})}newStream(){const t=this.peerConnection.createDataChannel(""),r=createStream({channel:t,direction:"outbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{t.close(),this.streams=this.streams.filter(n=>n.id!==r.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(r)}});return this.streams.push(r),this.metrics?.increment({outgoing_stream:!0}),r}}var Message;(function(e){(function(n){n.SDP_OFFER="SDP_OFFER",n.SDP_ANSWER="SDP_ANSWER",n.ICE_CANDIDATE="ICE_CANDIDATE"})(e.Type||(e.Type={}));let t;(function(n){n[n.SDP_OFFER=0]="SDP_OFFER",n[n.SDP_ANSWER=1]="SDP_ANSWER",n[n.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.data!=null&&(o.uint32(18),o.string(n.data)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.data=n.string();break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(Message||(Message={}));const log$u=logger("libp2p:webrtc:peer:util"),readCandidatesUntilConnected=async(e,t,r)=>{for(;;){const n=await Promise.race([e.promise,r.read()]);if(n instanceof Object){const o=n;if(o.type!==Message.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(o.data==null||o.data===""){log$u.trace("end-of-candidates received");break}log$u.trace("received new ICE candidate: %s",o.data);try{await t.addIceCandidate(new RTCIceCandidate(JSON.parse(o.data)))}catch(a){throw log$u.error("bad candidate received: ",a),new Error("bad candidate received")}}else break}await e.promise};function resolveOnConnected(e,t){e[isFirefox?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(log$u.trace("receiver peerConnectionState state: ",e.connectionState),isFirefox?e.iceConnectionState:e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Error("RTCPeerConnection was closed"));break}}}const DEFAULT_TIMEOUT=30*1e3,log$t=logger("libp2p:webrtc:peer");async function handleIncomingStream({rtcConfiguration:e,dataChannelOptions:t,stream:r}){const n=AbortSignal.timeout(DEFAULT_TIMEOUT),o=pbStream(abortableDuplex(r,n)).pb(Message),a=new RTCPeerConnection(e);try{const l=new DataChannelMuxerFactory({peerConnection:a,dataChannelOptions:t}),c=pDefer(),u=pDefer();n.onabort=()=>{c.reject(new CodeError("Timed out while trying to connect","ERR_TIMEOUT"))},a.onicecandidate=({candidate:I})=>{u.promise.then(async()=>{await o.write({type:Message.Type.ICE_CANDIDATE,data:I!=null?JSON.stringify(I.toJSON()):""})},k=>{log$t.error("cannot set candidate since sending answer failed",k),c.reject(k)})},resolveOnConnected(a,c);const _=await o.read();if(_.type!==Message.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${_.type??"undefined"} `);const b=new RTCSessionDescription({type:"offer",sdp:_.data});await a.setRemoteDescription(b).catch(I=>{throw log$t.error("could not execute setRemoteDescription",I),new Error("Failed to set remoteDescription")});const x=await a.createAnswer().catch(I=>{throw log$t.error("could not execute createAnswer",I),u.reject(I),new Error("Failed to create answer")});await o.write({type:Message.Type.SDP_ANSWER,data:x.sdp}),await a.setLocalDescription(x).catch(I=>{throw log$t.error("could not execute setLocalDescription",I),u.reject(I),new Error("Failed to set localDescription")}),u.resolve(),await readCandidatesUntilConnected(c,a,o);const E=parseRemoteAddress(a.currentRemoteDescription?.sdp??"");return{pc:a,muxerFactory:l,remoteAddress:E}}catch(l){throw a.close(),l}}async function initiateConnection({rtcConfiguration:e,dataChannelOptions:t,signal:r,stream:n}){const o=pbStream(abortableDuplex(n,r)).pb(Message),a=new RTCPeerConnection(e);try{const l=new DataChannelMuxerFactory({peerConnection:a,dataChannelOptions:t}),c=pDefer();resolveOnConnected(a,c),r.onabort=c.reject;const u=a.createDataChannel("init");a.onicecandidate=({candidate:I})=>{o.write({type:Message.Type.ICE_CANDIDATE,data:I!=null?JSON.stringify(I.toJSON()):""}).catch(k=>{log$t.error("error sending ICE candidate",k)})};const _=await a.createOffer();await o.write({type:Message.Type.SDP_OFFER,data:_.sdp}),await a.setLocalDescription(_).catch(I=>{throw log$t.error("could not execute setLocalDescription",I),new Error("Failed to set localDescription")});const b=await o.read();if(b.type!==Message.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");const x=new RTCSessionDescription({type:"answer",sdp:b.data});await a.setRemoteDescription(x).catch(I=>{throw log$t.error("could not execute setRemoteDescription",I),new Error("Failed to set remoteDescription")}),await readCandidatesUntilConnected(c,a,o),u.close();const E=parseRemoteAddress(a.currentRemoteDescription?.sdp??"");return{pc:a,muxerFactory:l,remoteAddress:E}}catch(l){throw a.close(),l}}function parseRemoteAddress(e){const t=e.split(`\r +`).filter(n=>n.startsWith("a=candidate")).pop(),r=t?.split(" ");return t==null||r==null||r.length<5?(log$t("could not parse remote address from",t),"/webrtc"):`/dnsaddr/${r[4]}/${r[2].toLowerCase()}/${r[5]}/webrtc`}class WebRTCPeerListener extends EventEmitter$2{constructor(r){super();Ke(this,"peerId");Ke(this,"transportManager");this.peerId=r.peerId,this.transportManager=r.transportManager}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(r=>r!==this).map(r=>r.getAddrs().filter(n=>Circuit$1.matches(n)).map(n=>n.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.safeDispatchEvent("close",{})}}const log$s=logger("libp2p:webrtc:peer"),WEBRTC_TRANSPORT="/webrtc",CIRCUIT_RELAY_TRANSPORT="/p2p-circuit",SIGNALING_PROTO_ID="/webrtc-signaling/0.0.1",WEBRTC_CODE=getProtocol("webrtc").code;var tc,rc;class WebRTCTransport{constructor(t,r={}){Ke(this,"components");Ke(this,"init");Ke(this,"_started",!1);Ke(this,"metrics");Ke(this,tc,"@libp2p/webrtc");Ke(this,rc,!0);this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}isStarted(){return this._started}async start(){await this.components.registrar.handle(SIGNALING_PROTO_ID,t=>{this._onProtocol(t).catch(r=>{log$s.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(SIGNALING_PROTO_ID),this._started=!1}createListener(t){return new WebRTCPeerListener(this.components)}filter(t){return t.filter(r=>r.protoCodes().includes(WEBRTC_CODE))}async dial(t,r){log$s.trace("dialing address: ",t);const{baseAddr:n,peerId:o}=splitAddr(t);if(r.signal==null){const c=new AbortController;r.signal=c.signal}this.metrics?.dialerEvents.increment({open:!0});const a=await this.components.transportManager.dial(n,r),l=await a.newStream(SIGNALING_PROTO_ID,{...r,runOnTransientConnection:!0});try{const{pc:c,muxerFactory:u,remoteAddress:_}=await initiateConnection({stream:l,rtcConfiguration:this.init.rtcConfiguration,dataChannelOptions:this.init.dataChannel,signal:r.signal}),b=await r.upgrader.upgradeOutbound(new WebRTCMultiaddrConnection({peerConnection:c,timeline:{open:Date.now()},remoteAddr:multiaddr(_).encapsulate(`/p2p/${o.toString()}`),metrics:this.metrics?.dialerEvents}),{skipProtection:!0,skipEncryption:!0,muxerFactory:u});return await l.close(),b}catch(c){throw this.metrics?.dialerEvents.increment({error:!0}),l.abort(c),c}finally{await a.close()}}async _onProtocol({connection:t,stream:r}){try{const{pc:n,muxerFactory:o,remoteAddress:a}=await handleIncomingStream({rtcConfiguration:this.init.rtcConfiguration,connection:t,stream:r,dataChannelOptions:this.init.dataChannel});await this.components.upgrader.upgradeInbound(new WebRTCMultiaddrConnection({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:multiaddr(a).encapsulate(`/p2p/${t.remotePeer.toString()}`),metrics:this.metrics?.listenerEvents}),{skipEncryption:!0,skipProtection:!0,muxerFactory:o})}catch(n){throw r.abort(n),n}finally{await t.close()}}}tc=Symbol.toStringTag,rc=symbol$1;function splitAddr(e){const t=e.toString().split(WEBRTC_TRANSPORT+"/");if(t.length!==2)throw new CodeError("webrtc protocol was not present in multiaddr",codes$6.ERR_INVALID_MULTIADDR);if(!t[0].includes(CIRCUIT_RELAY_TRANSPORT))throw new CodeError("p2p-circuit protocol was not present in multiaddr",codes$6.ERR_INVALID_MULTIADDR);let r=multiaddr(t[0]);const o=multiaddr("/"+t[1]).getPeerId();if(o==null)throw new CodeError("destination peer id was missing",codes$6.ERR_INVALID_MULTIADDR);const a=r.protos().pop();if(a===void 0)throw new CodeError("invalid multiaddr",codes$6.ERR_INVALID_MULTIADDR);return a.name!=="p2p"&&(r=r.encapsulate(`/p2p/${o}`)),{baseAddr:r,peerId:peerIdFromString(o)}}var src$2={exports:{}};function base$2(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,N=new Uint8Array(D);O!==$;){for(var H=I[O],ie=0,ue=D-1;(H!==0||ie>>0,N[ue]=H%l>>>0,H=H/l>>>0;if(H!==0)throw new Error("Non-zero carry");T=ie,O++}for(var de=D-T;de!==D&&N[de]===0;)de++;for(var le=c.repeat(k);de>>0,D=new Uint8Array($);I[k];){var N=t[I.charCodeAt(k)];if(N===255)return;for(var H=0,ie=$-1;(N!==0||H>>0,D[ie]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");O=H,k++}if(I[k]!==" "){for(var ue=$-O;ue!==$&&D[ue]===0;)ue++;for(var de=new Uint8Array(T+($-ue)),le=T;ue!==$;)de[le++]=D[ue++];return de}}}function E(I){var k=x(I);if(k)return k;throw new Error("Non-base"+l+" character")}return{encode:b,decodeUnsafe:x,decode:E}}var src$1=base$2;const textDecoder=new TextDecoder,decodeText$1=e=>textDecoder.decode(e),textEncoder=new TextEncoder,encodeText$2=e=>textEncoder.encode(e);function concat(e,t){const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}var util={decodeText:decodeText$1,encodeText:encodeText$2,concat};const{encodeText:encodeText$1}=util;class Base$1{constructor(t,r,n,o){this.name=t,this.code=r,this.codeBuf=encodeText$1(this.code),this.alphabet=o,this.codec=n(o)}encode(t){return this.codec.encode(t)}decode(t){for(const r of t)if(this.alphabet&&this.alphabet.indexOf(r)<0)throw new Error(`invalid character '${r}' in '${t}'`);return this.codec.decode(t)}}var base$1=Base$1;const decode$4=(e,t,r)=>{const n={};for(let _=0;_=8&&(l-=8,a[u++]=255&c>>l)}if(l>=r||255&c<<8-l)throw new SyntaxError("Unexpected end of data");return a},encode$6=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<t=>({encode(r){return encode$6(r,t,e)},decode(r){return decode$4(r,t,e)}});var rfc4648_1={rfc4648:rfc4648$2};const baseX$1=src$1,Base=base$1,{rfc4648:rfc4648$1}=rfc4648_1,{decodeText,encodeText}=util,identity$3=()=>({encode:decodeText,decode:encodeText}),constants$1=[["identity","\0",identity$3,""],["base2","0",rfc4648$1(1),"01"],["base8","7",rfc4648$1(3),"01234567"],["base10","9",baseX$1,"0123456789"],["base16","f",rfc4648$1(4),"0123456789abcdef"],["base16upper","F",rfc4648$1(4),"0123456789ABCDEF"],["base32hex","v",rfc4648$1(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",rfc4648$1(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",rfc4648$1(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",rfc4648$1(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",rfc4648$1(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",rfc4648$1(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",rfc4648$1(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",rfc4648$1(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",rfc4648$1(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",baseX$1,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",baseX$1,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",baseX$1,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",baseX$1,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",rfc4648$1(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],names$2=constants$1.reduce((e,t)=>(e[t[0]]=new Base(t[0],t[1],t[2],t[3]),e),{}),codes$5=constants$1.reduce((e,t)=>(e[t[1]]=names$2[t[0]],e),{});var constants_1={names:names$2,codes:codes$5};(function(e,t){const r=constants_1,{encodeText:n,decodeText:o,concat:a}=util;function l(T,O){if(!O)throw new Error("requires an encoded Uint8Array");const{name:$,codeBuf:D}=x(T);return b($,O),a([D,O],D.length+O.length)}function c(T,O){const $=x(T),D=n($.encode(O));return a([$.codeBuf,D],$.codeBuf.length+D.length)}function u(T){T instanceof Uint8Array&&(T=o(T));const O=T[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(O)&&(T=T.toLowerCase()),x(T[0]).decode(T.substring(1))}function _(T){if(T instanceof Uint8Array&&(T=o(T)),Object.prototype.toString.call(T)!=="[object String]")return!1;try{return x(T[0]).name}catch{return!1}}function b(T,O){x(T).decode(o(O))}function x(T){if(Object.prototype.hasOwnProperty.call(r.names,T))return r.names[T];if(Object.prototype.hasOwnProperty.call(r.codes,T))return r.codes[T];throw new Error(`Unsupported encoding: ${T}`)}function E(T){return T instanceof Uint8Array&&(T=o(T)),x(T[0])}t=e.exports=l,t.encode=c,t.decode=u,t.isEncoded=_,t.encoding=x,t.encodingFromData=E;const I=Object.freeze(r.names),k=Object.freeze(r.codes);t.names=I,t.codes=k})(src$2,src$2.exports);const names$1=Object.freeze({identity:0,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,"murmur3-128":34,"murmur3-32":35,"dbl-sha2-256":86,md4:212,md5:213,bmt:214,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082});var constants={names:names$1};function base(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,H=new Uint8Array(N);$!==D;){for(var ie=k[$],ue=0,de=N-1;(ie!==0||ue>>0,H[de]=ie%c>>>0,ie=ie/c>>>0;if(ie!==0)throw new Error("Non-zero carry");O=ue,$++}for(var le=N-O;le!==N&&H[le]===0;)le++;for(var ce=u.repeat(T);le>>0,N=new Uint8Array(D);k[T];){var H=r[k.charCodeAt(T)];if(H===255)return;for(var ie=0,ue=D-1;(H!==0||ie<$)&&ue!==-1;ue--,ie++)H+=c*N[ue]>>>0,N[ue]=H%256>>>0,H=H/256>>>0;if(H!==0)throw new Error("Non-zero carry");$=ie,T++}if(k[T]!==" "){for(var de=D-$;de!==D&&N[de]===0;)de++;for(var le=new Uint8Array(O+(D-de)),ce=O;de!==D;)le[ce++]=N[de++];return le}}}function I(k){var T=E(k);if(T)return T;throw new Error(`Non-${t} character`)}return{encode:x,decodeUnsafe:E,decode:I}}var src=base,_brrp__multiformats_scope_baseX=src;const coerce$1=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},fromString=e=>new TextEncoder().encode(e),toString$3=e=>new TextDecoder().decode(e);class Encoder{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return or$1(this,t)}}class ComposedDecoder{constructor(t){this.decoders=t}or(t){return or$1(this,t)}decode(t){const r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$1=(e,t)=>new ComposedDecoder({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Codec{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Encoder(t,r,n),this.decoder=new Decoder(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const from$1=({name:e,prefix:t,encode:r,decode:n})=>new Codec(e,t,r,n),baseX=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=_brrp__multiformats_scope_baseX(r,t);return from$1({prefix:e,name:t,encode:n,decode:a=>coerce$1(o(a))})},decode$3=(e,t,r,n)=>{const o={};for(let b=0;b=8&&(c-=8,l[_++]=255&u>>c)}if(c>=r||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return l},encode$5=(e,t,r)=>{const n=t[t.length-1]==="=",o=(1<r;)l-=r,a+=t[o&c>>l];if(l&&(a+=t[o&c<from$1({prefix:t,name:e,encode(o){return encode$5(o,n,r)},decode(o){return decode$3(o,n,r,e)}}),identity$2=from$1({prefix:"\0",name:"identity",encode:e=>toString$3(e),decode:e=>fromString(e)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$2},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32upper,base32pad,base32padupper,base32hex,base32hexupper,base32hexpad,base32hexpadupper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$1=Object.freeze(Object.defineProperty({__proto__:null,base64,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),alphabet$1=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),alphabetBytesToChars=alphabet$1.reduce((e,t,r)=>(e[r]=t,e),[]),alphabetCharsToBytes=alphabet$1.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function encode$4(e){return e.reduce((t,r)=>(t+=alphabetBytesToChars[r],t),"")}function decode$2(e){const t=[];for(const r of e){const n=alphabetCharsToBytes[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}const base256emoji=from$1({prefix:"\u{1F680}",name:"base256emoji",encode:encode$4,decode:decode$2}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"}));var encode_1=encode$3,MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31);function encode$3(e,t,r){t=t||[],r=r||0;for(var n=r;e>=INT;)t[r++]=e&255|MSB,e/=128;for(;e&MSBALL;)t[r++]=e&255|MSB,e>>>=7;return t[r]=e|0,encode$3.bytes=r-n+1,t}var decode$1=read$1,MSB$1=128,REST$1=127;function read$1(e,n){var r=0,n=n||0,o=0,a=n,l,c=e.length;do{if(a>=c)throw read$1.bytes=0,new RangeError("Could not decode varint");l=e[a++],r+=o<28?(l&REST$1)<=MSB$1);return read$1.bytes=a-n,r}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length$1=function(e){return e(_brrp_varint.encode(e,t,r),t),encodingLength=e=>_brrp_varint.encodingLength(e),create=(e,t)=>{const r=t.byteLength,n=encodingLength(e),o=n+encodingLength(r),a=new Uint8Array(o+r);return encodeTo(e,a,0),encodeTo(r,a,n),a.set(t,o),new Digest(e,r,t,a)};class Digest{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}const from=({name:e,code:t,encode:r})=>new Hasher(e,t,r);class Hasher{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?create(this.code,r):r.then(n=>create(this.code,n))}else throw Error("Unknown type, must be binary type")}}const sha=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),sha256=from({name:"sha2-256",code:18,encode:sha("SHA-256")}),sha512=from({name:"sha2-512",code:19,encode:sha("SHA-512")}),sha2=Object.freeze(Object.defineProperty({__proto__:null,sha256,sha512},Symbol.toStringTag,{value:"Module"})),code$2=0,name="identity",encode$2=coerce$1,digest=e=>create(code$2,encode$2(e)),identity={code:code$2,name,encode:encode$2,digest},identity$1=Object.freeze(Object.defineProperty({__proto__:null,identity},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;({...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$1,...base256emoji$1});({...sha2,...identity$1});const{names}=constants,codes$4={};for(const e in names){const t=e;codes$4[names[t]]=t}Object.freeze(codes$4);logger("libp2p:webrtc:sdp");Object.values(bases).map(e=>e.decoder).reduce((e,t)=>e.or(t));Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");logger("libp2p:webrtc:transport");getProtocol("webrtc-direct").code;getProtocol("certhash").code;function webRTC(e){return t=>new WebRTCTransport(t,e)}function extractSNI(e){let t;try{t=getProtocol("sni").code}catch{return null}for(const[r,n]of e)if(r===t&&n!==void 0)return n;return null}function hasTLS(e){return e.some(([t,r])=>t===getProtocol("tls").code)}function interpretNext(e,t,r){const n=interpreters[getProtocol(e).name];if(n===void 0)throw new Error(`Can't interpret protocol ${getProtocol(e).name}`);const o=n(t,r);return e===getProtocol("ip6").code?`[${o}]`:o}const interpreters={ip4:(e,t)=>e,ip6:(e,t)=>t.length===0?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${interpretNext(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${interpretNext(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=hasTLS(t),n=extractSNI(t);if(r&&n!==null)return`https://${n}`;const o=r?"https://":"http://",a=t.pop();if(a===void 0)throw new Error("Unexpected end of multiaddr");let l=interpretNext(a[0],a[1]??"",t);return l=l.replace("tcp://",""),`${o}${l}`},tls:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");let n=interpretNext(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=hasTLS(t),n=extractSNI(t);if(r&&n!==null)return`wss://${n}`;const o=r?"wss://":"ws://",a=t.pop();if(a===void 0)throw new Error("Unexpected end of multiaddr");let l=interpretNext(a[0],a[1]??"",t);return l=l.replace("tcp://",""),`${o}${l}`},wss:(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");let n=interpretNext(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(r===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(r[0],r[1]??"",t)}/p2p-webrtc-direct`}};function multiaddrToUri(e,t){const n=multiaddr(e).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");const a=getProtocol(o[0]),l=interpreters[a.name];if(l==null)throw new Error(`No interpreter found for ${a.name}`);let c=l(o[1]??"",n);return t?.assumeHttp!==!1&&o[0]===getProtocol("tcp").code&&(c=c.replace("tcp://","http://"),(o[1]==="443"||o[1]==="80")&&(o[1]==="443"&&(c=c.replace("http://","https://")),c=c.substring(0,c.lastIndexOf(":")))),c}const ready=async e=>{if(e.readyState>=2)throw new Error("socket closed");e.readyState!==1&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",o),e.removeEventListener("error",a)}function o(){n(),t()}function a(l){n(),r(l.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",o),e.addEventListener("error",a)})},sink=(e,t)=>(t=t??{},t.closeOnEnd=t.closeOnEnd!==!1,async n=>{for await(const o of n){try{await ready(e)}catch(a){if(a.message==="socket closed")break;throw a}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(o)}t.closeOnEnd!=null&&e.readyState<=1&&await new Promise((o,a)=>{e.addEventListener("close",l=>{if(l.wasClean||l.code===1006)o();else{const c=Object.assign(new Error("ws error"),{event:l});a(c)}}),setTimeout(()=>{e.close()})})});var dom$1={},eventIterator={};Object.defineProperty(eventIterator,"__esModule",{value:!0});class EventQueue{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(t){if(this.isStopped)return;const r={value:t,done:!1};if(this.pullQueue.length){const n=this.pullQueue.shift();n&&n.resolve(r)}else this.pushQueue.push(Promise.resolve(r)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const t of this.pullQueue)t.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(t){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const r of this.pullQueue)r.reject(t);this.pullQueue.length=0}else{const r=Promise.reject(t);r.catch(()=>{}),this.pushQueue.push(r)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:t=>{const r=this.pushQueue.shift();return r?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),r):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,o)=>{this.pullQueue.push({resolve:n,reject:o})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class EventIterator$1{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const o=new EventQueue;o.highWaterMark=r,o.lowWaterMark=n,o.removeCallback=t({push:a=>o.push(a),stop:()=>o.stop(),fail:a=>o.fail(a),on:(a,l)=>{o.eventHandlers[a]=l}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}}eventIterator.EventIterator=EventIterator$1;eventIterator.default=EventIterator$1;Object.defineProperty(dom$1,"__esModule",{value:!0});const event_iterator_1=eventIterator;var EventIterator=dom$1.EventIterator=event_iterator_1.EventIterator;function subscribe(e,t,r){return new event_iterator_1.EventIterator(({push:n})=>(this.addEventListener(e,n,t),()=>this.removeEventListener(e,n,t)),r)}dom$1.subscribe=subscribe;dom$1.default=event_iterator_1.EventIterator;function isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&typeof e?.byteLength=="number"}const source=e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise((a,l)=>{if(n){a();return}if(o!=null){l(o);return}const c=b=>{e.removeEventListener("open",u),e.removeEventListener("error",_),b()},u=()=>{c(a)},_=b=>{c(()=>{l(b.error??new Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",u),e.addEventListener("error",_)})},r=async function*(){const a=new EventIterator(({push:l,stop:c,fail:u})=>{const _=x=>{let E=null;typeof x.data=="string"&&(E=fromString$1(x.data)),isArrayBuffer(x.data)&&(E=new Uint8Array(x.data)),x.data instanceof Uint8Array&&(E=x.data),E!=null&&l(E)},b=x=>{u(x.error??new Error("Socket error"))};return e.addEventListener("message",_),e.addEventListener("error",b),e.addEventListener("close",c),()=>{e.removeEventListener("message",_),e.removeEventListener("error",b),e.removeEventListener("close",c)}},{highWaterMark:1/0});await t();for await(const l of a)yield isArrayBuffer(l)?new Uint8Array(l):l}();let n=e.readyState===1,o;return e.addEventListener("open",()=>{n=!0,o=null}),e.addEventListener("close",()=>{n=!1,o=null}),e.addEventListener("error",a=>{n||(o=a.error??new Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(r,{connected:t})},duplex=(e,t)=>{t=t??{};const r=source(e);let n=t.remoteAddress,o=t.remotePort;if(e.url!=null)try{const l=new URL(e.url);n=l.hostname,o=parseInt(l.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:sink(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(l=>{e.addEventListener("close",()=>{l()}),e.close()})},destroy:()=>{e.terminate!=null?e.terminate():e.close()},remoteAddress:n,remotePort:o,socket:e}},WebSocket$1=WebSocket,isReactNative$1=typeof navigator<"u"&&navigator.product==="ReactNative";function getDefaultBase(){return isReactNative$1?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}const URL$1=self.URL,defaultBase$1=getDefaultBase();class URLWithLegacySupport$2{constructor(t="",r=defaultBase$1){this.super=new URL$1(t,r),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(t){this.super.hash=t}set host(t){this.super.host=t}set hostname(t){this.super.hostname=t}set href(t){this.super.href=t}set password(t){this.super.password=t}set pathname(t){this.super.pathname=t}set port(t){this.super.port=t}set protocol(t){this.super.protocol=t}set search(t){this.super.search=t}set username(t){this.super.username=t}static createObjectURL(t){return URL$1.createObjectURL(t)}static revokeObjectURL(t){URL$1.revokeObjectURL(t)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}}function format$2(e){if(typeof e=="string")return new URL$1(e).toString();if(!(e instanceof URL$1)){const t=e.username&&e.password?`${e.username}:${e.password}@`:"",r=e.auth?e.auth+"@":"",n=e.port?":"+e.port:"",o=e.protocol?e.protocol+"//":"",a=e.host||"",l=e.hostname||"",c=e.search||(e.query?"?"+e.query:""),u=e.hash||"",_=e.pathname||"",b=e.path||_+c;return`${o}${t||r}${a||l+n}${b}${u}`}}var urlBrowser={URLWithLegacySupport:URLWithLegacySupport$2,URLSearchParams:self.URLSearchParams,defaultBase:defaultBase$1,format:format$2};const{URLWithLegacySupport:URLWithLegacySupport$1,format:format$1}=urlBrowser;var relative$1=(e,t={},r={},n)=>{let o=t.protocol?t.protocol.replace(":",""):"http";o=(r[o]||n||o)+":";let a;try{a=new URLWithLegacySupport$1(e)}catch{a={}}const l=Object.assign({},t,{protocol:o||a.protocol,host:t.host||a.host});return new URLWithLegacySupport$1(e,format$1(l)).toString()};const{URLWithLegacySupport,format,URLSearchParams:URLSearchParams$1,defaultBase}=urlBrowser,relative=relative$1;var isoUrl={URL:URLWithLegacySupport,URLSearchParams:URLSearchParams$1,format,relative,defaultBase};const map$2={http:"ws",https:"wss"},def="ws",wsurl=(e,t)=>isoUrl.relative(e,t,map$2,def);function connect(e,t){const r=typeof window>"u"?"":window.location;t=t??{};const n=wsurl(e,r.toString()),o=new WebSocket$1(n,t.websocket);return duplex(o,t)}function isElectron$1(){return typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&!!process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0}var isElectron_1=isElectron$1;const isEnvWithDom=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,isElectron=isElectron_1(),isBrowser=isEnvWithDom&&!isElectron,isElectronMain=isElectron&&!isEnvWithDom,isElectronRenderer=isElectron&&isEnvWithDom,isNode=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!isElectron,isWebWorker=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope;typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"];const isReactNative=typeof navigator<"u"&&navigator.product==="ReactNative",CODE_P2P=421,CODE_CIRCUIT=290,CLOSE_TIMEOUT$1=500;function all$1(e){return e.filter(t=>{if(t.protoCodes().includes(CODE_CIRCUIT))return!1;const r=t.decapsulateCode(CODE_P2P);return WebSockets$1.matches(r)||WebSocketsSecure.matches(r)})}function wss(e){return e.filter(t=>{if(t.protoCodes().includes(CODE_CIRCUIT))return!1;const r=t.decapsulateCode(CODE_P2P);return WebSocketsSecure.matches(r)})}function createListener$1(){throw new Error("WebSocket Servers can not be created in the browser!")}const log$r=logger("libp2p:websockets:socket");function socketToMaConn(e,t,r){r=r??{};const n={async sink(o){r?.signal!=null&&(o=abortableSource(o,r.signal));try{await e.sink(o)}catch(a){a.type!=="aborted"&&log$r.error(a)}},source:r.signal!=null?abortableSource(e.source,r.signal):e.source,remoteAddr:t,timeline:{open:Date.now()},async close(o={}){const a=Date.now();o.signal=o.signal??AbortSignal.timeout(CLOSE_TIMEOUT$1);const l=()=>{const{host:c,port:u}=n.remoteAddr.toOptions();log$r("timeout closing stream to %s:%s after %dms, destroying it manually",c,u,Date.now()-a),this.abort(new CodeError("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};o.signal.addEventListener("abort",l);try{await e.close()}catch(c){this.abort(c)}finally{o.signal.removeEventListener("abort",l),n.timeline.close=Date.now()}},abort(o){const{host:a,port:l}=n.remoteAddr.toOptions();log$r("timeout closing stream to %s:%s due to error",a,l,o),e.destroy(),n.timeline.close=Date.now()}};return e.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}const log$q=logger("libp2p:websockets");var nc,ic;class WebSockets{constructor(t){Ke(this,"init");Ke(this,nc,"@libp2p/websockets");Ke(this,ic,!0);this.init=t}async dial(t,r){log$q("dialing %s",t),r=r??{};const n=await this._connect(t,r),o=socketToMaConn(n,t);log$q("new outbound connection %s",o.remoteAddr);const a=await r.upgrader.upgradeOutbound(o);return log$q("outbound connection %s upgraded",o.remoteAddr),a}async _connect(t,r){if(r?.signal?.aborted===!0)throw new AbortError$4;const n=t.toOptions();log$q("dialing %s:%s",n.host,n.port);const o=pDefer(),a=connect(multiaddrToUri(t),this.init);if(a.socket.addEventListener("error",()=>{const u=new CodeError(`Could not connect to ${t.toString()}`,"ERR_CONNECTION_FAILED");log$q.error("connection error:",u),o.reject(u)}),r.signal==null)return await Promise.race([a.connected(),o.promise]),log$q("connected %s",t),a;let l;const c=new Promise((u,_)=>{if(l=()=>{_(new AbortError$4),a.close().catch(b=>{log$q.error("error closing raw socket",b)})},r?.signal?.aborted===!0){l();return}r?.signal?.addEventListener("abort",l)});try{await Promise.race([c,o.promise,a.connected()])}finally{l!=null&&r?.signal?.removeEventListener("abort",l)}return log$q("connected %s",t),a}createListener(t){return createListener$1({...this.init,...t})}filter(t){return t=Array.isArray(t)?t:[t],this.init?.filter!=null?this.init?.filter(t):isBrowser||isWebWorker?wss(t):all$1(t)}}nc=Symbol.toStringTag,ic=symbol$1;function webSockets(e={}){return()=>new WebSockets(e)}var events$1={exports:{}},R$1=typeof Reflect=="object"?Reflect:null,ReflectApply=R$1&&typeof R$1.apply=="function"?R$1.apply:function e(t,r,n){return Function.prototype.apply.call(t,r,n)},ReflectOwnKeys;R$1&&typeof R$1.ownKeys=="function"?ReflectOwnKeys=R$1.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var NumberIsNaN=Number.isNaN||function e(t){return t!==t};function EventEmitter(){EventEmitter.init.call(this)}events$1.exports=EventEmitter;events$1.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=void 0;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(e){if(typeof e!="number"||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}});EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};EventEmitter.prototype.setMaxListeners=function e(t){if(typeof t!="number"||t<0||NumberIsNaN(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function e(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function e(t){for(var r=[],n=1;n0&&(l=r[0]),l instanceof Error)throw l;var c=new Error("Unhandled error."+(l?" ("+l.message+")":""));throw c.context=l,c}var u=a[t];if(u===void 0)return!1;if(typeof u=="function")ReflectApply(u,this,r);else for(var _=u.length,b=arrayClone(u,_),n=0;n<_;++n)ReflectApply(b[n],this,r);return!0};function _addListener(e,t,r,n){var o,a,l;if(checkListener(r),a=e._events,a===void 0?(a=e._events=Object.create(null),e._eventsCount=0):(a.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),l=a[t]),l===void 0)l=a[t]=r,++e._eventsCount;else if(typeof l=="function"?l=a[t]=n?[r,l]:[l,r]:n?l.unshift(r):l.push(r),o=_getMaxListeners(e),o>0&&l.length>o&&!l.warned){l.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=l.length,ProcessEmitWarning(c)}return e}EventEmitter.prototype.addListener=function e(t,r){return _addListener(this,t,r,!1)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function e(t,r){return _addListener(this,t,r,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=onceWrapper.bind(n);return o.listener=r,n.wrapFn=o,o}EventEmitter.prototype.once=function e(t,r){return checkListener(r),this.on(t,_onceWrap(this,t,r)),this};EventEmitter.prototype.prependOnceListener=function e(t,r){return checkListener(r),this.prependListener(t,_onceWrap(this,t,r)),this};EventEmitter.prototype.removeListener=function e(t,r){var n,o,a,l,c;if(checkListener(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,l=n.length-1;l>=0;l--)if(n[l]===r||n[l].listener===r){c=n[l].listener,a=l;break}if(a<0)return this;a===0?n.shift():spliceOne(n,a),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,c||r)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function e(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var a=Object.keys(n),l;for(o=0;o=0;o--)this.removeListener(t,r[o]);return this};function _listeners(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?unwrapListeners(o):arrayClone(o,o.length)}EventEmitter.prototype.listeners=function e(t){return _listeners(this,t,!0)};EventEmitter.prototype.rawListeners=function e(t){return _listeners(this,t,!1)};EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount.call(e,t)};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}EventEmitter.prototype.eventNames=function e(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(e,t){for(var r=new Array(t),n=0;ncrypto.getRandomValues(new Uint8Array(e)).reduce((t,r)=>(r&=63,r<36?t+=r.toString(36):r<62?t+=(r-26).toString(36).toUpperCase():r>62?t+="-":t+="_",t),"");const pathSepS="/",pathSepB=new TextEncoder().encode(pathSepS),pathSep=pathSepB[0];class Key{constructor(t,r){Ke(this,"_buf");if(typeof t=="string")this._buf=fromString$1(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==pathSep)throw new Error("Invalid key")}toString(t="utf8"){return toString$5(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new Key(t.join(pathSepS))}static random(){return new Key(nanoid().replace(/-/g,""))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new Key(t):typeof t.uint8Array=="function"?new Key(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=pathSepB),this._buf[0]!==pathSep){const t=new Uint8Array(this._buf.byteLength+1);t.fill(pathSep,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===pathSep;)this._buf=this._buf.subarray(0,-1)}less(t){const r=this.list(),n=t.list();for(let o=0;ol)return!1}return r.lengthr.namespaces()))])}}function namespaceType(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function namespaceValue(e){const t=e.split(":");return t[t.length-1]}function flatten(e){return[].concat(...e)}var isPlainObj=e=>{if(Object.prototype.toString.call(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype};const isOptionObject=isPlainObj,{hasOwnProperty:hasOwnProperty$1}=Object.prototype,{propertyIsEnumerable}=Object,defineProperty=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),globalThis$4=commonjsGlobal$2,defaultMergeOptions={concatArrays:!1,ignoreUndefined:!1},getEnumerableOwnPropertyKeys=e=>{const t=[];for(const r in e)hasOwnProperty$1.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)propertyIsEnumerable.call(e,n)&&t.push(n)}return t};function clone$1(e){return Array.isArray(e)?cloneArray(e):isOptionObject(e)?cloneOptionObject(e):e}function cloneArray(e){const t=e.slice(0,0);return getEnumerableOwnPropertyKeys(e).forEach(r=>{defineProperty(t,r,clone$1(e[r]))}),t}function cloneOptionObject(e){const t=Object.getPrototypeOf(e)===null?Object.create(null):{};return getEnumerableOwnPropertyKeys(e).forEach(r=>{defineProperty(t,r,clone$1(e[r]))}),t}const mergeKeys=(e,t,r,n)=>(r.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in e&&e[o]!==Object.getPrototypeOf(e)?defineProperty(e,o,merge(e[o],t[o],n)):defineProperty(e,o,clone$1(t[o])))}),e),concatArrays=(e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach(a=>{const l=[];for(let c=0;c!l.includes(c)),r)}),n};function merge(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?concatArrays(e,t,r):!isOptionObject(t)||!isOptionObject(e)?clone$1(t):mergeKeys(e,t,getEnumerableOwnPropertyKeys(t),r)}var mergeOptions=function(...e){const t=merge(clone$1(defaultMergeOptions),this!==globalThis$4&&this||{},defaultMergeOptions);let r={_:{}};for(const n of e)if(n!==void 0){if(!isOptionObject(n))throw new TypeError("`"+n+"` is not an Option Object");r=merge(r,{_:n},t)}return r._};function isHighSurrogate$1(e){return e>=55296&&e<=56319}function isLowSurrogate$1(e){return e>=56320&&e<=57343}var truncate$2=function e(t,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var o=r.length,a=0,l,c,u=0;un)return r.slice(0,u-c.length+1)}return r};function isHighSurrogate(e){return e>=55296&&e<=56319}function isLowSurrogate(e){return e>=56320&&e<=57343}var browser$5=function e(t){if(typeof t!="string")throw new Error("Input must be string");for(var r=t.length,n=0,o=null,a=null,l=0;l=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),a=o;return n},truncate$1=truncate$2,getLength=browser$5,browser$4=truncate$1.bind(null,getLength),truncate=browser$4,illegalRe=/[\/\?<>\\:\*\|"]/g,controlRe=/[\x00-\x1f\x80-\x9f]/g,reservedRe=/^\.+$/,windowsReservedRe=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,windowsTrailingRe=/[\. ]+$/;function sanitize(e,t){if(typeof e!="string")throw new Error("Input must be string");var r=e.replace(illegalRe,t).replace(controlRe,t).replace(reservedRe,t).replace(windowsReservedRe,t).replace(windowsTrailingRe,t);return truncate(r,255)}var sanitizeFilename=function(e,t){var r=t&&t.replacement||"",n=sanitize(e,r);return r===""?n:sanitize(n,"")},codes$3;(function(e){e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(codes$3||(codes$3={}));const log$p=logger("libp2p:keychain"),keyPrefix="/pkcs8/",infoPrefix="/info/",privates=new WeakMap,NIST={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},defaultOptions$6={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function validateKeyName(e){return e==null||typeof e!="string"?!1:e===sanitizeFilename(e.trim())&&e.length>0}async function randomDelay(){const r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function DsName(e){return new Key(keyPrefix+e)}function DsInfoName(e){return new Key(infoPrefix+e)}class DefaultKeyChain{constructor(t,r){Ke(this,"components");Ke(this,"init");if(this.components=t,this.init=mergeOptions(defaultOptions$6,r),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLengtho.id===t);if(n==null)throw new CodeError(`Key with id '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND);return n}catch(r){throw await randomDelay(),r}}async findKeyByName(t){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);const r=DsInfoName(t);try{const n=await this.components.datastore.get(r);return JSON.parse(toString$5(n))}catch(n){throw await randomDelay(),log$p.error(n),new CodeError(`Key '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND)}}async removeKey(t){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);const r=DsName(t),n=await this.findKeyByName(t),o=this.components.datastore.batch();return o.delete(r),o.delete(DsInfoName(t)),await o.commit(),n}async renameKey(t,r){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid old key name '${t}'`,codes$3.ERR_OLD_KEY_NAME_INVALID);if(!validateKeyName(r)||r==="self")throw await randomDelay(),new CodeError(`Invalid new key name '${r}'`,codes$3.ERR_NEW_KEY_NAME_INVALID);const n=DsName(t),o=DsName(r),a=DsInfoName(t),l=DsInfoName(r);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${r}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);try{const u=await this.components.datastore.get(n),_=await this.components.datastore.get(a),b=JSON.parse(toString$5(_));b.name=r;const x=this.components.datastore.batch();return x.put(o,u),x.put(l,fromString$1(JSON.stringify(b))),x.delete(n),x.delete(a),await x.commit(),b}catch(u){throw await randomDelay(),u}}async exportKey(t,r){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw await randomDelay(),new CodeError("Password is required",codes$3.ERR_PASSWORD_REQUIRED);const n=DsName(t);try{const o=await this.components.datastore.get(n),a=toString$5(o),l=privates.get(this);if(l==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const c=l.dek;return await(await importKey(a,c)).export(r)}catch(o){throw await randomDelay(),o}}async exportPeerId(t){const r="temporary-password",n=await this.exportKey(t,r),o=await importKey(n,r);return peerIdFromKeys(o.public.bytes,o.bytes)}async importKey(t,r,n){if(!validateKeyName(t)||t==="self")throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw await randomDelay(),new CodeError("PEM encoded key is required",codes$3.ERR_PEM_REQUIRED);const o=DsName(t);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${t}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);let l;try{l=await importKey(r,n)}catch{throw await randomDelay(),new CodeError("Cannot read the key, most likely the password is wrong",codes$3.ERR_CANNOT_READ_KEY)}let c;try{c=await l.id();const b=privates.get(this);if(b==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const x=b.dek;r=await l.export(x)}catch(b){throw await randomDelay(),b}const u={name:t,id:c},_=this.components.datastore.batch();return _.put(o,fromString$1(r)),_.put(DsInfoName(t),fromString$1(JSON.stringify(u))),await _.commit(),u}async importPeer(t,r){try{if(!validateKeyName(t))throw new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);if(r==null)throw new CodeError("PeerId is required",codes$3.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new CodeError("PeerId.privKey is required",codes$3.ERR_MISSING_PRIVATE_KEY);const n=await unmarshalPrivateKey(r.privateKey),o=DsName(t);if(await this.components.datastore.has(o))throw await randomDelay(),new CodeError(`Key '${t}' already exists`,codes$3.ERR_KEY_ALREADY_EXISTS);const l=privates.get(this);if(l==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const c=l.dek,u=await n.export(c),_={name:t,id:r.toString()},b=this.components.datastore.batch();return b.put(o,fromString$1(u)),b.put(DsInfoName(t),fromString$1(JSON.stringify(_))),await b.commit(),_}catch(n){throw await randomDelay(),n}}async getPrivateKey(t){if(!validateKeyName(t))throw await randomDelay(),new CodeError(`Invalid key name '${t}'`,codes$3.ERR_INVALID_KEY_NAME);try{const r=DsName(t),n=await this.components.datastore.get(r);return toString$5(n)}catch(r){throw await randomDelay(),log$p.error(r),new CodeError(`Key '${t}' does not exist.`,codes$3.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(t,r){if(typeof t!="string")throw await randomDelay(),new CodeError(`Invalid old pass type '${typeof t}'`,codes$3.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await randomDelay(),new CodeError(`Invalid new pass type '${typeof r}'`,codes$3.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await randomDelay(),new CodeError(`Invalid pass length ${r.length}`,codes$3.ERR_INVALID_PASS_LENGTH);log$p("recreating keychain");const n=privates.get(this);if(n==null)throw new CodeError("dek missing",codes$3.ERR_INVALID_PARAMETERS);const o=n.dek;this.init.pass=r;const a=r!=null&&this.init.dek?.salt!=null?pbkdf2(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";privates.set(this,{dek:a});const l=await this.listKeys();for(const c of l){const u=await this.components.datastore.get(DsName(c.name)),_=toString$5(u),b=await importKey(_,o),x=a.toString(),E=await b.export(x),I=this.components.datastore.batch(),k={name:c.name,id:c.id};I.put(DsName(c.name),fromString$1(E)),I.put(DsInfoName(c.name),fromString$1(JSON.stringify(k))),await I.commit()}log$p("keychain reconstructed")}}var PeerIdProto;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.id!=null&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.id=r.bytes();break;case 2:o.pubKey=r.bytes();break;case 3:o.privKey=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerIdProto||(PeerIdProto={}));const createEd25519PeerId=async()=>{const e=await generateKeyPair("Ed25519"),t=await createFromPrivKey(e);if(t.type==="Ed25519")return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function createFromPrivKey(e){return peerIdFromKeys(marshalPublicKey(e.public),marshalPrivateKey(e))}const codes$2={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Envelope;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.publicKey!=null&&r.publicKey.byteLength>0&&(n.uint32(10),n.bytes(r.publicKey)),r.payloadType!=null&&r.payloadType.byteLength>0&&(n.uint32(18),n.bytes(r.payloadType)),r.payload!=null&&r.payload.byteLength>0&&(n.uint32(26),n.bytes(r.payload)),r.signature!=null&&r.signature.byteLength>0&&(n.uint32(42),n.bytes(r.signature)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.publicKey=r.bytes();break;case 2:o.payloadType=r.bytes();break;case 3:o.payload=r.bytes();break;case 5:o.signature=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Envelope||(Envelope={}));const Qi=class{constructor(t){Ke(this,"peerId");Ke(this,"payloadType");Ke(this,"payload");Ke(this,"signature");Ke(this,"marshaled");const{peerId:r,payloadType:n,payload:o,signature:a}=t;this.peerId=r,this.payloadType=n,this.payload=o,this.signature=a}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Envelope.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return equals$2(this.marshal(),t.marshal())}async validate(t){const r=formatSignaturePayload(t,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return unmarshalPublicKey(this.peerId.publicKey).verify(r.subarray(),this.signature)}};let RecordEnvelope=Qi;Ke(RecordEnvelope,"createFromProtobuf",async t=>{const r=Envelope.decode(t),n=await peerIdFromKeys(r.publicKey);return new Qi({peerId:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})}),Ke(RecordEnvelope,"seal",async(t,r)=>{if(r.privateKey==null)throw new Error("Missing private key");const n=t.domain,o=t.codec,a=t.marshal(),l=formatSignaturePayload(n,o,a),u=await(await unmarshalPrivateKey(r.privateKey)).sign(l.subarray());return new Qi({peerId:r,payloadType:o,payload:a,signature:u})}),Ke(RecordEnvelope,"openAndCertify",async(t,r)=>{const n=await Qi.createFromProtobuf(t);if(!await n.validate(r))throw new CodeError("envelope signature is not valid for the given domain",codes$2.ERR_SIGNATURE_NOT_VALID);return n});const formatSignaturePayload=(e,t,r)=>{const n=fromString$1(e),o=encode$d(n.byteLength),a=encode$d(t.length),l=encode$d(r.length);return new Uint8ArrayList(o,n,a,t,l,r)};function arrayEquals(e,t){const r=(n,o)=>n.toString().localeCompare(o.toString());return e.length!==t.length?!1:(t.sort(r),e.sort(r).every((n,o)=>t[o].equals(n)))}const ENVELOPE_DOMAIN_PEER_RECORD="libp2p-peer-record",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD=Uint8Array.from([3,1]);var PeerRecord$1;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(a.uint32(10),a.bytes(o.multiaddr)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={multiaddr:new Uint8Array(0)},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.AddressInfo||(e.AddressInfo={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.peerId!=null&&r.peerId.byteLength>0&&(n.uint32(10),n.bytes(r.peerId)),r.seq!=null&&r.seq!==0n&&(n.uint32(16),n.uint64(r.seq)),r.addresses!=null)for(const a of r.addresses)n.uint32(26),e.AddressInfo.codec().encode(a,n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={peerId:new Uint8Array(0),seq:0n,addresses:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.peerId=r.bytes();break;case 2:o.seq=r.uint64();break;case 3:o.addresses.push(e.AddressInfo.codec().decode(r,r.uint32()));break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(PeerRecord$1||(PeerRecord$1={}));const yi=class{constructor(t){Ke(this,"peerId");Ke(this,"multiaddrs");Ke(this,"seqNumber");Ke(this,"domain",yi.DOMAIN);Ke(this,"codec",yi.CODEC);Ke(this,"marshaled");const{peerId:r,multiaddrs:n,seqNumber:o}=t;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=PeerRecord$1.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof yi)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!arrayEquals(this.multiaddrs,t.multiaddrs))}};let PeerRecord=yi;Ke(PeerRecord,"createFromProtobuf",t=>{const r=PeerRecord$1.decode(t),n=peerIdFromBytes(r.peerId),o=(r.addresses??[]).map(l=>multiaddr(l.multiaddr)),a=r.seq;return new yi({peerId:n,multiaddrs:o,seqNumber:a})}),Ke(PeerRecord,"DOMAIN",ENVELOPE_DOMAIN_PEER_RECORD),Ke(PeerRecord,"CODEC",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD);function isAsyncIterable$6(e){return e[Symbol.asyncIterator]!=null}function all(e){if(isAsyncIterable$6(e))return(async()=>{const r=[];for await(const n of e)r.push(n);return r})();const t=[];for(const r of e)t.push(r);return t}const WORKER_REQUEST_READ_LOCK="lock:worker:request-read",WORKER_RELEASE_READ_LOCK="lock:worker:release-read",MASTER_GRANT_READ_LOCK="lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK="lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK="lock:worker:release-write",MASTER_GRANT_WRITE_LOCK="lock:master:grant-write",events={},observable=e=>{e.addEventListener("message",t=>{observable.dispatchEvent("message",e,t)}),e.port!=null&&e.port.addEventListener("message",t=>{observable.dispatchEvent("message",e,t)})};observable.addEventListener=(e,t)=>{events[e]==null&&(events[e]=[]),events[e].push(t)};observable.removeEventListener=(e,t)=>{events[e]!=null&&(events[e]=events[e].filter(r=>r===t))};observable.dispatchEvent=function(e,t,r){events[e]!=null&&events[e].forEach(n=>n(t,r))};const handleWorkerLockRequest=(e,t,r,n,o)=>(a,l)=>{if(l.data.type!==r)return;const c={type:l.data.type,name:l.data.name,identifier:l.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:c.name,handler:async()=>(a.postMessage({type:o,name:c.name,identifier:c.identifier}),await new Promise(u=>{const _=b=>{if(b==null||b.data==null)return;const x={type:b.data.type,name:b.data.name,identifier:b.data.identifier};x.type===n&&x.identifier===c.identifier&&(a.removeEventListener("message",_),u())};a.addEventListener("message",_)}))}}))},makeWorkerLockRequest=(e,t,r,n)=>async()=>{const o=nanoid();return globalThis.postMessage({type:t,identifier:o,name:e}),await new Promise(a=>{const l=c=>{if(c==null||c.data==null)return;const u={type:c.data.type,identifier:c.data.identifier};u.type===r&&u.identifier===o&&(globalThis.removeEventListener("message",l),a(()=>{globalThis.postMessage({type:n,identifier:o,name:e})}))};globalThis.addEventListener("message",l)})},defaultOptions$5={singleProcess:!1},impl=e=>{if(e=Object.assign({},defaultOptions$5,e),Boolean(globalThis.document)||e.singleProcess){const r=new EventTarget;return observable.addEventListener("message",handleWorkerLockRequest(r,"requestReadLock",WORKER_REQUEST_READ_LOCK,WORKER_RELEASE_READ_LOCK,MASTER_GRANT_READ_LOCK)),observable.addEventListener("message",handleWorkerLockRequest(r,"requestWriteLock",WORKER_REQUEST_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK)),r}return{isWorker:!0,readLock:r=>makeWorkerLockRequest(r,WORKER_REQUEST_READ_LOCK,MASTER_GRANT_READ_LOCK,WORKER_RELEASE_READ_LOCK),writeLock:r=>makeWorkerLockRequest(r,WORKER_REQUEST_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK)}},mutexes={};let implementation;async function createReleaseable(e,t){let r;const n=new Promise(o=>{r=o});return e.add(async()=>await pTimeout((async()=>await new Promise(o=>{r(()=>{o()})}))(),{milliseconds:t.timeout})),await n}const createMutex=(e,t)=>{if(implementation.isWorker===!0)return{readLock:implementation.readLock(e,t),writeLock:implementation.writeLock(e,t)};const r=new PQueue({concurrency:1});let n;return{async readLock(){if(n!=null)return await createReleaseable(n,t);n=new PQueue({concurrency:t.concurrency,autoStart:!1});const o=n,a=createReleaseable(n,t);return r.add(async()=>(o.start(),await o.onIdle().then(()=>{n===o&&(n=null)}))),await a},async writeLock(){return n=null,await createReleaseable(r,t)}}},defaultOptions$4={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function createMortice(e){const t=Object.assign({},defaultOptions$4,e);return implementation==null&&(implementation=impl(t),implementation.isWorker!==!0&&(implementation.addEventListener("requestReadLock",r=>{mutexes[r.data.name]!=null&&mutexes[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),implementation.addEventListener("requestWriteLock",async r=>{mutexes[r.data.name]!=null&&mutexes[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),mutexes[t.name]==null&&(mutexes[t.name]=createMutex(t.name,t)),mutexes[t.name]}const codes$1={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Peer$1;(function(e){(function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={key:"",value:new Uint8Array(0)},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.key=o.string();break;case 2:l.value=o.bytes();break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(r){let n;r.codec=()=>(n==null&&(n=message((o,a,l={})=>{l.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),Tag.codec().encode(o.value,a)),l.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{const l={key:""},c=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:l.key=o.string();break;case 2:l.value=Tag.codec().decode(o,o.uint32());break;default:o.skipType(u&7);break}}return l})),n),r.encode=o=>encodeMessage(o,r.codec()),r.decode=o=>decodeMessage(o,r.codec())}(e.Peer$tagsEntry||(e.Peer$tagsEntry={}));let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.addresses!=null)for(const a of r.addresses)n.uint32(10),Address.codec().encode(a,n);if(r.protocols!=null)for(const a of r.protocols)n.uint32(18),n.string(a);if(r.publicKey!=null&&(n.uint32(34),n.bytes(r.publicKey)),r.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(r.peerRecordEnvelope)),r.metadata!=null&&r.metadata.size!==0)for(const[a,l]of r.metadata.entries())n.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:l},n);if(r.tags!=null&&r.tags.size!==0)for(const[a,l]of r.tags.entries())n.uint32(58),e.Peer$tagsEntry.codec().encode({key:a,value:l},n);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.addresses.push(Address.codec().decode(r,r.uint32()));break;case 2:o.protocols.push(r.string());break;case 4:o.publicKey=r.bytes();break;case 5:o.peerRecordEnvelope=r.bytes();break;case 6:{const c=e.Peer$metadataEntry.codec().decode(r,r.uint32());o.metadata.set(c.key,c.value);break}case 7:{const c=e.Peer$tagsEntry.codec().decode(r,r.uint32());o.tags.set(c.key,c.value);break}default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Peer$1||(Peer$1={}));var Address;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.multiaddr!=null&&r.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={multiaddr:new Uint8Array(0)},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.multiaddr=r.bytes();break;case 2:o.isCertified=r.bool();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Address||(Address={}));var Tag;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.value!=null&&r.value!==0&&(n.uint32(8),n.uint32(r.value)),r.expiry!=null&&(n.uint32(16),n.uint64(r.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={value:0},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.value=r.uint32();break;case 2:o.expiry=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Tag||(Tag={}));function bytesToPeer(e,t){const r=Peer$1.decode(t);r.publicKey!=null&&e.publicKey==null&&(e=peerIdFromPeerId({...e,publicKey:e.publicKey}));const n=new Map,o=BigInt(Date.now());for(const[a,l]of r.tags.entries())l.expiry!=null&&l.expiry({multiaddr:multiaddr(a),isCertified:l??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}const NAMESPACE_COMMON="/peers/";function peerIdToDatastoreKey(e){if(!isPeerId(e)||e.type==null)throw new CodeError("Invalid PeerId",codes$1.ERR_INVALID_PARAMETERS);const t=e.toCID().toString();return new Key(`${NAMESPACE_COMMON}${t}`)}async function dedupeFilterAndSortAddresses(e,t,r){const n=new Map;for(const o of r){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=multiaddr(o.multiaddr)),!isMultiaddr(o.multiaddr))throw new CodeError("Multiaddr was invalid",codes$1.ERR_INVALID_PARAMETERS);if(!await t(e,o.multiaddr))continue;const a=o.isCertified??!1,l=o.multiaddr.toString(),c=n.get(l);c!=null?o.isCertified=c.isCertified||a:n.set(l,{multiaddr:o.multiaddr,isCertified:a})}return[...n.values()].sort((o,a)=>o.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:o,multiaddr:a})=>({isCertified:o,multiaddr:a.bytes}))}async function toPeerPB(e,t,r,n){if(t==null)throw new CodeError("Invalid PeerData",codes$1.ERR_INVALID_PARAMETERS);if(t.publicKey!=null&&e.publicKey!=null&&!equals$2(t.publicKey,e.publicKey))throw new CodeError("publicKey bytes do not match peer id publicKey bytes",codes$1.ERR_INVALID_PARAMETERS);const o=n.existingPeer;if(o!=null&&!e.equals(o.id))throw new CodeError("peer id did not match existing peer id",codes$1.ERR_INVALID_PARAMETERS);let a=o?.addresses??[],l=new Set(o?.protocols??[]),c=o?.metadata??new Map,u=o?.tags??new Map,_=o?.peerRecordEnvelope;if(r==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(a=[],t.multiaddrs!=null&&a.push(...t.multiaddrs.map(x=>({isCertified:!1,multiaddr:x}))),t.addresses!=null&&a.push(...t.addresses)),t.protocols!=null&&(l=new Set(t.protocols)),t.metadata!=null){const x=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);c=createSortedMap(x,{validate:validateMetadata})}if(t.tags!=null){const x=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);u=createSortedMap(x,{validate:validateTag,map:mapTag})}t.peerRecordEnvelope!=null&&(_=t.peerRecordEnvelope)}if(r==="merge"){if(t.multiaddrs!=null&&a.push(...t.multiaddrs.map(x=>({isCertified:!1,multiaddr:x}))),t.addresses!=null&&a.push(...t.addresses),t.protocols!=null&&(l=new Set([...l,...t.protocols])),t.metadata!=null){const x=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[E,I]of x)I==null?c.delete(E):c.set(E,I);c=createSortedMap([...c.entries()],{validate:validateMetadata})}if(t.tags!=null){const x=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),E=new Map(u);for(const[I,k]of x)k==null?E.delete(I):E.set(I,k);u=createSortedMap([...E.entries()],{validate:validateTag,map:mapTag})}t.peerRecordEnvelope!=null&&(_=t.peerRecordEnvelope)}const b={addresses:await dedupeFilterAndSortAddresses(e,n.addressFilter??(async()=>!0),a),protocols:[...l.values()].sort((x,E)=>x.localeCompare(E)),metadata:c,tags:u,publicKey:o?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:_};return e.type!=="RSA"&&delete b.publicKey,b}function createSortedMap(e,t){const r=new Map;for(const[n,o]of e)o!=null&&t.validate(n,o);for(const[n,o]of e.sort(([a],[l])=>a.localeCompare(l)))o!=null&&r.set(n,t.map?.(n,o)??o);return r}function validateMetadata(e,t){if(typeof e!="string")throw new CodeError("Metadata key must be a string",codes$1.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new CodeError("Metadata value must be a Uint8Array",codes$1.ERR_INVALID_PARAMETERS)}function validateTag(e,t){if(typeof e!="string")throw new CodeError("Tag name must be a string",codes$1.ERR_INVALID_PARAMETERS);if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new CodeError("Tag value must be an integer",codes$1.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new CodeError("Tag value must be between 0-100",codes$1.ERR_INVALID_PARAMETERS)}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new CodeError("Tag ttl must be an integer",codes$1.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new CodeError("Tag ttl must be between greater than 0",codes$1.ERR_INVALID_PARAMETERS)}}function mapTag(e,t){let r;return t.expiry!=null&&(r=t.expiry),t.ttl!=null&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function decodePeer(e,t,r){const n=e.toString().split("/")[2],o=base32$2.decode(n),a=peerIdFromBytes(o),l=r.get(a);if(l!=null)return l;const c=bytesToPeer(a,t);return r.set(a,c),c}function mapQuery(e,t){return e==null?{}:{prefix:NAMESPACE_COMMON,filters:(e.filters??[]).map(r=>({key:n,value:o})=>r(decodePeer(n,o,t))),orders:(e.orders??[]).map(r=>(n,o)=>r(decodePeer(n.key,n.value,t),decodePeer(o.key,o.value,t)))}}var _i,so,bi,oo;class PersistentStore{constructor(t,r={}){_r(this,_i);_r(this,bi);Ke(this,"peerId");Ke(this,"datastore");Ke(this,"lock");Ke(this,"addressFilter");this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=r.addressFilter,this.lock=createMortice({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(peerIdToDatastoreKey(t))}async delete(t){if(this.peerId.equals(t))throw new CodeError("Cannot delete self peer",codes$1.ERR_INVALID_PARAMETERS);await this.datastore.delete(peerIdToDatastoreKey(t))}async load(t){const r=await this.datastore.get(peerIdToDatastoreKey(t));return bytesToPeer(t,r)}async save(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"patch",{addressFilter:this.addressFilter});return vr(this,bi,oo).call(this,t,a,n,o)}async patch(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"patch",{addressFilter:this.addressFilter,existingPeer:o});return vr(this,bi,oo).call(this,t,a,n,o)}async merge(t,r){const{existingBuf:n,existingPeer:o}=await vr(this,_i,so).call(this,t),a=await toPeerPB(t,r,"merge",{addressFilter:this.addressFilter,existingPeer:o});return vr(this,bi,oo).call(this,t,a,n,o)}async*all(t){const r=new PeerMap;for await(const{key:n,value:o}of this.datastore.query(mapQuery(t??{},r))){const a=decodePeer(n,o,r);a.id.equals(this.peerId)||(yield a)}}}_i=new WeakSet,so=async function(t){try{const r=await this.datastore.get(peerIdToDatastoreKey(t)),n=bytesToPeer(t,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}},bi=new WeakSet,oo=async function(t,r,n,o){const a=Peer$1.encode(r);return n!=null&&equals$2(a,n)?{peer:bytesToPeer(t,a),previous:o,updated:!1}:(await this.datastore.put(peerIdToDatastoreKey(t),a),{peer:bytesToPeer(t,a),previous:o,updated:!0})};const log$o=logger("libp2p:peer-store");var wi,ao;class PersistentPeerStore{constructor(t,r={}){_r(this,wi);Ke(this,"store");Ke(this,"events");Ke(this,"peerId");this.events=t.events,this.peerId=t.peerId,this.store=new PersistentStore(t,r)}async forEach(t,r){log$o.trace("forEach await read lock");const n=await this.store.lock.readLock();log$o.trace("forEach got read lock");try{for await(const o of this.store.all(r))t(o)}finally{log$o.trace("forEach release read lock"),n()}}async all(t){log$o.trace("all await read lock");const r=await this.store.lock.readLock();log$o.trace("all got read lock");try{return await all(this.store.all(t))}finally{log$o.trace("all release read lock"),r()}}async delete(t){log$o.trace("delete await write lock");const r=await this.store.lock.writeLock();log$o.trace("delete got write lock");try{await this.store.delete(t)}finally{log$o.trace("delete release write lock"),r()}}async has(t){log$o.trace("has await read lock");const r=await this.store.lock.readLock();log$o.trace("has got read lock");try{return await this.store.has(t)}finally{log$o.trace("has release read lock"),r()}}async get(t){log$o.trace("get await read lock");const r=await this.store.lock.readLock();log$o.trace("get got read lock");try{return await this.store.load(t)}finally{log$o.trace("get release read lock"),r()}}async save(t,r){log$o.trace("save await write lock");const n=await this.store.lock.writeLock();log$o.trace("save got write lock");try{const o=await this.store.save(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("save release write lock"),n()}}async patch(t,r){log$o.trace("patch await write lock");const n=await this.store.lock.writeLock();log$o.trace("patch got write lock");try{const o=await this.store.patch(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("patch release write lock"),n()}}async merge(t,r){log$o.trace("merge await write lock");const n=await this.store.lock.writeLock();log$o.trace("merge got write lock");try{const o=await this.store.merge(t,r);return vr(this,wi,ao).call(this,t,o),o.peer}finally{log$o.trace("merge release write lock"),n()}}async consumePeerRecord(t,r){const n=await RecordEnvelope.openAndCertify(t,PeerRecord.DOMAIN);if(r?.equals(n.peerId)===!1)return log$o("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;const o=PeerRecord.createFromProtobuf(n.payload);let a;try{a=await this.get(n.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(a?.peerRecordEnvelope!=null){const l=await RecordEnvelope.createFromProtobuf(a.peerRecordEnvelope),c=PeerRecord.createFromProtobuf(l.payload);if(c.seqNumber>=o.seqNumber)return log$o("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:t,addresses:o.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))}),!0}}wi=new WeakSet,ao=function(t,r){!r.updated||(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))};function isAsyncIterable$5(e){return e[Symbol.asyncIterator]!=null}function drain(e){if(isAsyncIterable$5(e))return(async()=>{for await(const t of e);})();for(const t of e);}function peekable(e){const[t,r]=e[Symbol.asyncIterator]!=null?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}function isAsyncIterable$4(e){return e[Symbol.asyncIterator]!=null}function filter(e,t){if(isAsyncIterable$4(e))return async function*(){for await(const c of e)await t(c)&&(yield c)}();const r=peekable(e),{value:n,done:o}=r.next();if(o===!0)return function*(){}();const a=t(n);if(typeof a.then=="function")return async function*(){await a&&(yield n);for await(const c of r)await t(c)&&(yield c)}();const l=t;return function*(){a===!0&&(yield n);for(const c of r)l(c)&&(yield c)}()}function isAsyncIterable$3(e){return e[Symbol.asyncIterator]!=null}function sort(e,t){return isAsyncIterable$3(e)?async function*(){yield*(await all(e)).sort(t)}():function*(){yield*all(e).sort(t)}()}function isAsyncIterable$2(e){return e[Symbol.asyncIterator]!=null}function take(e,t){return isAsyncIterable$2(e)?async function*(){let r=0;if(!(t<1)){for await(const n of e)if(yield n,r++,r===t)return}}():function*(){let r=0;if(!(t<1)){for(const n of e)if(yield n,r++,r===t)return}}()}class BaseDatastore{put(t,r,n){return Promise.reject(new Error(".put is not implemented"))}get(t,r){return Promise.reject(new Error(".get is not implemented"))}has(t,r){return Promise.reject(new Error(".has is not implemented"))}delete(t,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,r={}){for await(const{key:n,value:o}of t)await this.put(n,o,r),yield n}async*getMany(t,r={}){for await(const n of t)yield{key:n,value:await this.get(n,r)}}async*deleteMany(t,r={}){for await(const n of t)await this.delete(n,r),yield n}batch(){let t=[],r=[];return{put(n,o){t.push({key:n,value:o})},delete(n){r.push(n)},commit:async n=>{await drain(this.putMany(t,n)),t=[],await drain(this.deleteMany(r,n)),r=[]}}}async*_all(t,r){throw new Error("._all is not implemented")}async*_allKeys(t,r){throw new Error("._allKeys is not implemented")}query(t,r){let n=this._all(t,r);if(t.prefix!=null){const o=t.prefix;n=filter(n,a=>a.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,a)=>filter(o,a),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,a)=>sort(o,a),n)),t.offset!=null){let o=0;const a=t.offset;n=filter(n,()=>o++>=a)}return t.limit!=null&&(n=take(n,t.limit)),n}queryKeys(t,r){let n=this._allKeys(t,r);if(t.prefix!=null){const o=t.prefix;n=filter(n,a=>a.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,a)=>filter(o,a),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,a)=>sort(o,a),n)),t.offset!=null){const o=t.offset;let a=0;n=filter(n,()=>a++>=o)}return t.limit!=null&&(n=take(n,t.limit)),n}}function notFoundError(e){return e=e??new Error("Not Found"),errCode(e,"ERR_NOT_FOUND")}class MemoryDatastore extends BaseDatastore{constructor(){super();Ke(this,"data");this.data=new Map}put(r,n){return this.data.set(r.toString(),n),r}get(r){const n=this.data.get(r.toString());if(n==null)throw notFoundError();return n}has(r){return this.data.has(r.toString())}delete(r){this.data.delete(r.toString())}*_all(){for(const[r,n]of this.data.entries())yield{key:new Key(r),value:n}}*_allKeys(){for(const r of this.data.keys())yield new Key(r)}}function debounce(e,t){let r;return function(){const n=function(){r=void 0,e()};clearTimeout(r),r=setTimeout(n,t)}}const log$n=logger("libp2p:address-manager"),defaultAddressFilter=e=>e;function stripPeerId(e,t){const r=e.getPeerId();return r!=null&&peerIdFromString(r).equals(t)&&(e=e.decapsulate(multiaddr(`/p2p/${t.toString()}`))),e}class DefaultAddressManager{constructor(t,r={}){Ke(this,"components");Ke(this,"listen");Ke(this,"announce");Ke(this,"observed");Ke(this,"announceFilter");const{listen:n=[],announce:o=[]}=r;this.components=t,this.listen=n.map(a=>a.toString()),this.announce=new Set(o.map(a=>a.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??defaultAddressFilter,this._updatePeerStoreAddresses=debounce(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){const t=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>multiaddr(r))).map(r=>r.getPeerId()===this.components.peerId.toString()?r.decapsulate(`/p2p/${this.components.peerId.toString()}`):r);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(r=>{log$n.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(t=>multiaddr(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>multiaddr(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>multiaddr(t))}addObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString(),o=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=stripPeerId(t,this.components.peerId);const r=t.toString();this.observed.delete(r)}getAddresses(){let t=this.getAnnounceAddrs().map(n=>n.toString());t.length===0&&(t=this.components.transportManager.getAddrs().map(n=>n.toString())),t=t.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));const r=new Set(t);return this.announceFilter(Array.from(r).map(n=>multiaddr(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}}function isStartable(e){return e!=null&&typeof e.start=="function"&&typeof e.stop=="function"}class DefaultComponents{constructor(t={}){Ke(this,"components",{});Ke(this,"_started",!1);this.components={};for(const[r,n]of Object.entries(t))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(r=>isStartable(r)).map(async r=>{await r[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const OPTIONAL_SERVICES=["metrics","connectionProtector"],NON_SERVICE_PROPERTIES=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function defaultComponents(e={}){const t=new DefaultComponents(e);return new Proxy(t,{get(n,o,a){if(typeof o=="string"&&!NON_SERVICE_PROPERTIES.includes(o)){const l=t.components[o];if(l==null&&!OPTIONAL_SERVICES.includes(o))throw new CodeError(`${o} not set`,"ERR_SERVICE_MISSING");return l}return Reflect.get(n,o,a)},set(n,o,a){return typeof o=="string"?t.components[o]=a:Reflect.set(n,o,a),!0}})}var Netmask_1;(function(){var e,t,r,n,o,a,l,c;c=function(u){var _,b,x,E;return _=(u&255<<24)>>>24,b=(u&255<<16)>>>16,x=(u&255<<8)>>>8,E=u&255,[_,b,x,E].join(".")},l=function(u){var _,b,x,E,I,k;for(_=[],x=E=0;E<=3&&u.length!==0;x=++E){if(x>0){if(u[0]!==".")throw new Error("Invalid IP");u=u.substring(1)}k=t(u),I=k[0],b=k[1],u=u.substring(b),_.push(I)}if(u.length!==0)throw new Error("Invalid IP");switch(_.length){case 1:if(_[0]>4294967295)throw new Error("Invalid IP");return _[0]>>>0;case 2:if(_[0]>255||_[1]>16777215)throw new Error("Invalid IP");return(_[0]<<24|_[1])>>>0;case 3:if(_[0]>255||_[1]>255||_[2]>65535)throw new Error("Invalid IP");return(_[0]<<24|_[1]<<16|_[2])>>>0;case 4:if(_[0]>255||_[1]>255||_[2]>255||_[3]>255)throw new Error("Invalid IP");return(_[0]<<24|_[1]<<16|_[2]<<8|_[3])>>>0;default:throw new Error("Invalid IP")}},r=function(u){return u.charCodeAt(0)},n=r("0"),a=r("a"),o=r("A"),t=function(u){var _,b,x,E,I;for(E=0,_=10,b="9",x=0,u.length>1&&u[x]==="0"&&(u[x+1]==="x"||u[x+1]==="X"?(x+=2,_=16):"0"<=u[x+1]&&u[x+1]<="9"&&(x++,_=8,b="7")),I=x;x>>0;else if(_===16)if("a"<=u[x]&&u[x]<="f")E=E*_+(10+r(u[x])-a)>>>0;else if("A"<=u[x]&&u[x]<="F")E=E*_+(10+r(u[x])-o)>>>0;else break;else break;if(E>4294967295)throw new Error("too large");x++}if(x===I)throw new Error("empty octet");return[E,x]},e=function(){function u(_,b){var x,E,I;if(typeof _!="string")throw new Error("Missing `net' parameter");if(b||(I=_.split("/",2),_=I[0],b=I[1]),b||(b=32),typeof b=="string"&&b.indexOf(".")>-1){try{this.maskLong=l(b)}catch{throw new Error("Invalid mask: "+b)}for(x=E=32;E>=0;x=--E)if(this.maskLong===4294967295<<32-x>>>0){this.bitmask=x;break}}else if(b||b===0)this.bitmask=parseInt(b,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(l(_)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+_)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+b);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return u.prototype.contains=function(_){return typeof _=="string"&&(_.indexOf("/")>0||_.split(".").length!==4)&&(_=new u(_)),_ instanceof u?this.contains(_.base)&&this.contains(_.broadcast||_.last):(l(_)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},u.prototype.next=function(_){return _==null&&(_=1),new u(c(this.netLong+this.size*_),this.mask)},u.prototype.forEach=function(_){var b,x,E;for(E=l(this.first),x=l(this.last),b=0;E<=x;)_(c(E),E,b),b++,E++},u.prototype.toString=function(){return this.base+"/"+this.bitmask},u}(),Netmask_1=e}).call(commonjsGlobal$2);const word="[a-fA-F\\d:]",boundry=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))`:"",v4="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",v6segment="[a-fA-F\\d]{1,4}",v6=` (?: (?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 (?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 @@ -137,9 +137,9 @@ hooks.version="2.29.4";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min (?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 (?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 -`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),v46Exact=new RegExp(`(?:^${v4}$)|(?:^${v6}$)`),v4exact=new RegExp(`^${v4}$`),v6exact=new RegExp(`^${v6}$`),ipRegex=e=>e&&e.exact?v46Exact:new RegExp(`(?:${boundry(e)}${v4}${boundry(e)})|(?:${boundry(e)}${v6}${boundry(e)})`,"g");ipRegex.v4=e=>e&&e.exact?v4exact:new RegExp(`${boundry(e)}${v4}${boundry(e)}`,"g");ipRegex.v6=e=>e&&e.exact?v6exact:new RegExp(`${boundry(e)}${v6}${boundry(e)}`,"g");var ipaddr$1={exports:{}};(function(e){(function(t){const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp(`^${r}\\.${r}\\.${r}\\.${r}$`,"i"),threeOctet:new RegExp(`^${r}\\.${r}\\.${r}$`,"i"),twoOctet:new RegExp(`^${r}\\.${r}$`,"i"),longValue:new RegExp(`^${r}$`,"i")},o=new RegExp("^0[0-7]+$","i"),a=new RegExp("^0x[a-f0-9]+$","i"),l="%[0-9a-z]{1,}",c="(?:[0-9a-f]+::?)+",u={zoneIndex:new RegExp(l,"i"),native:new RegExp(`^(::)?(${c})?([0-9a-f]+)?(::)?(${l})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${r}\\.${r}\\.${r}\\.${r}(${l})?)$`,"i"),transitional:new RegExp(`^((?:${c})|(?:::)(?:${c})?)${r}\\.${r}\\.${r}\\.${r}(${l})?$`,"i")};function _(k,T){if(k.indexOf("::")!==k.lastIndexOf("::"))return null;let O=0,$=-1,D=(k.match(u.zoneIndex)||[])[0],N,H;for(D&&(D=D.substring(1),k=k.replace(/%.+$/,""));($=k.indexOf(":",$+1))>=0;)O++;if(k.substr(0,2)==="::"&&O--,k.substr(-2,2)==="::"&&O--,O>T)return null;for(H=T-O,N=":";H--;)N+="0:";return k=k.replace("::",N),k[0]===":"&&(k=k.slice(1)),k[k.length-1]===":"&&(k=k.slice(0,-1)),T=function(){const ie=k.split(":"),ue=[];for(let de=0;de0;){if(N=O-$,N<0&&(N=0),k[D]>>N!==T[D]>>N)return!1;$-=O,D+=1}return!0}function x(k){if(a.test(k))return parseInt(k,16);if(k[0]==="0"&&!isNaN(parseInt(k[1],10))){if(o.test(k))return parseInt(k,8);throw new Error(`ipaddr: cannot parse ${k} as octal`)}return parseInt(k,10)}function E(k,T){for(;k.length=0;D-=1)if(N=this.octets[D],N in $){if(H=$[N],O&&H!==0)return null;H!==8&&(O=!0),T+=H}else return null;return 32-T},k.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},k.prototype.toByteArray=function(){return this.octets.slice(0)},k.prototype.toIPv4MappedAddress=function(){return I.IPv6.parse(`::ffff:${this.toString()}`)},k.prototype.toNormalizedString=function(){return this.toString()},k.prototype.toString=function(){return this.octets.join(".")},k}(),I.IPv4.broadcastAddressFromCIDR=function(k){try{const T=this.parseCIDR(k),O=T[0].toByteArray(),$=this.subnetMaskFromPrefixLength(T[1]).toByteArray(),D=[];let N=0;for(;N<4;)D.push(parseInt(O[N],10)|parseInt($[N],10)^255),N++;return new this(D)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.isIPv4=function(k){return this.parser(k)!==null},I.IPv4.isValid=function(k){try{return new this(this.parser(k)),!0}catch{return!1}},I.IPv4.isValidFourPartDecimal=function(k){return!!(I.IPv4.isValid(k)&&k.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},I.IPv4.networkAddressFromCIDR=function(k){let T,O,$,D,N;try{for(T=this.parseCIDR(k),$=T[0].toByteArray(),N=this.subnetMaskFromPrefixLength(T[1]).toByteArray(),D=[],O=0;O<4;)D.push(parseInt($[O],10)&parseInt(N[O],10)),O++;return new this(D)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.parse=function(k){const T=this.parser(k);if(T===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(T)},I.IPv4.parseCIDR=function(k){let T;if(T=k.match(/^(.+)\/(\d+)$/)){const O=parseInt(T[2]);if(O>=0&&O<=32){const $=[this.parse(T[1]),O];return Object.defineProperty($,"toString",{value:function(){return this.join("/")}}),$}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},I.IPv4.parser=function(k){let T,O,$;if(T=k.match(n.fourOctet))return function(){const D=T.slice(1,6),N=[];for(let H=0;H4294967295||$<0)throw new Error("ipaddr: address outside defined range");return function(){const D=[];let N;for(N=0;N<=24;N+=8)D.push($>>N&255);return D}().reverse()}else return(T=k.match(n.twoOctet))?function(){const D=T.slice(1,4),N=[];if($=x(D[1]),$>16777215||$<0)throw new Error("ipaddr: address outside defined range");return N.push(x(D[0])),N.push($>>16&255),N.push($>>8&255),N.push($&255),N}():(T=k.match(n.threeOctet))?function(){const D=T.slice(1,5),N=[];if($=x(D[2]),$>65535||$<0)throw new Error("ipaddr: address outside defined range");return N.push(x(D[0])),N.push(x(D[1])),N.push($>>8&255),N.push($&255),N}():null},I.IPv4.subnetMaskFromPrefixLength=function(k){if(k=parseInt(k),k<0||k>32)throw new Error("ipaddr: invalid IPv4 prefix length");const T=[0,0,0,0];let O=0;const $=Math.floor(k/8);for(;O<$;)T[O]=255,O++;return $<4&&(T[$]=Math.pow(2,k%8)-1<<8-k%8),new this(T)},I.IPv6=function(){function k(T,O){let $,D;if(T.length===16)for(this.parts=[],$=0;$<=14;$+=2)this.parts.push(T[$]<<8|T[$+1]);else if(T.length===8)this.parts=T;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for($=0;$=0;H-=1)if(D=this.parts[H],D in $){if(N=$[D],O&&N!==0)return null;N!==16&&(O=!0),T+=N}else return null;return 128-T},k.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},k.prototype.toByteArray=function(){let T;const O=[],$=this.parts;for(let D=0;D<$.length;D++)T=$[D],O.push(T>>8),O.push(T&255);return O},k.prototype.toFixedLengthString=function(){const T=function(){const $=[];for(let D=0;D>8,O&255,$>>8,$&255])},k.prototype.toNormalizedString=function(){const T=function(){const $=[];for(let D=0;DD&&($=N.index,D=N[0].length);return D<0?O:`${O.substring(0,$)}::${O.substring($+D)}`},k.prototype.toString=function(){return this.toRFC5952String()},k}(),I.IPv6.broadcastAddressFromCIDR=function(k){try{const T=this.parseCIDR(k),O=T[0].toByteArray(),$=this.subnetMaskFromPrefixLength(T[1]).toByteArray(),D=[];let N=0;for(;N<16;)D.push(parseInt(O[N],10)|parseInt($[N],10)^255),N++;return new this(D)}catch(T){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${T})`)}},I.IPv6.isIPv6=function(k){return this.parser(k)!==null},I.IPv6.isValid=function(k){if(typeof k=="string"&&k.indexOf(":")===-1)return!1;try{const T=this.parser(k);return new this(T.parts,T.zoneId),!0}catch{return!1}},I.IPv6.networkAddressFromCIDR=function(k){let T,O,$,D,N;try{for(T=this.parseCIDR(k),$=T[0].toByteArray(),N=this.subnetMaskFromPrefixLength(T[1]).toByteArray(),D=[],O=0;O<16;)D.push(parseInt($[O],10)&parseInt(N[O],10)),O++;return new this(D)}catch(H){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${H})`)}},I.IPv6.parse=function(k){const T=this.parser(k);if(T.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(T.parts,T.zoneId)},I.IPv6.parseCIDR=function(k){let T,O,$;if((O=k.match(/^(.+)\/(\d+)$/))&&(T=parseInt(O[2]),T>=0&&T<=128))return $=[this.parse(O[1]),T],Object.defineProperty($,"toString",{value:function(){return this.join("/")}}),$;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},I.IPv6.parser=function(k){let T,O,$,D,N,H;if($=k.match(u.deprecatedTransitional))return this.parser(`::ffff:${$[1]}`);if(u.native.test(k))return _(k,8);if(($=k.match(u.transitional))&&(H=$[6]||"",T=_($[1].slice(0,-1)+H,6),T.parts)){for(N=[parseInt($[2]),parseInt($[3]),parseInt($[4]),parseInt($[5])],O=0;O128)throw new Error("ipaddr: invalid IPv6 prefix length");const T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let O=0;const $=Math.floor(k/8);for(;O<$;)T[O]=255,O++;return $<16&&(T[$]=Math.pow(2,k%8)-1<<8-k%8),new this(T)},I.fromByteArray=function(k){const T=k.length;if(T===4)return new I.IPv4(k);if(T===16)return new I.IPv6(k);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},I.isValid=function(k){return I.IPv6.isValid(k)||I.IPv4.isValid(k)},I.parse=function(k){if(I.IPv6.isValid(k))return I.IPv6.parse(k);if(I.IPv4.isValid(k))return I.IPv4.parse(k);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},I.parseCIDR=function(k){try{return I.IPv6.parseCIDR(k)}catch{try{return I.IPv4.parseCIDR(k)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},I.process=function(k){const T=this.parse(k);return T.kind()==="ipv6"&&T.isIPv4MappedAddress()?T.toIPv4Address():T},I.subnetMatch=function(k,T,O){let $,D,N,H;O==null&&(O="unicast");for(D in T)if(Object.prototype.hasOwnProperty.call(T,D)){for(N=T[D],N[0]&&!(N[0]instanceof Array)&&(N=[N]),$=0;$new Netmask_1(e));function ipv4_check(e){for(let t of NETMASK_RANGES)if(t.contains(e))return!0;return!1}function ipv6_check(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}const is_ip_private=e=>{if(is_valid(e)){const t=parse$6(e);if(t.kind()==="ipv4")return ipv4_check(t.toNormalizedString());if(t.kind()==="ipv6")return ipv6_check(e)}else if(isIP(e)&&ipRegex.v6().test(e))return ipv6_check(e)};function connectionGater(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{const r=t.stringTuples();return r[0][0]===4||r[0][0]===41?Boolean(is_ip_private(`${r[0][1]}`)):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}const toParts=e=>e.toString().split("/").slice(1),func=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),literal=e=>({match:t=>func(r=>r===e).match(t),pattern:e}),string=()=>({match:e=>func(t=>typeof t=="string").match(e),pattern:"{string}"}),number$1=()=>({match:e=>func(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),peerId=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{base58btc$1.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),certhash=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{base64url$1.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),optional=e=>({match:t=>{const r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),or=(...e)=>({match:t=>{let r;for(const n of e){const o=n.match(t);o!==!1&&(r==null||o.lengtht.pattern).join(", ")})`}),and=(...e)=>({match:t=>{for(const r of e){const n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function fmt(...e){function t(o){let a=toParts(o);for(const l of e){const c=l.match(a);if(c===!1)return!1;a=c}return a}function r(o){return t(o)!==!1}function n(o){const a=t(o);return a===!1?!1:a.length===0}return{matches:r,exactMatch:n}}const _DNS4=and(literal("dns4"),string()),_DNS6=and(literal("dns6"),string()),_DNSADDR=and(literal("dnsaddr"),string()),_DNS=and(literal("dns"),string());fmt(or(_DNS,_DNSADDR,_DNS4,_DNS6));const _IP4=and(literal("ip4"),func(isIPv4)),_IP6=and(literal("ip6"),func(isIPv6)),_IP=or(_IP4,_IP6),IP_OR_DOMAIN=or(_IP,_DNS,_DNS4,_DNS6,_DNSADDR),_TCP=and(IP_OR_DOMAIN,literal("tcp"),number$1()),_UDP=and(IP_OR_DOMAIN,literal("udp"),number$1()),TCP_OR_UDP=or(_TCP,_UDP),_QUIC=and(_UDP,literal("quic")),_QUICV1=and(_UDP,literal("quic-v1")),QUIC_V0_OR_V1=or(_QUIC,_QUICV1),_WEB=or(IP_OR_DOMAIN,_TCP,_UDP,_QUIC,_QUICV1),_WebSockets=or(and(_WEB,literal("ws"),optional(peerId()))),_WebSocketsSecure=or(and(_WEB,literal("wss"),optional(peerId())),and(_WEB,literal("tls"),literal("ws"),optional(peerId()))),_WebRTCDirect=and(TCP_OR_UDP,literal("webrtc-direct"),certhash(),optional(certhash()),optional(peerId())),_WebTransport=and(_QUICV1,literal("webtransport"),certhash(),certhash(),optional(peerId())),_P2P=or(_WebSockets,_WebSocketsSecure,and(_TCP,optional(peerId())),and(QUIC_V0_OR_V1,optional(peerId())),and(IP_OR_DOMAIN,optional(peerId())),_WebRTCDirect,_WebTransport,peerId()),_Circuit=and(_P2P,literal("p2p-circuit"),peerId()),Circuit=fmt(_Circuit);or(and(_P2P,literal("p2p-circuit"),literal("webrtc"),peerId()),and(_P2P,literal("webrtc"),optional(peerId())),literal("webrtc"));function isPrivate(e){try{const{address:t}=e.nodeAddress();return Boolean(is_ip_private(t))}catch{return!0}}function publicAddressesFirst(e,t){const r=isPrivate(e.multiaddr),n=isPrivate(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function certifiedAddressesFirst(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function circuitRelayAddressesLast(e,t){const r=Circuit.exactMatch(e.multiaddr),n=Circuit.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function defaultAddressSort(e,t){const r=publicAddressesFirst(e,t);if(r!==0)return r;const n=circuitRelayAddressesLast(e,t);return n!==0?n:certifiedAddressesFirst(e,t)}var s$3=1e3,m$4=s$3*60,h$4=m$4*60,d$5=h$4*24,w$2=d$5*7,y$3=d$5*365.25,ms$3=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$5(e);if(r==="number"&&isFinite(e))return t.long?fmtLong$3(e):fmtShort$3(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$5(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$3;case"weeks":case"week":case"w":return r*w$2;case"days":case"day":case"d":return r*d$5;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$4;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$4;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$3(e){var t=Math.abs(e);return t>=d$5?Math.round(e/d$5)+"d":t>=h$4?Math.round(e/h$4)+"h":t>=m$4?Math.round(e/m$4)+"m":t>=s$3?Math.round(e/s$3)+"s":e+"ms"}function fmtLong$3(e){var t=Math.abs(e);return t>=d$5?plural$3(e,t,d$5,"day"):t>=h$4?plural$3(e,t,h$4,"hour"):t>=m$4?plural$3(e,t,m$4,"minute"):t>=s$3?plural$3(e,t,s$3,"second"):e+" ms"}function plural$3(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}var receptacle=Receptacle,toMS=ms$3,cache$1=Receptacle.prototype,counter=new Date%1e9;function getUID(){return(Math.random()*1e9>>>0)+counter++}function Receptacle(e){e=e||{},this.id=e.id||getUID(),this.max=e.max||1/0,this.items=e.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(e.lastModified||new Date);for(var t,r,n=this.items.length;n--;)t=this.items[n],r=new Date(t.expires)-new Date,this._lookup[t.key]=t,r>0?this.expire(t.key,r):r<=0&&this.delete(t.key)}cache$1.has=function(e){return e in this._lookup};cache$1.get=function(e){if(!this.has(e))return null;var t=this._lookup[e];return t.refresh&&this.expire(e,t.refresh),this.items.splice(this.items.indexOf(t),1),this.items.push(t),t.value};cache$1.meta=function(e){if(!this.has(e))return null;var t=this._lookup[e];return"meta"in t?t.meta:null};cache$1.set=function(e,t,r){var n=this._lookup[e],o=this._lookup[e]={key:e,value:t};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,o)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(o),this.size++),r&&("ttl"in r&&this.expire(e,r.ttl),"meta"in r&&(o.meta=r.meta),r.refresh&&(o.refresh=r.ttl)),this};cache$1.delete=function(e){var t=this._lookup[e];return t?(this.lastModified=new Date,this.items.splice(this.items.indexOf(t),1),clearTimeout(t.timeout),delete this._lookup[e],this.size--,this):!1};cache$1.expire=function(e,t){var r=t||0,n=this._lookup[e];if(!n)return this;if(typeof r=="string"&&(r=toMS(t)),typeof r!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),r),n.expires=Number(new Date)+r,this};cache$1.clear=function(){for(var e=this.items.length;e--;)this.delete(this.items[e].key);return this};cache$1.toJSON=function(){for(var e=new Array(this.items.length),t,r=e.length;r--;)t=this.items[r],e[r]={key:t.key,meta:t.meta,value:t.value,expires:t.expires,refresh:t.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:e}};const globalFetch=globalThis.fetch,globalHeaders=globalThis.Headers;function buildResource(e,t,r){return`${e}?name=${t}&type=${r}`}async function request(e,t){return await(await globalFetch(e,{headers:new globalHeaders({accept:"application/dns-json"}),signal:t})).json()}function getCacheKey(e,t){return`${t}_${e}`}const log$m=Object.assign(debug$9("dns-over-http-resolver"),{error:debug$9("dns-over-http-resolver:error")});class Resolver{constructor(t={}){this._cache=new receptacle({max:t?.maxCache??100}),this._TXTcache=new receptacle({max:t?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=t.request??request,this._abortControllers=[]}cancel(){this._abortControllers.forEach(t=>t.abort())}getServers(){return this._servers}_getShuffledServers(){const t=[...this._servers];for(let r=t.length-1;r>0;r--){const n=Math.floor(Math.random()*r),o=t[r];t[r]=t[n],t[n]=o}return t}setServers(t){this._servers=t}async resolve(t,r="A"){switch(r){case"A":return await this.resolve4(t);case"AAAA":return await this.resolve6(t);case"TXT":return await this.resolveTxt(t);default:throw new Error(`${r} is not supported`)}}async resolve4(t){const r="A",n=this._cache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>b.data),_=Math.min(...c.Answer.map(b=>b.TTL));return this._cache.set(getCacheKey(t,r),u,{ttl:_}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolve6(t){const r="AAAA",n=this._cache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>b.data),_=Math.min(...c.Answer.map(b=>b.TTL));return this._cache.set(getCacheKey(t,r),u,{ttl:_}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolveTxt(t){const r="TXT",n=this._TXTcache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>[b.data.replace(/['"]+/g,"")]),_=Math.min(...c.Answer.map(b=>b.TTL));return this._TXTcache.set(getCacheKey(t,r),u,{ttl:_}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const{code:dnsaddrCode}=getProtocol("dnsaddr");async function dnsaddrResolver(e,t={}){const r=new Resolver;t.signal!=null&&t.signal.addEventListener("abort",()=>{r.cancel()});const n=e.getPeerId(),[,o]=e.stringTuples().find(([c])=>c===dnsaddrCode)??[];if(o==null)throw new Error("No hostname found in multiaddr");let l=(await r.resolveTxt(`_dnsaddr.${o}`)).flat().map(c=>c.split("=")[1]).filter(Boolean);return n!=null&&(l=l.filter(c=>c.includes(n))),l}var messages$1;(function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.DHT_DISABLED="DHT is not available",e.PUBSUB_DISABLED="PubSub is not available",e.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",e.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"})(messages$1||(messages$1={}));var codes;(function(e){e.DHT_DISABLED="ERR_DHT_DISABLED",e.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",e.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",e.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",e.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",e.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",e.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e.ERR_DIALED_SELF="ERR_DIALED_SELF",e.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e.ERR_INVALID_KEY="ERR_INVALID_KEY",e.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_PEER="ERR_INVALID_PEER",e.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e.ERR_NOT_FOUND="ERR_NOT_FOUND",e.ERR_TIMEOUT="ERR_TIMEOUT",e.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e.ERR_FIND_SELF="ERR_FIND_SELF",e.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",e.ERR_INVALID_CMS="ERR_INVALID_CMS",e.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e.ERR_NO_KEY="ERR_NO_KEY",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(codes||(codes={}));const DefaultConfig={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:dnsaddrResolver},addressSorter:defaultAddressSort},transportManager:{faultTolerance:FaultTolerance.FATAL_ALL}};function validateConfig(e){const t=mergeOptions(DefaultConfig,e);if(t.transports==null||t.transports.length<1)throw new CodeError(messages$1.ERR_TRANSPORTS_REQUIRED,codes.ERR_TRANSPORTS_REQUIRED);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new CodeError(messages$1.ERR_PROTECTOR_REQUIRED,codes.ERR_PROTECTOR_REQUIRED);return t}const KEEP_ALIVE="keep-alive",log$l=logger("libp2p:get-peer");function getPeerAddress(e){if(isPeerId(e))return{peerId:e,multiaddrs:[]};Array.isArray(e)||(e=[e]);let t;if(e.length>0){const r=e[0].getPeerId();t=r==null?void 0:peerIdFromString(r),e.forEach(n=>{if(!isMultiaddr(n))throw log$l.error("multiaddr %s was invalid",n),new CodeError("Invalid Multiaddr",codes.ERR_INVALID_MULTIADDR);const o=n.getPeerId();if(o==null){if(t!=null)throw new CodeError("Multiaddrs must all have the same peer id or have no peer id",codes.ERR_INVALID_PARAMETERS)}else{const a=peerIdFromString(o);if(t==null||!t.equals(a))throw new CodeError("Multiaddrs must all have the same peer id or have no peer id",codes.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}function lowerBound(e,t,r){let n=0,o=e.length;for(;o>0;){const a=Math.trunc(o/2);let l=n+a;r(e[l],t)<=0?(n=++l,o-=a+1):o=a}return n}var Ur;class PeerPriorityQueue{constructor(){_r(this,Ur,[])}enqueue(t,r){const n=r?.peerId,o=r?.priority??0;if(n==null)throw new CodeError("missing peer id",codes.ERR_INVALID_PARAMETERS);const a={priority:o,peerId:n,run:t};if(this.size>0&&Jt(this,Ur)[this.size-1].priority>=o){Jt(this,Ur).push(a);return}const l=lowerBound(Jt(this,Ur),a,(c,u)=>u.priority-c.priority);Jt(this,Ur).splice(l,0,a)}dequeue(){return Jt(this,Ur).shift()?.run}filter(t){if(t.peerId!=null){const r=t.peerId;return Jt(this,Ur).filter(n=>r.equals(n.peerId)).map(n=>n.run)}return Jt(this,Ur).filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return Jt(this,Ur).length}}Ur=new WeakMap;class PeerJobQueue extends PQueue{constructor(t={}){super({...t,queueClass:PeerPriorityQueue})}hasJob(t){return this.sizeBy({peerId:t})>0}}const DIAL_TIMEOUT=3e4,INBOUND_UPGRADE_TIMEOUT=3e4,MAX_PEER_ADDRS_TO_DIAL=25,MAX_PARALLEL_DIALS_PER_PEER=1,AUTO_DIAL_INTERVAL=5e3,AUTO_DIAL_CONCURRENCY=25,AUTO_DIAL_PRIORITY=0,AUTO_DIAL_MAX_QUEUE_LENGTH=100,AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE=10,INBOUND_CONNECTION_THRESHOLD=5,MAX_INCOMING_PENDING_CONNECTIONS=10,LAST_DIAL_FAILURE_KEY="last-dial-failure",MIN_CONNECTIONS=5,MAX_CONNECTIONS=100,MAX_PARALLEL_DIALS=50,AUTO_DIAL_PEER_RETRY_THRESHOLD=1e3*60*7,log$k=logger("libp2p:connection-manager:auto-dial"),defaultOptions$3={minConnections:MIN_CONNECTIONS,maxQueueLength:AUTO_DIAL_MAX_QUEUE_LENGTH,autoDialConcurrency:AUTO_DIAL_CONCURRENCY,autoDialPriority:AUTO_DIAL_PRIORITY,autoDialInterval:AUTO_DIAL_INTERVAL,autoDialPeerRetryThreshold:AUTO_DIAL_PEER_RETRY_THRESHOLD,autoDialDiscoveredPeersDebounce:AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE};class AutoDial{constructor(t,r){Ye(this,"connectionManager");Ye(this,"peerStore");Ye(this,"queue");Ye(this,"minConnections");Ye(this,"autoDialPriority");Ye(this,"autoDialIntervalMs");Ye(this,"autoDialMaxQueueLength");Ye(this,"autoDialPeerRetryThresholdMs");Ye(this,"autoDialDiscoveredPeersDebounce");Ye(this,"autoDialInterval");Ye(this,"started");Ye(this,"running");this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.minConnections=r.minConnections??defaultOptions$3.minConnections,this.autoDialPriority=r.autoDialPriority??defaultOptions$3.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??defaultOptions$3.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??defaultOptions$3.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??defaultOptions$3.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??defaultOptions$3.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new PeerJobQueue({concurrency:r.autoDialConcurrency??defaultOptions$3.autoDialConcurrency}),this.queue.addListener("error",o=>{log$k.error("error during auto-dial",o)}),t.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{log$k.error(o)})});let n;t.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{log$k.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(t=>{log$k.error("error while autodialing",t)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(t=>{log$k.error("error while autodialing",t)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;const t=this.connectionManager.getConnectionsMap(),r=t.size;if(r>=this.minConnections){this.minConnections>0&&log$k.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){log$k("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){log$k("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,log$k("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);const n=new PeerSet(this.connectionManager.getDialQueue().map(_=>_.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[_=>_.addresses.length===0?(log$k.trace("not autodialing %p because they have no addresses"),!1):t.has(_.id)?(log$k.trace("not autodialing %p because they are already connected"),!1):n.has(_.id)?(log$k.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(_.id)?(log$k.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),a=o.sort(()=>Math.random()>.5?1:-1),l=new PeerMap;for(const _ of a)l.has(_.id)||l.set(_.id,[..._.tags.values()].reduce((b,x)=>b+x.value,0));const u=a.sort((_,b)=>{const x=l.get(_.id)??0,E=l.get(b.id)??0;return x>E?-1:x{const b=_.metadata.get(LAST_DIAL_FAILURE_KEY);if(b==null)return!0;const x=parseInt(toString$5(b));return isNaN(x)?!0:Date.now()-x>this.autoDialPeerRetryThresholdMs});log$k("selected %d/%d peers to dial",u.length,o.length);for(const _ of u)this.queue.add(async()=>{const b=this.connectionManager.getConnectionsMap().size;if(b>=this.minConnections){log$k("got enough connections now %d/%d",b,this.minConnections),this.queue.clear();return}log$k("connecting to a peerStore stored peer %p",_.id),await this.connectionManager.openConnection(_.id,{priority:this.autoDialPriority})},{peerId:_.id}).catch(b=>{log$k.error("could not connect to peerStore stored peer",b)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(_=>{log$k.error("error while autodialing",_)})},this.autoDialIntervalMs))}}const log$j=logger("libp2p:connection-manager:connection-pruner"),defaultOptions$2={maxConnections:MAX_CONNECTIONS,allow:[]};class ConnectionPruner{constructor(t,r={}){Ye(this,"maxConnections");Ye(this,"connectionManager");Ye(this,"peerStore");Ye(this,"allow");Ye(this,"events");this.maxConnections=r.maxConnections??defaultOptions$2.maxConnections,this.allow=r.allow??defaultOptions$2.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,t.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{log$j.error(n)})})}async maybePruneConnections(){const t=this.connectionManager.getConnections(),r=t.length,n=Math.max(r-this.maxConnections,0);if(log$j("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;log$j("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);const o=new PeerMap;for(const c of t){const u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{const _=await this.peerStore.get(u);o.set(u,[..._.tags.values()].reduce((b,x)=>b+x.value,0))}catch(_){_.code!=="ERR_NOT_FOUND"&&log$j.error("error loading peer tags",_)}}}const a=t.sort((c,u)=>{const _=o.get(c.remotePeer)??0,b=o.get(u.remotePeer)??0;if(_>b)return 1;if(_E?-1:0}),l=[];for(const c of a)if(log$j("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(_=>c.remoteAddr.toString().startsWith(_.toString()))||l.push(c),l.length===n)break;await Promise.all(l.map(async c=>{try{await c.close()}catch(u){log$j.error(u)}})),this.events.safeDispatchEvent("connection:prune",{detail:l})}}function anySignal(e){const t=new globalThis.AbortController;function r(){t.abort();for(const a of e)a?.removeEventListener!=null&&a.removeEventListener("abort",r)}for(const a of e){if(a?.aborted===!0){r();break}a?.addEventListener!=null&&a.addEventListener("abort",r)}function n(){for(const a of e)a?.removeEventListener!=null&&a.removeEventListener("abort",r)}const o=t.signal;return o.clear=n,o}const log$i=logger("libp2p:connection-manager:utils");async function resolveMultiaddrs(e,t){if(!e.protoNames().includes("dnsaddr"))return[e];const n=await resolveRecord(e,t),l=(await Promise.all(n.map(async c=>resolveMultiaddrs(c,t)))).flat().reduce((c,u)=>(c.find(_=>_.equals(u))==null&&c.push(u),c),[]);return log$i("resolved %s to",e,l.map(c=>c.toString())),l}async function resolveRecord(e,t){try{return e=multiaddr(e.toString()),await e.resolve(t)}catch(r){return log$i.error(`multiaddr ${e.toString()} could not be resolved`,r),[]}}function combineSignals(...e){const t=[];for(const n of e)if(n!=null){try{events$1.exports.setMaxListeners?.(1/0,n)}catch{}t.push(n)}const r=anySignal(t);try{events$1.exports.setMaxListeners?.(1/0,r)}catch{}return r}const log$h=logger("libp2p:connection-manager:dial-queue"),defaultOptions$1={addressSorter:defaultAddressSort,maxParallelDials:MAX_PARALLEL_DIALS,maxPeerAddrsToDial:MAX_PEER_ADDRS_TO_DIAL,maxParallelDialsPerPeer:MAX_PARALLEL_DIALS_PER_PEER,dialTimeout:DIAL_TIMEOUT,resolvers:{dnsaddr:dnsaddrResolver}};class DialQueue{constructor(t,r={}){Ye(this,"pendingDials");Ye(this,"queue");Ye(this,"peerId");Ye(this,"peerStore");Ye(this,"connectionGater");Ye(this,"transportManager");Ye(this,"addressSorter");Ye(this,"maxPeerAddrsToDial");Ye(this,"maxParallelDialsPerPeer");Ye(this,"dialTimeout");Ye(this,"inProgressDialCount");Ye(this,"pendingDialCount");Ye(this,"shutDownController");this.addressSorter=r.addressSorter??defaultOptions$1.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??defaultOptions$1.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??defaultOptions$1.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??defaultOptions$1.dialTimeout,this.peerId=t.peerId,this.peerStore=t.peerStore,this.connectionGater=t.connectionGater,this.transportManager=t.transportManager,this.shutDownController=new AbortController;try{events$1.exports.setMaxListeners?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=t.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=t.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(const[n,o]of Object.entries(r.resolvers??{}))resolvers.set(n,o);this.queue=new PQueue({concurrency:r.maxParallelDials??defaultOptions$1.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{log$h.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(t,r={}){const{peerId:n,multiaddrs:o}=getPeerAddress(t),a=o.map(b=>({multiaddr:b,isCertified:!1})),l=this.createDialAbortControllers(r.signal);let c;try{c=await this.calculateMultiaddrs(n,a,{...r,signal:l})}catch(b){throw l.clear(),b}const u=this.pendingDials.find(b=>!!(b.peerId!=null&&n!=null&&b.peerId.equals(n)||c.map(({multiaddr:x})=>x.toString()).join()===b.multiaddrs.map(x=>x.toString()).join()));if(u!=null)return log$h("joining existing dial target for %p",n),l.clear(),u.promise;log$h("creating dial target for",c.map(({multiaddr:b})=>b.toString()));const _={id:randomId(),status:"queued",peerId:n,multiaddrs:c.map(({multiaddr:b})=>b)};return _.promise=this.performDial(_,{...r,signal:l}).finally(()=>{this.pendingDials=this.pendingDials.filter(b=>b.id!==_.id),l.clear()}).catch(async b=>{if(log$h.error("dial failed to %s",_.multiaddrs.map(x=>x.toString()).join(", "),b),n!=null)try{await this.peerStore.patch(n,{metadata:{[LAST_DIAL_FAILURE_KEY]:fromString$1(Date.now().toString())}})}catch(x){log$h.error("could not update last dial failure key for %p",n,x)}throw l.aborted?new CodeError(b.message,codes.ERR_TIMEOUT):b}),this.pendingDials.push(_),_.promise}createDialAbortControllers(t){const r=anySignal([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,t]);try{events$1.exports.setMaxListeners?.(1/0,r)}catch{}return r}async calculateMultiaddrs(t,r=[],n={}){if(t!=null){if(this.peerId.equals(t))throw new CodeError("Tried to dial self",codes.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(t)===!0)throw new CodeError("The dial request is blocked by gater.allowDialPeer",codes.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){log$h("loading multiaddrs for %p",t);try{const b=await this.peerStore.get(t);r.push(...b.addresses),log$h("loaded multiaddrs for %p",t,r.map(({multiaddr:x})=>x.toString()))}catch(b){if(b.code!==codes.ERR_NOT_FOUND)throw b}}}const o=(await Promise.all(r.map(async b=>{const x=await resolveMultiaddrs(b.multiaddr,n);return x.length===1&&x[0].equals(b.multiaddr)?b:x.map(E=>({multiaddr:E,isCertified:!1}))}))).flat(),a=o.filter(b=>{if(this.transportManager.transportForMultiaddr(b.multiaddr)==null)return!1;const x=b.multiaddr.getPeerId();return t!=null&&x!=null?t.equals(x):!0}),l=new Map;for(const b of a){const x=b.multiaddr.toString(),E=l.get(x);if(E!=null){E.isCertified=E.isCertified||b.isCertified||!1;continue}l.set(x,b)}let c=[...l.values()];if((c.length===0||c.length>this.maxPeerAddrsToDial)&&(log$h("addresses for %p before filtering",t??"unknown peer",o.map(({multiaddr:b})=>b.toString())),log$h("addresses for %p after filtering",t??"unknown peer",c.map(({multiaddr:b})=>b.toString()))),c.length===0)throw new CodeError("The dial request has no valid addresses",codes.ERR_NO_VALID_ADDRESSES);if(c.length>this.maxPeerAddrsToDial)throw new CodeError("dial with more addresses than allowed",codes.ERR_TOO_MANY_ADDRESSES);if(t!=null){const b=`/p2p/${t.toString()}`;c=c.map(x=>{const E=x.multiaddr.getPeerId();return x.multiaddr.protos().pop()?.path===!0?x:E!==t.toString()?{multiaddr:x.multiaddr.encapsulate(b),isCertified:x.isCertified}:x})}const u=[];for(const b of c)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(b.multiaddr)||u.push(b);const _=u.sort(this.addressSorter);if(_.length===0)throw new CodeError("The connection gater denied all addresses in the dial request",codes.ERR_NO_VALID_ADDRESSES);return _}async performDial(t,r={}){const n=t.multiaddrs.map(()=>new AbortController);try{const o=new PQueue({concurrency:this.maxParallelDialsPerPeer});o.on("error",l=>{log$h.error("error dialling",l)});const a=await Promise.any(t.multiaddrs.map(async(l,c)=>{const u=n[c];if(u==null)throw new CodeError("dialAction did not come with an AbortController",codes.ERR_INVALID_PARAMETERS);const _=combineSignals(u.signal,r.signal);_.addEventListener("abort",()=>{log$h("dial to %a aborted",l)});const b=pDefer();return await o.add(async()=>{if(_.aborted){log$h("dial to %a was aborted before reaching the head of the peer dial queue",l),b.reject(new AbortError$4);return}await this.queue.add(async()=>{try{if(_.aborted){log$h("dial to %a was aborted before reaching the head of the dial queue",l),b.reject(new AbortError$4);return}t.status="active";const x=await this.transportManager.dial(l,{...r,signal:_});if(u.signal.aborted){log$h("multiple dials succeeded, closing superfluous connection"),x.close().catch(E=>{log$h.error("error closing superfluous connection",E)}),b.reject(new AbortError$4);return}n[c]=void 0,n.forEach(E=>{E!==void 0&&E.abort()}),log$h("dial to %a succeeded",l),b.resolve(x)}catch(x){log$h.error("error during dial of %a",l,x),b.reject(x)}},{...r,signal:_}).catch(x=>{b.reject(x)})},{signal:_}).catch(x=>{b.reject(x)}).finally(()=>{_.clear()}),b.promise}));if(a==null)throw new CodeError("successful dial led to empty object returned from peer dial queue",codes.ERR_TRANSPORT_DIAL_FAILED);return t.status="success",a}catch(o){throw t.status="error",t.multiaddrs.length===1&&o.name==="AggregateError"?o.errors[0]:o}}}function randomId(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}const log$g=logger("libp2p:connection-manager"),DEFAULT_DIAL_PRIORITY=50,defaultOptions={minConnections:MIN_CONNECTIONS,maxConnections:MAX_CONNECTIONS,inboundConnectionThreshold:INBOUND_CONNECTION_THRESHOLD,maxIncomingPendingConnections:MAX_INCOMING_PENDING_CONNECTIONS,autoDialConcurrency:AUTO_DIAL_CONCURRENCY,autoDialPriority:AUTO_DIAL_PRIORITY,autoDialMaxQueueLength:AUTO_DIAL_MAX_QUEUE_LENGTH};class DefaultConnectionManager{constructor(t,r={}){Ye(this,"started");Ye(this,"connections");Ye(this,"allow");Ye(this,"deny");Ye(this,"maxIncomingPendingConnections");Ye(this,"incomingPendingConnections");Ye(this,"maxConnections");Ye(this,"dialQueue");Ye(this,"autoDial");Ye(this,"connectionPruner");Ye(this,"inboundConnectionRateLimiter");Ye(this,"peerStore");Ye(this,"metrics");Ye(this,"events");this.maxConnections=r.maxConnections??defaultOptions.maxConnections;const n=r.minConnections??defaultOptions.minConnections;if(this.maxConnectionsmultiaddr(o)),this.deny=(r.deny??[]).map(o=>multiaddr(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??defaultOptions.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new rateLimiterFlexible.RateLimiterMemory({points:r.inboundConnectionThreshold??defaultOptions.inboundConnectionThreshold,duration:1}),this.autoDial=new AutoDial({connectionManager:this,peerStore:t.peerStore,events:t.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??defaultOptions.autoDialConcurrency,autoDialPriority:r.autoDialPriority??defaultOptions.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??defaultOptions.autoDialMaxQueueLength}),this.connectionPruner=new ConnectionPruner({connectionManager:this,peerStore:t.peerStore,events:t.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new DialQueue({peerId:t.peerId,metrics:t.metrics,peerStore:t.peerStore,transportManager:t.transportManager,connectionGater:t.connectionGater},{addressSorter:r.addressSorter??defaultAddressSort,maxParallelDials:r.maxParallelDials??MAX_PARALLEL_DIALS,maxPeerAddrsToDial:r.maxPeerAddrsToDial??MAX_PEER_ADDRS_TO_DIAL,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??MAX_PARALLEL_DIALS_PER_PEER,dialTimeout:r.dialTimeout??DIAL_TIMEOUT,resolvers:r.resolvers??{dnsaddr:dnsaddrResolver}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const t={inbound:0,outbound:0};for(const r of this.connections.values())for(const n of r)n.direction==="inbound"?t.inbound++:t.outbound++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const t={};for(const r of this.connections.values())for(const n of r)for(const o of n.streams){const a=`${o.direction} ${o.protocol??"unnegotiated"}`;t[a]=(t[a]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const t={};for(const n of this.connections.values())for(const o of n){const a={};for(const l of o.streams){const c=`${l.direction} ${l.protocol??"unnegotiated"}`;a[c]=(a[c]??0)+1}for(const[l,c]of Object.entries(a))t[l]=t[l]??[],t[l].push(c)}const r={};for(let[n,o]of Object.entries(t)){o=o.sort((l,c)=>l-c);const a=Math.floor(o.length*.9);r[n]=o[a]}return r}}),this.autoDial.start(),this.started=!0,log$g("started")}async afterStart(){Promise.resolve().then(async()=>{const t=await this.peerStore.all({filters:[r=>r.tags.has(KEEP_ALIVE)]});await Promise.all(t.map(async r=>{await this.openConnection(r.id).catch(n=>{log$g.error(n)})}))}).catch(t=>{log$g.error(t)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();const t=[];for(const r of this.connections.values())for(const n of r)t.push((async()=>{try{await n.close()}catch(o){log$g.error(o)}})());log$g("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),log$g("stopped")}onConnect(t){this._onConnect(t).catch(r=>{log$g.error(r)})}async _onConnect(t){const{detail:r}=t;if(!this.started){await r.close();return}const n=r.remotePeer,o=this.connections.get(n);let a=!1;o!=null?o.push(r):(a=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),a&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(t){const{detail:r}=t;if(!this.started)return;const n=r.remotePeer;let o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(a=>a.id!==r.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let r=[];for(const n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(t,r={}){if(!this.isStarted())throw new CodeError("Not started",codes.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();const{peerId:n}=getPeerAddress(t);if(n!=null&&r.force!==!0){log$g("dial %p",n);const c=this.getConnections(n);if(c.length>0)return log$g("had an existing connection to %p",n),c[0]}const o=await this.dialQueue.dial(t,{...r,priority:r.priority??DEFAULT_DIAL_PRIORITY});let a=this.connections.get(o.remotePeer);a==null&&(a=[],this.connections.set(o.remotePeer,a));let l=!1;for(const c of a)c.id===o.id&&(l=!0);return l||a.push(o),o}async closeConnections(t,r={}){const n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(r)}catch(a){o.abort(a)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return log$g("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return log$g("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){const o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return log$g("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length(await t.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function uniquePeers(e){const t=new Set;return filter(e,r=>t.has(r.id.toString())?!1:(t.add(r.id.toString()),!0))}async function*requirePeers(e,t=1){let r=0;for await(const n of e)r++,yield n;if(rn.findProviders(t,r))),n=>storeAddresses(n,this.components.peerStore),n=>uniquePeers(n),n=>requirePeers(n))}async provide(t,r={}){if(this.routers.length===0)throw new CodeError("No content routers available",codes.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(t,r)}))}async put(t,r,n){if(!this.isStarted())throw new CodeError(messages$1.NOT_STARTED_YET,codes.DHT_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(t,r,n)}))}async get(t,r){if(!this.isStarted())throw new CodeError(messages$1.NOT_STARTED_YET,codes.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(t,r)))}}function isAsyncIterable(e){return e[Symbol.asyncIterator]!=null}function first(e){if(isAsyncIterable(e))return(async()=>{for await(const t of e)return t})();for(const t of e)return t}const log$f=logger("libp2p:peer-routing");class DefaultPeerRouting{constructor(t,r){Ye(this,"components");Ye(this,"routers");this.components=t,this.routers=r.routers??[]}async findPeer(t,r){if(this.routers.length===0)throw new CodeError("No peer routers available",codes.ERR_NO_ROUTERS_AVAILABLE);if(t.toString()===this.components.peerId.toString())throw new CodeError("Should not try to find self",codes.ERR_FIND_SELF);const n=await pipe(merge$1(...this.routers.map(o=>async function*(){try{yield await o.findPeer(t,r)}catch(a){log$f.error(a)}}())),o=>filter(o,Boolean),o=>storeAddresses(o,this.components.peerStore),async o=>first(o));if(n!=null)return n;throw new CodeError(messages$1.NOT_FOUND,codes.ERR_NOT_FOUND)}async*getClosestPeers(t,r){if(this.routers.length===0)throw new CodeError("No peer routers available",codes.ERR_NO_ROUTERS_AVAILABLE);yield*pipe(merge$1(...this.routers.map(n=>n.getClosestPeers(t,r))),n=>storeAddresses(n,this.components.peerStore),n=>uniquePeers(n),n=>requirePeers(n))}}const log$e=logger("libp2p:registrar"),DEFAULT_MAX_INBOUND_STREAMS=32,DEFAULT_MAX_OUTBOUND_STREAMS=64;class DefaultRegistrar{constructor(t){Ye(this,"topologies");Ye(this,"handlers");Ye(this,"components");this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){const r=this.handlers.get(t);if(r==null)throw new CodeError(`No handler registered for protocol ${t}`,codes.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(t){const r=this.topologies.get(t);return r==null?[]:[...r.values()]}async handle(t,r,n){if(this.handlers.has(t))throw new CodeError(`Handler already registered for protocol ${t}`,codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const o=mergeOptions.bind({ignoreUndefined:!0})({maxInboundStreams:DEFAULT_MAX_INBOUND_STREAMS,maxOutboundStreams:DEFAULT_MAX_OUTBOUND_STREAMS},n);this.handlers.set(t,{handler:r,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,r){if(r==null)throw new CodeError("invalid topology",codes.ERR_INVALID_PARAMETERS);const n=`${(Math.random()*1e9).toString(36)}${Date.now()}`;let o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,r),n}unregister(t){for(const[r,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(r))}_onDisconnect(t){const r=t.detail;this.components.peerStore.get(r).then(n=>{for(const o of n.protocols){const a=this.topologies.get(o);if(a!=null)for(const l of a.values())l.onDisconnect?.(r)}}).catch(n=>{n.code!==codes.ERR_NOT_FOUND&&log$e.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(t){const r=t.detail;this.components.peerStore.get(r).then(n=>{const o=this.components.connectionManager.getConnections(n.id)[0];if(o==null){log$e("peer %p connected but the connection manager did not have a connection",n);return}for(const a of n.protocols){const l=this.topologies.get(a);if(l!=null)for(const c of l.values())c.onConnect?.(r,o)}}).catch(n=>{n.code!==codes.ERR_NOT_FOUND&&log$e.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(t){const{peer:r,previous:n}=t.detail,o=(n?.protocols??[]).filter(l=>!r.protocols.includes(l)),a=r.protocols.filter(l=>!(n?.protocols??[]).includes(l));for(const l of o){const c=this.topologies.get(l);if(c!=null)for(const u of c.values())u.onDisconnect?.(r.id)}for(const l of a){const c=this.topologies.get(l);if(c!=null)for(const u of c.values()){const _=this.components.connectionManager.getConnections(r.id)[0];_!=null&&u.onConnect?.(r.id,_)}}}}class TrackedMap extends Map{constructor(r){super();Ye(this,"metric");const{name:n,metrics:o}=r;this.metric=o.registerMetric(n),this.updateComponentMetric()}set(r,n){return super.set(r,n),this.updateComponentMetric(),this}delete(r){const n=super.delete(r);return this.updateComponentMetric(),n}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function trackedMap(e){const{name:t,metrics:r}=e;let n;return r!=null?n=new TrackedMap({name:t,metrics:r}):n=new Map,n}const log$d=logger("libp2p:transports");class DefaultTransportManager{constructor(t,r={}){Ye(this,"components");Ye(this,"transports");Ye(this,"listeners");Ye(this,"faultTolerance");Ye(this,"started");this.components=t,this.started=!1,this.transports=new Map,this.listeners=trackedMap({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??FaultTolerance.FATAL_ALL}add(t){const r=t[Symbol.toStringTag];if(r==null)throw new CodeError("Transport must have a valid tag",codes.ERR_INVALID_KEY);if(this.transports.has(r))throw new CodeError(`There is already a transport with the tag ${r}`,codes.ERR_DUPLICATE_TRANSPORT);log$d("adding transport %s",r),this.transports.set(r,t),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){const t=[];for(const[r,n]of this.listeners)for(log$d("closing listeners for %s",r);n.length>0;){const o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),log$d("all listeners closed");for(const r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(t,r){const n=this.transportForMultiaddr(t);if(n==null)throw new CodeError(`No transport available for address ${String(t)}`,codes.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(t,{...r,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=codes.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let t=[];for(const r of this.listeners.values())for(const n of r)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(t){for(const r of this.transports.values())if(r.filter([t]).length>0)return r}async listen(t){if(!this.isStarted())throw new CodeError("Not started",codes.ERR_NODE_NOT_STARTED);if(t==null||t.length===0){log$d("no addresses were provided for listening, this node is dial only");return}const r=[];for(const[n,o]of this.transports.entries()){const a=o.filter(t),l=[];for(const _ of a){log$d("creating listener for %s on %a",n,_);const b=o.createListener({upgrader:this.components.upgrader});let x=this.listeners.get(n)??[];x==null&&(x=[],this.listeners.set(n,x)),x.push(b),b.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:b})}),b.addEventListener("close",()=>{const E=x.findIndex(I=>I===b);x.splice(E,1),this.components.events.safeDispatchEvent("transport:close",{detail:b})}),l.push(b.listen(_))}if(l.length===0){r.push(n);continue}if((await Promise.allSettled(l)).find(_=>_.status==="fulfilled")==null&&this.faultTolerance!==FaultTolerance.NO_FATAL)throw new CodeError(`Transport (${n}) could not listen on any available address`,codes.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){const n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===FaultTolerance.FATAL_ALL)throw new CodeError(n,codes.ERR_NO_VALID_ADDRESSES);log$d(`libp2p in dial mode only: ${n}`)}}async remove(t){log$d("removing %s",t);for(const r of this.listeners.get(t)??[])await r.close();this.transports.delete(t),this.listeners.delete(t)}async removeAll(){const t=[];for(const r of this.transports.keys())t.push(this.remove(r));await Promise.all(t)}}const PROTOCOL_ID="/multistream/1.0.0",MAX_PROTOCOL_LENGTH=1024;function reader(e){const t=async function*(){let r=yield,n=new Uint8ArrayList;for await(const o of e){if(r==null){n.append(o),r=yield n,n=new Uint8ArrayList;continue}for(n.append(o);n.length>=r;){const a=n.sublist(0,r);if(n.consume(r),r=yield a,r==null){n.length>0&&(r=yield n,n=new Uint8ArrayList);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return t.next(),t}function handshake(e){const t=pushable(),r=reader(e.source),n=pDefer();let o;const a=e.sink(async function*(){yield*t,yield*await n.promise}());return a.catch(c=>{o=c}),{reader:r,writer:t,stream:{sink:async c=>{if(o!=null){await Promise.reject(o);return}n.resolve(c),await a},source:r},rest:()=>t.end(),write:t.push,read:async()=>{const c=await r.next();if(c.value!=null)return c.value}}}const log$c=logger("libp2p:mss"),NewLine=fromString$1(` -`);function encode$1(e){const t=new Uint8ArrayList(e,NewLine);return encode$c.single(t)}function write(e,t,r={}){const n=encode$1(t);r.writeBytes===!0?e.push(n.subarray()):e.push(n)}function writeAll(e,t,r={}){const n=new Uint8ArrayList;for(const o of t)n.append(encode$1(o));r.writeBytes===!0?e.push(n.subarray()):e.push(n)}async function read(e,t){let r=1;const n={[Symbol.asyncIterator]:()=>n,next:async()=>e.next(r)};let o=n;t?.signal!=null&&(o=abortableSource(n,t.signal));const a=c=>{r=c},l=await pipe(o,c=>decode$a(c,{onLength:a,maxDataLength:MAX_PROTOCOL_LENGTH}),async c=>first(c));if(l==null||l.length===0)throw new CodeError("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(l.get(l.byteLength-1)!==NewLine[0])throw log$c.error("Invalid mss message - missing newline - %s",l.subarray()),new CodeError("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return l.sublist(0,-1)}async function readString(e,t){const r=await read(e,t);return toString$5(r.subarray())}const log$b=logger("libp2p:mss:select");async function select(e,t,r={}){t=Array.isArray(t)?[...t]:[t];const{reader:n,writer:o,rest:a,stream:l}=handshake(e),c=t.shift();if(c==null)throw new Error("At least one protocol must be specified");log$b.trace('select: write ["%s", "%s"]',PROTOCOL_ID,c);const u=fromString$1(PROTOCOL_ID),_=fromString$1(c);writeAll(o,[u,_],r);let b=await readString(n,r);if(log$b.trace('select: read "%s"',b),b===PROTOCOL_ID&&(b=await readString(n,r),log$b.trace('select: read "%s"',b)),b===c)return a(),{stream:l,protocol:c};for(const x of t){log$b.trace('select: write "%s"',x),write(o,fromString$1(x),r);const E=await readString(n,r);if(log$b.trace('select: read "%s" for "%s"',E,x),E===x)return a(),{stream:l,protocol:x}}throw a(),new CodeError("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const log$a=logger("libp2p:mss:handle");async function handle(e,t,r){t=Array.isArray(t)?t:[t];const{writer:n,reader:o,rest:a,stream:l}=handshake(e);for(;;){const c=await readString(o,r);if(log$a.trace('read "%s"',c),c===PROTOCOL_ID){log$a.trace('respond with "%s" for "%s"',PROTOCOL_ID,c),write(n,fromString$1(PROTOCOL_ID),r);continue}if(t.includes(c))return write(n,fromString$1(c),r),log$a.trace('respond with "%s" for "%s"',c,c),a(),{stream:l,protocol:c};if(c==="ls"){write(n,new Uint8ArrayList(...t.map(u=>encode$1(fromString$1(u)))),r),log$a.trace('respond with "%s" for %s',t,c);continue}write(n,fromString$1("na"),r),log$a('respond with "na" for "%s"',c)}}const symbol=Symbol.for("@libp2p/connection"),log$9=logger("libp2p:connection"),CLOSE_TIMEOUT=500;var sc,oc;class ConnectionImpl{constructor(t){Ye(this,"id");Ye(this,"remoteAddr");Ye(this,"remotePeer");Ye(this,"direction");Ye(this,"timeline");Ye(this,"multiplexer");Ye(this,"encryption");Ye(this,"status");Ye(this,"transient");Ye(this,"tags");Ye(this,"_newStream");Ye(this,"_close");Ye(this,"_abort");Ye(this,"_getStreams");Ye(this,sc,"Connection");Ye(this,oc,!0);const{remoteAddr:r,remotePeer:n,newStream:o,close:a,abort:l,getStreams:c}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.transient=t.transient??!1,this._newStream=o,this._close=a,this._abort=l,this._getStreams=c,this.tags=[]}get streams(){return this._getStreams()}async newStream(t,r){if(this.status==="closing")throw new CodeError("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new CodeError("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(t)||(t=[t]),this.transient&&r?.runOnTransientConnection!==!0)throw new CodeError("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const n=await this._newStream(t,r);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){log$9("closing connection to %a",this.remoteAddr),this.status="closing",t.signal=t?.signal??AbortSignal.timeout(CLOSE_TIMEOUT);try{events$1.exports.setMaxListeners?.(1/0,t.signal)}catch{}try{await Promise.all(this.streams.map(async r=>r.close(t))),await this._close(t),this.timeline.close=Date.now(),this.status="closed"}catch(r){log$9.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(t){log$9.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(r=>{r.abort(t)}),log$9.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}}sc=Symbol.toStringTag,oc=symbol;function createConnection(e){return new ConnectionImpl(e)}const log$8=logger("libp2p:upgrader");function findIncomingStreamLimit(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(r){if(r.code!==codes.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return DEFAULT_MAX_INBOUND_STREAMS}function findOutgoingStreamLimit(e,t,r={}){try{const{options:n}=t.getHandler(e);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==codes.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??DEFAULT_MAX_OUTBOUND_STREAMS}function countStreams(e,t,r){let n=0;return r.streams.forEach(o=>{o.direction===t&&o.protocol===e&&n++}),n}class DefaultUpgrader{constructor(t,r){Ye(this,"components");Ye(this,"connectionEncryption");Ye(this,"muxers");Ye(this,"inboundUpgradeTimeout");Ye(this,"events");this.components=t,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??INBOUND_UPGRADE_TIMEOUT,this.events=t.events}async shouldBlockConnection(t,r,n){const o=this.components.connectionGater[n];if(o!==void 0&&await o(t,r))throw new CodeError(`The multiaddr connection is blocked by gater.${n}`,codes.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(t,r){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new CodeError("connection denied",codes.ERR_CONNECTION_DENIED);let o,a,l,c,u;const _=AbortSignal.timeout(this.inboundUpgradeTimeout),b=()=>{t.abort(new CodeError("inbound upgrade timeout",codes.ERR_TIMEOUT))};_.addEventListener("abort",b,{once:!0});try{events$1.exports.setMaxListeners?.(1/0,_)}catch{}try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new CodeError("The multiaddr connection is blocked by gater.acceptConnection",codes.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(t),log$8("starting the inbound connection upgrade");let x=t;if(r?.skipProtection!==!0){const E=this.components.connectionProtector;E!=null&&(log$8("protecting the inbound connection"),x=await E.protect(t))}try{if(o=x,r?.skipEncryption!==!0){({conn:o,remotePeer:a,protocol:u}=await this._encryptInbound(x));const E={...x,...o};await this.shouldBlockConnection(a,E,"denyInboundEncryptedConnection")}else{const E=t.remoteAddr.getPeerId();if(E==null)throw new CodeError("inbound connection that skipped encryption must have a peer id",codes.ERR_INVALID_MULTIADDR);const I=peerIdFromString(E);u="native",a=I}if(l=o,r?.muxerFactory!=null)c=r.muxerFactory;else if(this.muxers.size>0){const E=await this._multiplexInbound({...x,...o},this.muxers);c=E.muxerFactory,l=E.stream}}catch(E){throw log$8.error("Failed to upgrade inbound connection",E),E}return await this.shouldBlockConnection(a,t,"denyInboundUpgradedConnection"),log$8("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:u,direction:"inbound",maConn:t,upgradedConn:l,muxerFactory:c,remotePeer:a,transient:r?.transient})}finally{_.removeEventListener("abort",b),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,r){const n=t.remoteAddr.getPeerId();let o;n!=null&&(o=peerIdFromString(n),await this.shouldBlockConnection(o,t,"denyOutboundConnection"));let a,l,c,u,_;this.components.metrics?.trackMultiaddrConnection(t),log$8("Starting the outbound connection upgrade");let b=t;if(r?.skipProtection!==!0){const x=this.components.connectionProtector;x!=null&&(b=await x.protect(t))}try{if(a=b,r?.skipEncryption!==!0){({conn:a,remotePeer:l,protocol:u}=await this._encryptOutbound(b,o));const x={...b,...a};await this.shouldBlockConnection(l,x,"denyOutboundEncryptedConnection")}else{if(o==null)throw new CodeError("Encryption was skipped but no peer id was passed",codes.ERR_INVALID_PEER);u="native",l=o}if(c=a,r?.muxerFactory!=null)_=r.muxerFactory;else if(this.muxers.size>0){const x=await this._multiplexOutbound({...b,...a},this.muxers);_=x.muxerFactory,c=x.stream}}catch(x){throw log$8.error("Failed to upgrade outbound connection",x),await t.close(x),x}return await this.shouldBlockConnection(l,t,"denyOutboundUpgradedConnection"),log$8("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:u,direction:"outbound",maConn:t,upgradedConn:c,muxerFactory:_,remotePeer:l,transient:r?.transient})}_createConnection(t){const{cryptoProtocol:r,direction:n,maConn:o,upgradedConn:a,remotePeer:l,muxerFactory:c,transient:u}=t;let _,b,x;c!=null&&(_=c.createStreamMuxer({direction:n,onIncomingStream:k=>{x!=null&&Promise.resolve().then(async()=>{const T=this.components.registrar.getProtocols(),{stream:O,protocol:$}=await handle(k,T);if(log$8("%s: incoming stream opened on %s",n,$),x==null)return;const D=findIncomingStreamLimit($,this.components.registrar);if(countStreams($,"inbound",x)===D){const H=new CodeError(`Too many inbound protocol streams for protocol "${$}" - limit ${D}`,codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw k.abort(H),H}k.source=O.source,k.sink=O.sink,k.protocol=$,await this.components.peerStore.merge(l,{protocols:[$]}),this.components.metrics?.trackProtocolStream(k,x),this._onStream({connection:x,stream:k,protocol:$})}).catch(async T=>{log$8.error(T),k.timeline.close==null&&await k.close()})}}),b=async(k,T={})=>{if(_==null)throw new CodeError("Stream is not multiplexed",codes.ERR_MUXER_UNAVAILABLE);log$8("%s: starting new stream on %s",n,k);const O=await _.newStream();try{if(T.signal==null){log$8("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",k),T.signal=AbortSignal.timeout(3e4);try{events$1.exports.setMaxListeners?.(1/0,T.signal)}catch{}}const{stream:$,protocol:D}=await select(O,k,T),N=findOutgoingStreamLimit(D,this.components.registrar,T);if(countStreams(D,"outbound",x)>=N){const ie=new CodeError(`Too many outbound protocol streams for protocol "${D}" - limit ${N}`,codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw O.abort(ie),ie}return await this.components.peerStore.merge(l,{protocols:[D]}),O.source=$.source,O.sink=$.sink,O.protocol=D,this.components.metrics?.trackProtocolStream(O,x),O}catch($){throw log$8.error("could not create new stream",$),O.timeline.close==null&&O.abort($),$.code!=null?$:new CodeError(String($),codes.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([_.sink(a.source),a.sink(_.source)]).catch(k=>{log$8.error(k)}));const E=o.timeline;o.timeline=new Proxy(E,{set:(...k)=>(x!=null&&k[1]==="close"&&k[2]!=null&&E.close==null&&(async()=>{try{x.status==="open"&&await x.close()}catch(T){log$8.error(T)}finally{this.events.safeDispatchEvent("connection:close",{detail:x})}})().catch(T=>{log$8.error(T)}),Reflect.set(...k))}),o.timeline.upgraded=Date.now();const I=()=>{throw new CodeError("connection is not multiplexed",codes.ERR_CONNECTION_NOT_MULTIPLEXED)};return x=createConnection({remoteAddr:o.remoteAddr,remotePeer:l,status:"open",direction:n,timeline:o.timeline,multiplexer:_?.protocol,encryption:r,transient:u,newStream:b??I,getStreams:()=>_!=null?_.streams:[],close:async k=>{await o.close(k),_!=null&&await _.close(k)},abort:k=>{o.abort(k),_?.abort(k)}}),this.events.safeDispatchEvent("connection:open",{detail:x}),x}_onStream(t){const{connection:r,stream:n,protocol:o}=t,{handler:a,options:l}=this.components.registrar.getHandler(o);if(r.transient&&l.runOnTransientConnection!==!0)throw new CodeError("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");a({connection:r,stream:n})}async _encryptInbound(t){const r=Array.from(this.connectionEncryption.keys());log$8("handling inbound crypto protocol selection",r);try{const{stream:n,protocol:o}=await handle(t,r,{writeBytes:!0}),a=this.connectionEncryption.get(o);if(a==null)throw new Error(`no crypto module found for ${o}`);return log$8("encrypting inbound connection..."),{...await a.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw new CodeError(String(n),codes.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(t,r){const n=Array.from(this.connectionEncryption.keys());log$8("selecting outbound crypto protocol",n);try{const{stream:o,protocol:a}=await select(t,n,{writeBytes:!0}),l=this.connectionEncryption.get(a);if(l==null)throw new Error(`no crypto module found for ${a}`);return log$8("encrypting outbound connection to %p",r),{...await l.secureOutbound(this.components.peerId,o,r),protocol:a}}catch(o){throw new CodeError(String(o),codes.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(t,r){const n=Array.from(r.keys());log$8("outbound selecting muxer %s",n);try{const{stream:o,protocol:a}=await select(t,n,{writeBytes:!0});log$8("%s selected as muxer protocol",a);const l=r.get(a);return{stream:o,muxerFactory:l}}catch(o){throw log$8.error("error multiplexing outbound stream",o),new CodeError(String(o),codes.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(t,r){const n=Array.from(r.keys());log$8("inbound handling muxers %s",n);try{const{stream:o,protocol:a}=await handle(t,n,{writeBytes:!0}),l=r.get(a);return{stream:o,muxerFactory:l}}catch(o){throw log$8.error("error multiplexing inbound stream",o),new CodeError(String(o),codes.ERR_MUXER_UNAVAILABLE)}}}const log$7=logger("libp2p");var un,ts,ya;class Libp2pNode extends EventEmitter$2{constructor(r){super();_r(this,ts);Ye(this,"peerId");Ye(this,"peerStore");Ye(this,"contentRouting");Ye(this,"peerRouting");Ye(this,"keychain");Ye(this,"metrics");Ye(this,"services");Ye(this,"components");_r(this,un,void 0);const n=new EventEmitter$2,o=n.dispatchEvent.bind(n);n.dispatchEvent=_=>{const b=o(_),x=this.dispatchEvent(new CustomEvent$1(_.type,{detail:_.detail}));return b||x};try{events$1.exports.setMaxListeners?.(1/0,n)}catch{}wn(this,un,!1),this.peerId=r.peerId,this.services={};const a=this.components=defaultComponents({peerId:r.peerId,events:n,datastore:r.datastore??new MemoryDatastore,connectionGater:connectionGater(r.connectionGater)});this.peerStore=this.configureComponent("peerStore",new PersistentPeerStore(a,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...r.peerStore})),r.metrics!=null&&(this.metrics=this.configureComponent("metrics",r.metrics(this.components))),a.events.addEventListener("peer:update",_=>{if(_.detail.previous==null){const b={id:_.detail.peer.id,multiaddrs:_.detail.peer.addresses.map(x=>x.multiaddr),protocols:_.detail.peer.protocols};a.events.safeDispatchEvent("peer:discovery",{detail:b})}}),r.connectionProtector!=null&&this.configureComponent("connectionProtector",r.connectionProtector(a)),this.components.upgrader=new DefaultUpgrader(this.components,{connectionEncryption:(r.connectionEncryption??[]).map((_,b)=>this.configureComponent(`connection-encryption-${b}`,_(this.components))),muxers:(r.streamMuxers??[]).map((_,b)=>this.configureComponent(`stream-muxers-${b}`,_(this.components))),inboundUpgradeTimeout:r.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new DefaultTransportManager(this.components,r.transportManager)),this.configureComponent("connectionManager",new DefaultConnectionManager(this.components,r.connectionManager)),this.configureComponent("registrar",new DefaultRegistrar(this.components)),this.configureComponent("addressManager",new DefaultAddressManager(this.components,r.addresses));const l=DefaultKeyChain.generateOptions();this.keychain=this.configureComponent("keyChain",new DefaultKeyChain(this.components,{...l,...r.keychain}));const c=(r.peerRouters??[]).map((_,b)=>this.configureComponent(`peer-router-${b}`,_(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new DefaultPeerRouting(this.components,{routers:c}));const u=(r.contentRouters??[]).map((_,b)=>this.configureComponent(`content-router-${b}`,_(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new CompoundContentRouting(this.components,{routers:u})),(r.peerDiscovery??[]).forEach((_,b)=>{this.configureComponent(`peer-discovery-${b}`,_(this.components)).addEventListener("peer",E=>{vr(this,ts,ya).call(this,E)})}),r.transports.forEach((_,b)=>{this.components.transportManager.add(this.configureComponent(`transport-${b}`,_(this.components)))}),r.services!=null)for(const _ of Object.keys(r.services)){const b=r.services[_],x=b(this.components);if(x==null){log$7.error("service factory %s returned null or undefined instance",_);continue}this.services[_]=x,this.configureComponent(_,x),x[contentRouting]!=null&&(log$7("registering service %s for content routing",_),u.push(x[contentRouting])),x[peerRouting]!=null&&(log$7("registering service %s for peer routing",_),c.push(x[peerRouting])),x[peerDiscovery]!=null&&(log$7("registering service %s for peer discovery",_),x[peerDiscovery].addEventListener("peer",E=>{vr(this,ts,ya).call(this,E)}))}}configureComponent(r,n){return n==null&&log$7.error("component %s was null or undefined",r),this.components[r]=n,n}async start(){if(Jt(this,un))return;wn(this,un,!0),log$7("libp2p is starting"),(await this.keychain.listKeys()).find(n=>n.name==="self")==null&&(log$7("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),log$7("libp2p has started")}catch(n){throw log$7.error("An error occurred starting libp2p",n),await this.stop(),n}}async stop(){!Jt(this,un)||(log$7("libp2p is stopping"),wn(this,un,!1),await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),log$7("libp2p has stopped"))}isStarted(){return Jt(this,un)}getConnections(r){return this.components.connectionManager.getConnections(r)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const r=new PeerSet;for(const n of this.components.connectionManager.getConnections())r.add(n.remotePeer);return Array.from(r)}async dial(r,n={}){return this.components.connectionManager.openConnection(r,n)}async dialProtocol(r,n,o={}){if(n==null)throw new CodeError("no protocols were provided to open a stream",codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(n=Array.isArray(n)?n:[n],n.length===0)throw new CodeError("no protocols were provided to open a stream",codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(r,o)).newStream(n,o)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(r,n={}){isMultiaddr(r)&&(r=peerIdFromString(r.getPeerId()??"")),await this.components.connectionManager.closeConnections(r,n)}async getPublicKey(r,n={}){if(log$7("getPublicKey %p",r),r.publicKey!=null)return r.publicKey;const o=await this.peerStore.get(r);if(o.id.publicKey!=null)return o.id.publicKey;const a=concat$1([fromString$1("/pk/"),r.multihash.digest]),l=await this.contentRouting.get(a,n);return unmarshalPublicKey(l),await this.peerStore.patch(r,{publicKey:l}),l}async handle(r,n,o){Array.isArray(r)||(r=[r]),await Promise.all(r.map(async a=>{await this.components.registrar.handle(a,n,o)}))}async unhandle(r){Array.isArray(r)||(r=[r]),await Promise.all(r.map(async n=>{await this.components.registrar.unhandle(n)}))}async register(r,n){return this.components.registrar.register(r,n)}unregister(r){this.components.registrar.unregister(r)}}un=new WeakMap,ts=new WeakSet,ya=function(r){const{detail:n}=r;if(n.id.toString()===this.peerId.toString()){log$7.error(new Error(codes.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(n.id,{multiaddrs:n.multiaddrs,protocols:n.protocols}).catch(o=>{log$7.error(o)})};async function createLibp2pNode(e){if(e.peerId==null){const t=e.datastore;if(t!=null)try{const r=new DefaultKeyChain({datastore:t},mergeOptions(DefaultKeyChain.generateOptions(),e.keychain));e.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return e.peerId==null&&(e.peerId=await createEd25519PeerId()),new Libp2pNode(validateConfig(e))}async function createLibp2p(e){const t=await createLibp2pNode(e);return e.start!==!1&&await t.start(),t}const CIRCUIT_PROTO_CODE=290,RELAY_RENDEZVOUS_NS="/libp2p/relay",DEFAULT_RESERVATION_CONCURRENCY=1,RELAY_TAG="circuit-relay-relay";BigInt(1<<17);const RELAY_V2_HOP_CODEC="/libp2p/circuit/relay/0.2.0/hop",RELAY_V2_STOP_CODEC="/libp2p/circuit/relay/0.2.0/stop";var HopMessage;(function(e){(function(n){n.RESERVE="RESERVE",n.CONNECT="CONNECT",n.STATUS="STATUS"})(e.Type||(e.Type={}));let t;(function(n){n[n.RESERVE=0]="RESERVE",n[n.CONNECT=1]="CONNECT",n[n.STATUS=2]="STATUS"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),Peer.codec().encode(n.peer,o)),n.reservation!=null&&(o.uint32(26),Reservation.codec().encode(n.reservation,o)),n.limit!=null&&(o.uint32(34),Limit.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(40),Status.codec().encode(n.status,o)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.peer=Peer.codec().decode(n,n.uint32());break;case 3:a.reservation=Reservation.codec().decode(n,n.uint32());break;case 4:a.limit=Limit.codec().decode(n,n.uint32());break;case 5:a.status=Status.codec().decode(n);break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(HopMessage||(HopMessage={}));var StopMessage;(function(e){(function(n){n.CONNECT="CONNECT",n.STATUS="STATUS"})(e.Type||(e.Type={}));let t;(function(n){n[n.CONNECT=0]="CONNECT",n[n.STATUS=1]="STATUS"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),Peer.codec().encode(n.peer,o)),n.limit!=null&&(o.uint32(26),Limit.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(32),Status.codec().encode(n.status,o)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.peer=Peer.codec().decode(n,n.uint32());break;case 3:a.limit=Limit.codec().decode(n,n.uint32());break;case 4:a.status=Status.codec().decode(n);break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(StopMessage||(StopMessage={}));var Peer;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.id!=null&&r.id.byteLength>0&&(n.uint32(10),n.bytes(r.id)),r.addrs!=null)for(const a of r.addrs)n.uint32(18),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={id:new Uint8Array(0),addrs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.id=r.bytes();break;case 2:o.addrs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Peer||(Peer={}));var Reservation;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.expire!=null&&r.expire!==0n&&(n.uint32(8),n.uint64(r.expire)),r.addrs!=null)for(const a of r.addrs)n.uint32(18),n.bytes(a);r.voucher!=null&&(n.uint32(26),n.bytes(r.voucher)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={expire:0n,addrs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.expire=r.uint64();break;case 2:o.addrs.push(r.bytes());break;case 3:o.voucher=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Reservation||(Reservation={}));var Limit;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.duration!=null&&(n.uint32(8),n.uint32(r.duration)),r.data!=null&&(n.uint32(16),n.uint64(r.data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.duration=r.uint32();break;case 2:o.data=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Limit||(Limit={}));var Status;(function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Status||(Status={}));var __StatusValues;(function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(__StatusValues||(__StatusValues={}));(function(e){e.codec=()=>enumeration(__StatusValues)})(Status||(Status={}));var ReservationVoucher;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.relay!=null&&r.relay.byteLength>0&&(n.uint32(10),n.bytes(r.relay)),r.peer!=null&&r.peer.byteLength>0&&(n.uint32(18),n.bytes(r.peer)),r.expiration!=null&&r.expiration!==0n&&(n.uint32(24),n.uint64(r.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.relay=r.bytes();break;case 2:o.peer=r.bytes();break;case 3:o.expiration=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ReservationVoucher||(ReservationVoucher={}));logger("libp2p:circuit-relay:utils");async function namespaceToCid(e){const t=new TextEncoder().encode(e),r=await sha256$1.digest(t);return CID.createV0(r)}function getExpirationMilliseconds(e){const t=e*BigInt(1e3),r=new Date().getTime();return Number(t-BigInt(r))}var retry$1={exports:{}},retry={};function RetryOperation(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};RetryOperation.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=l)}return t};(function(e){var t=retry_operation;e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var o in r)n[o]=r[o];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],l=0;l{this.safeDispatchEvent("relay:discover",{detail:r})}}),this.discover().catch(r=>{log$5.error("error listening on relays",r)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){log$5("searching peer store for relays");const r=await this.peerStore.all({filters:[n=>n.protocols.includes(RELAY_V2_HOP_CODEC)],orders:[()=>Math.random()<.5?1:-1]});for(const n of r)log$5("found relay peer %p in content peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});log$5("found %d relay peers in peer store",r.length);try{log$5("searching content routing for relays");const n=await namespaceToCid(RELAY_RENDEZVOUS_NS);let o=0;for await(const a of this.contentRouting.findProviders(n))if(a.multiaddrs.length>0&&!a.id.equals(this.peerId)){const l=a.id;o++,await this.peerStore.merge(l,{multiaddrs:a.multiaddrs}),log$5("found relay peer %p in content routing",l),this.safeDispatchEvent("relay:discover",{detail:l})}log$5("found %d relay peers in content routing",o)}catch(n){log$5.error("failed when finding relays on the network",n)}}}const log$4=logger("libp2p:circuit-relay:transport:listener");var uo,Va;class CircuitRelayTransportListener extends EventEmitter$2{constructor(r){super();_r(this,uo);Ye(this,"connectionManager");Ye(this,"relayStore");Ye(this,"listeningAddrs");this.connectionManager=r.connectionManager,this.relayStore=r.relayStore,this.listeningAddrs=new PeerMap,this.relayStore.addEventListener("relay:removed",n=>{vr(this,uo,Va).call(this,n.detail)})}async listen(r){log$4("listen on %a",r);const n=r.getPeerId();let o;if(n!=null){const l=peerIdFromString(n),c=this.connectionManager.getConnectionsMap().get(l)??[];c.length>0&&(o=c[0])}if(o==null){const l=r.toString().split("/p2p-circuit").find(u=>u!==""),c=multiaddr(l);o=await this.connectionManager.openConnection(c)}if(!this.relayStore.hasReservation(o.remotePeer)){await this.relayStore.addRelay(o.remotePeer,"configured");return}const a=this.relayStore.getReservation(o.remotePeer);if(a==null)throw new CodeError("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(o.remotePeer)){log$4("already listening on relay %p",o.remotePeer);return}this.listeningAddrs.set(o.remotePeer,a.addrs.map(l=>multiaddr(l).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}}uo=new WeakSet,Va=function(r){const n=this.listeningAddrs.has(r);log$4("relay peer removed %p - had reservation",r,n),this.listeningAddrs.delete(r),n&&this.safeDispatchEvent("close",{})};function createListener(e){return new CircuitRelayTransportListener(e)}const log$3=logger("libp2p:circuit-relay:transport:reservation-store"),REFRESH_WINDOW=60*1e3*10,REFRESH_TIMEOUT=60*1e3*5,REFRESH_TIMEOUT_MIN=30*1e3;var ho,Ha,fo,za;class ReservationStore extends EventEmitter$2{constructor(r,n){super();_r(this,ho);_r(this,fo);Ye(this,"peerId");Ye(this,"connectionManager");Ye(this,"transportManager");Ye(this,"peerStore");Ye(this,"events");Ye(this,"reserveQueue");Ye(this,"reservations");Ye(this,"maxDiscoveredRelays");Ye(this,"maxReservationQueueLength");Ye(this,"reservationCompletionTimeout");Ye(this,"started");this.peerId=r.peerId,this.connectionManager=r.connectionManager,this.transportManager=r.transportManager,this.peerStore=r.peerStore,this.events=r.events,this.reservations=new PeerMap,this.maxDiscoveredRelays=n?.discoverRelays??0,this.maxReservationQueueLength=n?.maxReservationQueueLength??100,this.reservationCompletionTimeout=n?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new PeerJobQueue({concurrency:n?.reservationConcurrency??DEFAULT_RESERVATION_CONCURRENCY}),this.events.addEventListener("peer:disconnect",o=>{vr(this,fo,za).call(this,o.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:r})=>{clearTimeout(r)}),this.reservations.clear(),this.started=!1}async addRelay(r,n){if(this.peerId.equals(r)){log$3("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){log$3("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(r)){log$3("relay peer is already in the reservation queue");return}log$3("add relay %p",r),await this.reserveQueue.add(async()=>{try{const o=this.reservations.get(r);if(o!=null){if(getExpirationMilliseconds(o.reservation.expire)>REFRESH_WINDOW){log$3("already have reservation on relay peer %p and it expires in more than 10 minutes",r);return}clearTimeout(o.timeout),this.reservations.delete(r)}if(n==="discovered"&&[...this.reservations.values()].reduce((x,E)=>(E.type==="discovered"&&x++,x),0)>=this.maxDiscoveredRelays){log$3("already have enough discovered relays");return}const a=AbortSignal.timeout(this.reservationCompletionTimeout),l=await this.connectionManager.openConnection(r,{signal:a});if(l.remoteAddr.protoNames().includes("p2p-circuit")){log$3("not creating reservation over relayed connection");return}const c=await vr(this,ho,Ha).call(this,l,{signal:a});log$3("created reservation on relay peer %p",r);const u=getExpirationMilliseconds(c.expire),_=Math.min(Math.max(u-REFRESH_TIMEOUT,REFRESH_TIMEOUT_MIN),Math.pow(2,31)-1),b=setTimeout(()=>{this.addRelay(r,n).catch(x=>{log$3.error("could not refresh reservation to relay %p",r,x)})},_);this.reservations.set(r,{timeout:b,reservation:c,type:n}),await this.peerStore.merge(r,{tags:{[RELAY_TAG]:{value:1,ttl:u}}}),await this.transportManager.listen([multiaddr(`/p2p/${r.toString()}/p2p-circuit`)])}catch(o){log$3.error("could not reserve slot on %p",r,o);const a=this.reservations.get(r);a!=null&&clearTimeout(a.timeout),this.reservations.delete(r)}},{peerId:r})}hasReservation(r){return this.reservations.has(r)}getReservation(r){return this.reservations.get(r)?.reservation}}ho=new WeakSet,Ha=async function(r,n){n.signal?.throwIfAborted(),log$3("requesting reservation from %p",r.remotePeer);const o=await r.newStream(RELAY_V2_HOP_CODEC,n),l=pbStream(o).pb(HopMessage);await l.write({type:HopMessage.Type.RESERVE},n);let c;try{c=await l.read(n)}catch(_){throw log$3.error("error parsing reserve message response from %p because",r.remotePeer,_),_}finally{await o.close()}if(c.status===Status.OK&&c.reservation!=null)return c.reservation;const u=`reservation failed with status ${c.status??"undefined"}`;throw log$3.error(u),new Error(u)},fo=new WeakSet,za=function(r){const n=this.reservations.get(r);n!=null&&(log$3("connection to relay %p closed, removing reservation from local store",r),clearTimeout(n.timeout),this.reservations.delete(r),this.safeDispatchEvent("relay:removed",{detail:r}),this.reservations.size{if(e.peer==null)return!1;try{e.peer.addrs.forEach(multiaddr)}catch{return!1}return!0},defaults={maxInboundStopStreams:MAX_CONNECTIONS,maxOutboundStopStreams:MAX_CONNECTIONS,stopTimeout:3e4};var ac,lc;class CircuitRelayTransport{constructor(t,r){Ye(this,"discovery");Ye(this,"registrar");Ye(this,"peerStore");Ye(this,"connectionManager");Ye(this,"peerId");Ye(this,"upgrader");Ye(this,"addressManager");Ye(this,"connectionGater");Ye(this,"reservationStore");Ye(this,"maxInboundStopStreams");Ye(this,"maxOutboundStopStreams");Ye(this,"stopTimeout");Ye(this,"started");Ye(this,ac,!0);Ye(this,lc,"libp2p/circuit-relay-v2");this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=r.maxInboundStopStreams??defaults.maxInboundStopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??defaults.maxOutboundStopStreams,this.stopTimeout=r.stopTimeout??defaults.stopTimeout,r.discoverRelays!=null&&r.discoverRelays>0&&(this.discovery=new RelayDiscovery(t),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{log$2.error("could not add discovered relay %p",n.detail,o)})})),this.reservationStore=new ReservationStore(t,r),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{log$2.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(RELAY_V2_STOP_CODEC,t=>{this.onStop(t).catch(r=>{log$2.error("error while handling STOP protocol",r),t.stream.abort(r)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(RELAY_V2_STOP_CODEC),this.started=!1}async dial(t,r={}){if(t.protoCodes().filter(k=>k===CIRCUIT_PROTO_CODE).length!==1){const k="Invalid circuit relay address";throw log$2.error(k,t),new CodeError(k,codes.ERR_RELAYED_DIAL)}const n=t.toString().split("/p2p-circuit"),o=multiaddr(n[0]),a=multiaddr(n[n.length-1]),l=o.getPeerId(),c=a.getPeerId();if(l==null||c==null){const k=`Circuit relay dial to ${t.toString()} failed as address did not have peer ids`;throw log$2.error(k),new CodeError(k,codes.ERR_RELAYED_DIAL)}const u=peerIdFromString(l),_=peerIdFromString(c);let b=!1,E=this.connectionManager.getConnections(u)[0];E==null&&(await this.peerStore.merge(u,{multiaddrs:[o]}),E=await this.connectionManager.openConnection(u,r),b=!0);let I;try{return I=await E.newStream([RELAY_V2_HOP_CODEC]),await this.connectV2({stream:I,connection:E,destinationPeer:_,destinationAddr:a,relayAddr:o,ma:t,disconnectOnFailure:b})}catch(k){throw log$2.error(`Circuit relay dial to destination ${_.toString()} via relay ${u.toString()} failed`,k),I?.abort(k),b&&await E.close(),k}}async connectV2({stream:t,connection:r,destinationPeer:n,destinationAddr:o,relayAddr:a,ma:l,disconnectOnFailure:c}){try{const u=pbStream(t),_=u.pb(HopMessage);await _.write({type:HopMessage.Type.CONNECT,peer:{id:n.toBytes(),addrs:[multiaddr(o).bytes]}});const b=await _.read();if(b.status!==Status.OK)throw new CodeError(`failed to connect via relay with status ${b?.status?.toString()??"undefined"}`,codes.ERR_HOP_REQUEST_FAILED);const x=streamToMaConnection({stream:u.unwrap(),remoteAddr:l,localAddr:a.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return log$2("new outbound transient connection %a",x.remoteAddr),await this.upgrader.upgradeOutbound(x,{transient:!0})}catch(u){throw log$2.error(`Circuit relay dial to destination ${n.toString()} via relay ${r.remotePeer.toString()} failed`,u),c&&await r.close(),u}}createListener(t){return createListener({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(t){return t=Array.isArray(t)?t:[t],t.filter(r=>Circuit$1.matches(r))}async onStop({connection:t,stream:r}){const n=AbortSignal.timeout(this.stopTimeout),o=pbStream(r).pb(StopMessage),a=await o.read({signal:n});if(log$2("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,a.type),a?.type===void 0){log$2.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.MALFORMED_MESSAGE},{signal:n}),await r.close();return}if(a.type!==StopMessage.Type.CONNECT){log$2.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.UNEXPECTED_MESSAGE},{signal:n}),await r.close();return}if(!isValidStop(a)){log$2.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.MALFORMED_MESSAGE},{signal:n}),await r.close();return}const l=peerIdFromBytes(a.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,l)===!0){log$2.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.PERMISSION_DENIED},{signal:n}),await r.close();return}log$2.trace("sending success response to %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.OK},{signal:n});const c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${l.toString()}`),u=this.addressManager.getAddresses()[0],_=streamToMaConnection({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u});log$2("new inbound transient connection %a",_.remoteAddr),await this.upgrader.upgradeInbound(_,{transient:!0}),log$2("%s connection %a upgraded","inbound",_.remoteAddr)}}ac=symbol$1,lc=Symbol.toStringTag;function circuitRelayTransport(e={}){return t=>new CircuitRelayTransport(t,e)}const version="0.46.11",AGENT_VERSION=`js-libp2p/${version}`,IDENTIFY_PROTOCOL_VERSION="0.1.0",MULTICODEC_IDENTIFY_PROTOCOL_NAME="id",MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME="id/push",MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0",MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION="1.0.0";var Identify;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.protocolVersion!=null&&(n.uint32(42),n.string(r.protocolVersion)),r.agentVersion!=null&&(n.uint32(50),n.string(r.agentVersion)),r.publicKey!=null&&(n.uint32(10),n.bytes(r.publicKey)),r.listenAddrs!=null)for(const a of r.listenAddrs)n.uint32(18),n.bytes(a);if(r.observedAddr!=null&&(n.uint32(34),n.bytes(r.observedAddr)),r.protocols!=null)for(const a of r.protocols)n.uint32(26),n.string(a);r.signedPeerRecord!=null&&(n.uint32(66),n.bytes(r.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={listenAddrs:[],protocols:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 5:o.protocolVersion=r.string();break;case 6:o.agentVersion=r.string();break;case 1:o.publicKey=r.bytes();break;case 2:o.listenAddrs.push(r.bytes());break;case 4:o.observedAddr=r.bytes();break;case 3:o.protocols.push(r.string());break;case 8:o.signedPeerRecord=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Identify||(Identify={}));const log$1=logger("libp2p:identify"),MAX_IDENTIFY_MESSAGE_SIZE=1024*8,defaultValues={protocolPrefix:"ipfs",agentVersion:AGENT_VERSION,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0};var rs,va;class DefaultIdentifyService{constructor(t,r){_r(this,rs);Ye(this,"identifyProtocolStr");Ye(this,"identifyPushProtocolStr");Ye(this,"host");Ye(this,"started");Ye(this,"timeout");Ye(this,"peerId");Ye(this,"peerStore");Ye(this,"registrar");Ye(this,"connectionManager");Ye(this,"addressManager");Ye(this,"maxInboundStreams");Ye(this,"maxOutboundStreams");Ye(this,"maxPushIncomingStreams");Ye(this,"maxPushOutgoingStreams");Ye(this,"maxIdentifyMessageSize");Ye(this,"maxObservedAddresses");Ye(this,"events");Ye(this,"runOnTransientConnection");this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.connectionManager=t.connectionManager,this.events=t.events,this.identifyProtocolStr=`/${r.protocolPrefix??defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,this.identifyPushProtocolStr=`/${r.protocolPrefix??defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`,this.timeout=r.timeout??defaultValues.timeout,this.maxInboundStreams=r.maxInboundStreams??defaultValues.maxInboundStreams,this.maxOutboundStreams=r.maxOutboundStreams??defaultValues.maxOutboundStreams,this.maxPushIncomingStreams=r.maxPushIncomingStreams??defaultValues.maxPushIncomingStreams,this.maxPushOutgoingStreams=r.maxPushOutgoingStreams??defaultValues.maxPushOutgoingStreams,this.maxIdentifyMessageSize=r.maxIdentifyMessageSize??defaultValues.maxIdentifyMessageSize,this.maxObservedAddresses=r.maxObservedAddresses??defaultValues.maxObservedAddresses,this.runOnTransientConnection=r.runOnTransientConnection??defaultValues.runOnTransientConnection,this.host={protocolVersion:`${r.protocolPrefix??defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,agentVersion:r.agentVersion??defaultValues.agentVersion},(r.runOnConnectionOpen??defaultValues.runOnConnectionOpen)&&t.events.addEventListener("connection:open",n=>{const o=n.detail;this.identify(o).catch(a=>{log$1.error("error during identify trigged by connection:open",a)})}),t.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{log$1.error(o)})}),this.host.agentVersion===AGENT_VERSION&&(isNode||isElectronMain?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(isBrowser||isWebWorker||isElectronRenderer||isReactNative)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:fromString$1(this.host.agentVersion),ProtocolVersion:fromString$1(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,t=>{this._handleIdentify(t).catch(r=>{log$1.error(r)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,t=>{this._handlePush(t).catch(r=>{log$1.error(r)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(t){const r=this.addressManager.getAddresses().map(b=>b.decapsulateCode(getProtocol("p2p").code)),n=new PeerRecord({peerId:this.peerId,multiaddrs:r}),o=await RecordEnvelope.seal(n,this.peerId),a=this.registrar.getProtocols(),l=await this.peerStore.get(this.peerId),c=toString$5(l.metadata.get("AgentVersion")??fromString$1(this.host.agentVersion)),u=toString$5(l.metadata.get("ProtocolVersion")??fromString$1(this.host.protocolVersion)),_=t.map(async b=>{let x;const E=AbortSignal.timeout(this.timeout);try{events$1.exports.setMaxListeners?.(1/0,E)}catch{}try{x=await b.newStream([this.identifyPushProtocolStr],{signal:E,runOnTransientConnection:this.runOnTransientConnection}),await pbStream(x,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).write({listenAddrs:r.map(k=>k.bytes),signedPeerRecord:o.marshal(),protocols:a,agentVersion:c,protocolVersion:u},{signal:E}),await x.close({signal:E})}catch(I){log$1.error("could not push identify update to peer",I),x?.abort(I)}});await Promise.all(_)}async push(){if(!this.isStarted())return;const t=[];await Promise.all(this.connectionManager.getConnections().map(async r=>{try{if(!(await this.peerStore.get(r.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;t.push(r)}catch(n){if(n.code!==codes.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(t)}async _identify(t,r={}){let n;r.signal=r.signal??AbortSignal.timeout(this.timeout);try{n=await t.newStream([this.identifyProtocolStr],{...r,runOnTransientConnection:this.runOnTransientConnection});const a=await pbStream(n,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).read(r);return await n.close(r),a}catch(o){throw log$1.error("error while reading identify message",o),n?.abort(o),o}}async identify(t,r={}){const n=await this._identify(t,r),{publicKey:o,protocols:a,observedAddr:l}=n;if(o==null)throw new CodeError("public key was missing from identify message",codes.ERR_MISSING_PUBLIC_KEY);const c=await peerIdFromKeys(o);if(!t.remotePeer.equals(c))throw new CodeError("identified peer does not match the expected peer",codes.ERR_INVALID_PEER);if(this.peerId.equals(c))throw new CodeError("identified peer is our own peer id?",codes.ERR_INVALID_PEER);const u=getCleanMultiaddr(l);log$1("identify completed for peer %p and protocols %o",c,a),log$1("our observed address is %a",u),u!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(log$1("storing our observed address %a",u),this.addressManager.addObservedAddr(u));const _=await vr(this,rs,va).call(this,t.remotePeer,n),b={peerId:c,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(x=>multiaddr(x)),observedAddr:n.observedAddr==null?void 0:multiaddr(n.observedAddr),protocols:n.protocols,signedPeerRecord:_};return this.events.safeDispatchEvent("peer:identify",{detail:b}),b}async _handleIdentify(t){const{connection:r,stream:n}=t,o=AbortSignal.timeout(this.timeout);try{events$1.exports.setMaxListeners?.(1/0,o)}catch{}try{const a=this.peerId.publicKey??new Uint8Array(0),l=await this.peerStore.get(this.peerId),c=this.addressManager.getAddresses().map(b=>b.decapsulateCode(getProtocol("p2p").code));let u=l.peerRecordEnvelope;if(c.length>0&&u==null){const b=new PeerRecord({peerId:this.peerId,multiaddrs:c});u=(await RecordEnvelope.seal(b,this.peerId)).marshal().subarray()}await pbStream(n).pb(Identify).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:a,listenAddrs:c.map(b=>b.bytes),signedPeerRecord:u,observedAddr:r.remoteAddr.bytes,protocols:l.protocols},{signal:o}),await n.close({signal:o})}catch(a){log$1.error("could not respond to identify request",a),n.abort(a)}}async _handlePush(t){const{connection:r,stream:n}=t;try{if(this.peerId.equals(r.remotePeer))throw new Error("received push from ourselves?");const o={signal:AbortSignal.timeout(this.timeout)},l=await pbStream(n,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).read(o);await n.close(o),await vr(this,rs,va).call(this,r.remotePeer,l)}catch(o){log$1.error("received invalid message",o),n.abort(o);return}log$1("handled push from %p",r.remotePeer)}}rs=new WeakSet,va=async function(t,r){if(log$1("received identify from %p",t),r==null)throw new Error("Message was null or undefined");const n={addresses:r.listenAddrs.map(a=>({isCertified:!1,multiaddr:multiaddr(a)})),protocols:r.protocols,metadata:new Map,peerRecordEnvelope:r.signedPeerRecord};let o;if(r.signedPeerRecord!=null){log$1("received signedPeerRecord in push from %p",t);let a=r.signedPeerRecord;const l=await RecordEnvelope.openAndCertify(a,PeerRecord.DOMAIN);let c=PeerRecord.createFromProtobuf(l.payload);if(!c.peerId.equals(l.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!t.equals(c.peerId))throw new Error("signing key does not match remote PeerId");let u;try{u=await this.peerStore.get(c.peerId)}catch(_){if(_.code!=="ERR_NOT_FOUND")throw _}if(u!=null&&(n.metadata=u.metadata,u.peerRecordEnvelope!=null)){const _=await RecordEnvelope.createFromProtobuf(u.peerRecordEnvelope),b=PeerRecord.createFromProtobuf(_.payload);b.seqNumber>=c.seqNumber&&(log$1("sequence number was lower or equal to existing sequence number - stored: %d received: %d",b.seqNumber,c.seqNumber),c=b,a=u.peerRecordEnvelope)}n.peerRecordEnvelope=a,n.addresses=c.multiaddrs.map(_=>({isCertified:!0,multiaddr:_})),o={seq:c.seqNumber,addresses:c.multiaddrs}}else log$1("%p did not send a signed peer record",t);return r.agentVersion!=null&&n.metadata.set("AgentVersion",fromString$1(r.agentVersion)),r.protocolVersion!=null&&n.metadata.set("ProtocolVersion",fromString$1(r.protocolVersion)),await this.peerStore.patch(t,n),o};function getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return multiaddr(e)}catch{}}function identifyService(e={}){return t=>new DefaultIdentifyService(t,e)}const createNode=async e=>await createLibp2p({addresses:{listen:["/webrtc"]},transports:[webSockets({filter:all$1}),webRTC(),circuitRelayTransport({discoverRelays:1})],streamMuxers:[mplex()],connectionEncryption:[noise()],services:{pubsub:floodsub(),identify:identifyService()},peerDiscovery:[bootstrap({list:e.bootstrappers})],connectionGater:{denyDialMultiaddr:()=>!1}}),agents=["QmcQJV9CQ7UCHAtGw55urFS39knSVR2nocNVNv1N1BuWwG","QmYAesHYTymfXyXitPBaHLBrC3dfVrRESFd28gfnbyjo7e","QmQHzQqXe5npsyRfRFrSbjDHTKKRz1cULajerNZrJLAMsK","QmXzPWCya9xakMQY2YLdhscHHhQ7ojNhGJzuunC57FZnta","QmRohqPDqYVwttjxJrhQVtZJH9o5QFBja3NT62aAbNDVkX","QmRjxZ7ccJ5N2HgLmz5we9pezBvP7gDvx2BjDJSw6p1TCE","QmamWhrh3qqaRzbjcZ1Si9k8V2ytoJhhPDzVGyzEAtdUCc","QmZuyyMJRo5Cs4GkARbvkxrBbiP2oRUNpWc7dBmTACZg4T","12D3KooWP2yCMkb67Xj8EkDEDfzvEgMhR7kdun8MvDcvsqoUPmuD","12D3KooWRazGg1wMjjEFaaZGXseHpt3MXrU5oZS2idQZ6M4GPL4U","12D3KooWB7wQJuFyUQL1RjdkEwDQ82msxB4xsLCHHGdJLGxaqrmR","12D3KooWGQAxCSvgAbcVHXxuzaBgzie9HSUStjvnQRQBY2CTjnLU","12D3KooWKDUV8Je6EQLhKDsiQCgzQEDKBo8ukPcxYKmts47nST4D"];function getAgents(){return agents}const topic="airalab.lighthouse.5.robonomics.eth";class Provider$1{constructor(t){this.node=null,this.isReady=!1,this.whiteListAccounts=[],this.history={},this.init(t).then(()=>{this.isReady=!0,window.pubsubPeers=()=>{console.log("peers",this.node.services.pubsub.getPeers().map(r=>r.toString())),console.log("pubsub",this.node.services.pubsub.getSubscribers(topic).map(r=>r.toString()))}})}async init(t){this.node=await createNode(t),this.whiteListAccounts=getAgents()}ready(){return new Promise(t=>{const r=setInterval(()=>{this.isReady&&(t(),clearInterval(r))},100)})}getHistoryBySensor(t){return Promise.resolve(this.history[t]?this.history[t]:[])}watch(t){this.node.services.pubsub.subscribe(topic),this.node.services.pubsub.addEventListener("message",r=>{const n=r.detail.from.toString();if(!this.whiteListAccounts.includes(n))return;let o;try{o=JSON.parse(Buffer.from(r.detail.data).toString("utf8"))}catch(l){console.error(l.message);return}for(const l in o){const c=o[l];if(Object.prototype.hasOwnProperty.call(c,"model")&&(!Object.prototype.hasOwnProperty.call(this.history,l)||this.history[l].find(u=>u.timestamp===c.measurement.timestamp)===void 0)){const{timestamp:u,..._}=c.measurement,b={};for(var a in _){const T=a.toLowerCase();b[T]=measurements[T]?.calculate?measurements[T].calculate(_[a]):_[a]}const[x,E]=c.geo.split(","),I=c.donated_by||void 0,k={sensor_id:l,sender:n,model:c.model,geo:{lat:x,lng:E},data:b,donated_by:I,timestamp:u};Object.prototype.hasOwnProperty.call(this.history,l)||(this.history[l]=[]),this.history[l].push(k),t(k)}}})}}var lib$1={exports:{}},re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],parseuri$2=function e(t){var r=t,n=t.indexOf("["),o=t.indexOf("]");n!=-1&&o!=-1&&(t=t.substring(0,n)+t.substring(n,o).replace(/:/g,";")+t.substring(o,t.length));for(var a=re.exec(t||""),l={},c=14;c--;)l[parts[c]]=a[c]||"";return n!=-1&&o!=-1&&(l.source=r,l.host=l.host.substring(1,l.host.length-1).replace(/;/g,":"),l.authority=l.authority.replace("[","").replace("]","").replace(/;/g,":"),l.ipv6uri=!0),l.pathNames=pathNames(l,l.path),l.queryKey=queryKey(l,l.query),l};function pathNames(e,t){var r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.substr(0,1)=="/"||t.length===0)&&n.splice(0,1),t.substr(t.length-1,1)=="/"&&n.splice(n.length-1,1),n}function queryKey(e,t){var r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,o,a){o&&(r[o]=a)}),r}var browser$3={exports:{}},debug$8={exports:{}},s$2=1e3,m$3=s$2*60,h$3=m$3*60,d$4=h$3*24,y$2=d$4*365.25,ms$2=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$4(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong$2(e):fmtShort$2(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$4(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$2;case"days":case"day":case"d":return r*d$4;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$3;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$3;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$2;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$2(e){return e>=d$4?Math.round(e/d$4)+"d":e>=h$3?Math.round(e/h$3)+"h":e>=m$3?Math.round(e/m$3)+"m":e>=s$2?Math.round(e/s$2)+"s":e+"ms"}function fmtLong$2(e){return plural$2(e,d$4,"day")||plural$2(e,h$3,"hour")||plural$2(e,m$3,"minute")||plural$2(e,s$2,"second")||e+" ms"}function plural$2(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}};function n(u){var _=this.useColors;if(u[0]=(_?"%c":"")+this.namespace+(_?" %c":" ")+u[0]+(_?"%c ":" ")+"+"+t.humanize(this.diff),!!_){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser$3,browser$3.exports);var parseuri$1=parseuri$2,debug$7=browser$3.exports("socket.io-client:url"),url_1=url;function url(e,t){var r=e;t=t||typeof location<"u"&&location,e==null&&(e=t.protocol+"//"+t.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=t.protocol+e:e=t.host+e),/^(https?|wss?):\/\//.test(e)||(debug$7("protocol-less url %s",e),typeof t<"u"?e=t.protocol+"//"+e:e="https://"+e),debug$7("parse %s",e),r=parseuri$1(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var n=r.host.indexOf(":")!==-1,o=n?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port,r.href=r.protocol+"://"+o+(t&&t.port===r.port?"":":"+r.port),r}var socket_ioParser={},browser$2={exports:{}},debug$6={exports:{}},s$1=1e3,m$2=s$1*60,h$2=m$2*60,d$3=h$2*24,y$1=d$3*365.25,ms$1=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$3(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong$1(e):fmtShort$1(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$3(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$1;case"days":case"day":case"d":return r*d$3;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$2;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$2;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$1;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$1(e){return e>=d$3?Math.round(e/d$3)+"d":e>=h$2?Math.round(e/h$2)+"h":e>=m$2?Math.round(e/m$2)+"m":e>=s$1?Math.round(e/s$1)+"s":e+"ms"}function fmtLong$1(e){return plural$1(e,d$3,"day")||plural$1(e,h$2,"hour")||plural$1(e,m$2,"minute")||plural$1(e,s$1,"second")||e+" ms"}function plural$1(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}};function n(u){var _=this.useColors;if(u[0]=(_?"%c":"")+this.namespace+(_?" %c":" ")+u[0]+(_?"%c ":" ")+"+"+t.humanize(this.diff),!!_){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser$2,browser$2.exports);var componentEmitter={exports:{}};(function(e){e.exports=t;function t(n){if(n)return r(n)}function r(n){for(var o in t.prototype)n[o]=t.prototype[o];return n}t.prototype.on=t.prototype.addEventListener=function(n,o){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(o),this},t.prototype.once=function(n,o){function a(){this.off(n,a),o.apply(this,arguments)}return a.fn=o,this.on(n,a),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(n,o){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var a=this._callbacks["$"+n];if(!a)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var l,c=0;c=0&&e.numn&&(r=n),t>=n||t>=r||n===0)return new ArrayBuffer(0);for(var o=new Uint8Array(e),a=new Uint8Array(r-t),l=t,c=0;l=55296&&o<=56319&&r65535&&(n-=65536,o+=stringFromCharCode(n>>>10&1023|55296),n=56320|n&1023),o+=stringFromCharCode(n);return o}function checkScalarValue(e,t){if(e>=55296&&e<=57343){if(t)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function createByte(e,t){return stringFromCharCode(e>>t&63|128)}function encodeCodePoint(e,t){if((e&4294967168)==0)return stringFromCharCode(e);var r="";return(e&4294965248)==0?r=stringFromCharCode(e>>6&31|192):(e&4294901760)==0?(checkScalarValue(e,t)||(e=65533),r=stringFromCharCode(e>>12&15|224),r+=createByte(e,6)):(e&4292870144)==0&&(r=stringFromCharCode(e>>18&7|240),r+=createByte(e,12),r+=createByte(e,6)),r+=stringFromCharCode(e&63|128),r}function utf8encode(e,t){t=t||{};for(var r=t.strict!==!1,n=ucs2decode$1(e),o=n.length,a=-1,l,c="";++a=byteCount)throw Error("Invalid byte index");var e=byteArray[byteIndex]&255;if(byteIndex++,(e&192)==128)return e&63;throw Error("Invalid continuation byte")}function decodeSymbol(e){var t,r,n,o,a;if(byteIndex>byteCount)throw Error("Invalid byte index");if(byteIndex==byteCount)return!1;if(t=byteArray[byteIndex]&255,byteIndex++,(t&128)==0)return t;if((t&224)==192){if(r=readContinuationByte(),a=(t&31)<<6|r,a>=128)return a;throw Error("Invalid continuation byte")}if((t&240)==224){if(r=readContinuationByte(),n=readContinuationByte(),a=(t&15)<<12|r<<6|n,a>=2048)return checkScalarValue(a,e)?a:65533;throw Error("Invalid continuation byte")}if((t&248)==240&&(r=readContinuationByte(),n=readContinuationByte(),o=readContinuationByte(),a=(t&7)<<18|r<<12|n<<6|o,a>=65536&&a<=1114111))return a;throw Error("Invalid UTF-8 detected")}var byteArray,byteCount,byteIndex;function utf8decode(e,t){t=t||{};var r=t.strict!==!1;byteArray=ucs2decode$1(e),byteCount=byteArray.length,byteIndex=0;for(var n=[],o;(o=decodeSymbol(r))!==!1;)n.push(o);return ucs2encode(n)}var utf8={version:"2.1.2",encode:utf8encode,decode:utf8decode},base64Arraybuffer={},hasRequiredBase64Arraybuffer;function requireBase64Arraybuffer(){return hasRequiredBase64Arraybuffer||(hasRequiredBase64Arraybuffer=1,function(e){base64Arraybuffer.encode=function(t){var r=new Uint8Array(t),n,o=r.length,a="";for(n=0;n>2],a+=e[(r[n]&3)<<4|r[n+1]>>4],a+=e[(r[n+1]&15)<<2|r[n+2]>>6],a+=e[r[n+2]&63];return o%3===2?a=a.substring(0,a.length-1)+"=":o%3===1&&(a=a.substring(0,a.length-2)+"=="),a},base64Arraybuffer.decode=function(t){var r=t.length*.75,n=t.length,o,a=0,l,c,u,_;t[t.length-1]==="="&&(r--,t[t.length-2]==="="&&r--);var b=new ArrayBuffer(r),x=new Uint8Array(b);for(o=0;o>4,x[a++]=(c&15)<<4|u>>2,x[a++]=(u&3)<<6|_&63;return b}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")),base64Arraybuffer}var blob,hasRequiredBlob;function requireBlob(){if(hasRequiredBlob)return blob;hasRequiredBlob=1;var e=typeof e<"u"?e:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:!1,t=function(){try{var c=new Blob(["hi"]);return c.size===2}catch{return!1}}(),r=t&&function(){try{var c=new Blob([new Uint8Array([1,2])]);return c.size===2}catch{return!1}}(),n=e&&e.prototype.append&&e.prototype.getBlob;function o(c){return c.map(function(u){if(u.buffer instanceof ArrayBuffer){var _=u.buffer;if(u.byteLength!==_.byteLength){var b=new Uint8Array(u.byteLength);b.set(new Uint8Array(_,u.byteOffset,u.byteLength)),_=b.buffer}return _}return u})}function a(c,u){u=u||{};var _=new e;return o(c).forEach(function(b){_.append(b)}),u.type?_.getBlob(u.type):_.getBlob()}function l(c,u){return new Blob(o(c),u||{})}return typeof Blob<"u"&&(a.prototype=Blob.prototype,l.prototype=Blob.prototype),blob=function(){return t?r?Blob:l:n?a:void 0}(),blob}(function(e){var t=keys,r=hasBinary2,n=arraybuffer_slice,o=after_1,a=utf8,l;typeof ArrayBuffer<"u"&&(l=requireBase64Arraybuffer());var c=typeof navigator<"u"&&/Android/i.test(navigator.userAgent),u=typeof navigator<"u"&&/PhantomJS/i.test(navigator.userAgent),_=c||u;e.protocol=3;var b=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},x=t(b),E={type:"error",data:"parser error"},I=requireBlob();e.encodePacket=function(H,ie,ue,de){typeof ie=="function"&&(de=ie,ie=!1),typeof ue=="function"&&(de=ue,ue=null);var le=H.data===void 0?void 0:H.data.buffer||H.data;if(typeof ArrayBuffer<"u"&&le instanceof ArrayBuffer)return T(H,ie,de);if(typeof I<"u"&&le instanceof I)return $(H,ie,de);if(le&&le.base64)return k(H,de);var ce=b[H.type];return H.data!==void 0&&(ce+=ue?a.encode(String(H.data),{strict:!1}):String(H.data)),de(""+ce)};function k(H,ie){var ue="b"+e.packets[H.type]+H.data.data;return ie(ue)}function T(H,ie,ue){if(!ie)return e.encodeBase64Packet(H,ue);var de=H.data,le=new Uint8Array(de),ce=new Uint8Array(1+de.byteLength);ce[0]=b[H.type];for(var ve=0;ve1?{type:x[le],data:H.substring(1)}:{type:x[le]}}var de=new Uint8Array(H),le=de[0],ce=n(H,1);return I&&ie==="blob"&&(ce=new I([ce])),{type:x[le],data:ce}};function D(H){try{H=a.decode(H,{strict:!1})}catch{return!1}return H}e.decodeBase64Packet=function(H,ie){var ue=x[H.charAt(0)];if(!l)return{type:ue,data:{base64:!0,data:H.substr(1)}};var de=l.decode(H.substr(1));return ie==="blob"&&I&&(de=new I([de])),{type:ue,data:de}},e.encodePayload=function(H,ie,ue){typeof ie=="function"&&(ue=ie,ie=null);var de=r(H);if(ie&&de)return I&&!_?e.encodePayloadAsBlob(H,ue):e.encodePayloadAsArrayBuffer(H,ue);if(!H.length)return ue("0:");function le(ve){return ve.length+":"+ve}function ce(ve,ee){e.encodePacket(ve,de?ie:!1,!1,function(he){ee(null,le(he))})}N(H,ce,function(ve,ee){return ue(ee.join(""))})};function N(H,ie,ue){for(var de=new Array(H.length),le=o(H.length,ue),ce=function(ee,he,ne){ie(he,function(xe,te){de[ee]=te,ne(xe,de)})},ve=0;ve0;){for(var ce=new Uint8Array(de),ve=ce[0]===0,ee="",he=1;ce[he]!==255;he++){if(ee.length>310)return ue(E,0,1);ee+=ce[he]}de=n(de,2+ee.length),ee=parseInt(ee);var ne=n(de,0,ee);if(ve)try{ne=String.fromCharCode.apply(null,new Uint8Array(ne))}catch{var xe=new Uint8Array(ne);ne="";for(var he=0;he0);return t}function decode(e){var t=0;for(i=0;i0)return parse$2(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$2(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y;case"days":case"day":case"d":return r*d$2;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$1;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$1;case"seconds":case"second":case"secs":case"sec":case"s":return r*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort(e){return e>=d$2?Math.round(e/d$2)+"d":e>=h$1?Math.round(e/h$1)+"h":e>=m$1?Math.round(e/m$1)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d$2,"day")||plural(e,h$1,"hour")||plural(e,m$1,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}};function n(u){var _=this.useColors;if(u[0]=(_?"%c":"")+this.namespace+(_?" %c":" ")+u[0]+(_?"%c ":" ")+"+"+t.humanize(this.diff),!!_){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser,browser.exports);var Transport$1=requireTransport(),parseqs$2=parseqs$3,parser$3=browser$1,inherit$3=componentInherit,yeast$1=yeast_1,debug$4=browser.exports("engine.io-client:polling"),polling$1=Polling$2,hasXHR2=function(){var e=xmlhttprequest_browser,t=new e({xdomain:!1});return t.responseType!=null}();function Polling$2(e){var t=e&&e.forceBase64;(!hasXHR2||t)&&(this.supportsBinary=!1),Transport$1.call(this,e)}inherit$3(Polling$2,Transport$1);Polling$2.prototype.name="polling";Polling$2.prototype.doOpen=function(){this.poll()};Polling$2.prototype.pause=function(e){var t=this;this.readyState="pausing";function r(){debug$4("paused"),t.readyState="paused",e()}if(this.polling||!this.writable){var n=0;this.polling&&(debug$4("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){debug$4("pre-pause polling complete"),--n||r()})),this.writable||(debug$4("we are currently writing - waiting to pause"),n++,this.once("drain",function(){debug$4("pre-pause writing complete"),--n||r()}))}else r()};Polling$2.prototype.poll=function(){debug$4("polling"),this.polling=!0,this.doPoll(),this.emit("poll")};Polling$2.prototype.onData=function(e){var t=this;debug$4("polling got data %s",e);var r=function(n,o,a){if(t.readyState==="opening"&&n.type==="open"&&t.onOpen(),n.type==="close")return t.onClose(),!1;t.onPacket(n)};parser$3.decodePayload(e,this.socket.binaryType,r),this.readyState!=="closed"&&(this.polling=!1,this.emit("pollComplete"),this.readyState==="open"?this.poll():debug$4('ignoring poll - transport state "%s"',this.readyState))};Polling$2.prototype.doClose=function(){var e=this;function t(){debug$4("writing close packet"),e.write([{type:"close"}])}this.readyState==="open"?(debug$4("transport open - closing"),t()):(debug$4("transport not open - deferring close"),this.once("open",t))};Polling$2.prototype.write=function(e){var t=this;this.writable=!1;var r=function(){t.writable=!0,t.emit("drain")};parser$3.encodePayload(e,this.supportsBinary,function(n){t.doWrite(n,r)})};Polling$2.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",r="";this.timestampRequests!==!1&&(e[this.timestampParam]=yeast$1()),!this.supportsBinary&&!e.sid&&(e.b64=1),e=parseqs$2.encode(e),this.port&&(t==="https"&&Number(this.port)!==443||t==="http"&&Number(this.port)!==80)&&(r=":"+this.port),e.length&&(e="?"+e);var n=this.hostname.indexOf(":")!==-1;return t+"://"+(n?"["+this.hostname+"]":this.hostname)+r+this.path+e};var XMLHttpRequest$2=xmlhttprequest_browser,Polling$1=polling$1,Emitter$2=componentEmitter.exports,inherit$2=componentInherit,debug$3=browser.exports("engine.io-client:polling-xhr"),globalThis$2=globalThis_browser;pollingXhr.exports=XHR$1;pollingXhr.exports.Request=Request;function empty$1(){}function XHR$1(e){if(Polling$1.call(this,e),this.requestTimeout=e.requestTimeout,this.extraHeaders=e.extraHeaders,typeof location<"u"){var t=location.protocol==="https:",r=location.port;r||(r=t?443:80),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}}inherit$2(XHR$1,Polling$1);XHR$1.prototype.supportsBinary=!0;XHR$1.prototype.request=function(e){return e=e||{},e.uri=this.uri(),e.xd=this.xd,e.xs=this.xs,e.agent=this.agent||!1,e.supportsBinary=this.supportsBinary,e.enablesXDR=this.enablesXDR,e.withCredentials=this.withCredentials,e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized,e.requestTimeout=this.requestTimeout,e.extraHeaders=this.extraHeaders,new Request(e)};XHR$1.prototype.doWrite=function(e,t){var r=typeof e!="string"&&e!==void 0,n=this.request({method:"POST",data:e,isBinary:r}),o=this;n.on("success",t),n.on("error",function(a){o.onError("xhr post error",a)}),this.sendXhr=n};XHR$1.prototype.doPoll=function(){debug$3("xhr poll");var e=this.request(),t=this;e.on("data",function(r){t.onData(r)}),e.on("error",function(r){t.onError("xhr poll error",r)}),this.pollXhr=e};function Request(e){this.method=e.method||"GET",this.uri=e.uri,this.xd=!!e.xd,this.xs=!!e.xs,this.async=e.async!==!1,this.data=e.data!==void 0?e.data:null,this.agent=e.agent,this.isBinary=e.isBinary,this.supportsBinary=e.supportsBinary,this.enablesXDR=e.enablesXDR,this.withCredentials=e.withCredentials,this.requestTimeout=e.requestTimeout,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.extraHeaders=e.extraHeaders,this.create()}Emitter$2(Request.prototype);Request.prototype.create=function(){var e={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized;var t=this.xhr=new XMLHttpRequest$2(e),r=this;try{debug$3("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(var n in this.extraHeaders)this.extraHeaders.hasOwnProperty(n)&&t.setRequestHeader(n,this.extraHeaders[n])}}catch{}if(this.method==="POST")try{this.isBinary?t.setRequestHeader("Content-type","application/octet-stream"):t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}"withCredentials"in t&&(t.withCredentials=this.withCredentials),this.requestTimeout&&(t.timeout=this.requestTimeout),this.hasXDR()?(t.onload=function(){r.onLoad()},t.onerror=function(){r.onError(t.responseText)}):t.onreadystatechange=function(){if(t.readyState===2)try{var o=t.getResponseHeader("Content-Type");(r.supportsBinary&&o==="application/octet-stream"||o==="application/octet-stream; charset=UTF-8")&&(t.responseType="arraybuffer")}catch{}t.readyState===4&&(t.status===200||t.status===1223?r.onLoad():setTimeout(function(){r.onError(typeof t.status=="number"?t.status:0)},0))},debug$3("xhr data %s",this.data),t.send(this.data)}catch(o){setTimeout(function(){r.onError(o)},0);return}typeof document<"u"&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)};Request.prototype.onSuccess=function(){this.emit("success"),this.cleanup()};Request.prototype.onData=function(e){this.emit("data",e),this.onSuccess()};Request.prototype.onError=function(e){this.emit("error",e),this.cleanup(!0)};Request.prototype.cleanup=function(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=empty$1:this.xhr.onreadystatechange=empty$1,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Request.requests[this.index],this.xhr=null}};Request.prototype.onLoad=function(){var e;try{var t;try{t=this.xhr.getResponseHeader("Content-Type")}catch{}t==="application/octet-stream"||t==="application/octet-stream; charset=UTF-8"?e=this.xhr.response||this.xhr.responseText:e=this.xhr.responseText}catch(r){this.onError(r)}e!=null&&this.onData(e)};Request.prototype.hasXDR=function(){return typeof XDomainRequest<"u"&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};Request.requestsCount=0;Request.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",unloadHandler);else if(typeof addEventListener=="function"){var terminationEvent="onpagehide"in globalThis$2?"pagehide":"unload";addEventListener(terminationEvent,unloadHandler,!1)}}function unloadHandler(){for(var e in Request.requests)Request.requests.hasOwnProperty(e)&&Request.requests[e].abort()}var Polling=polling$1,inherit$1=componentInherit,globalThis$1=globalThis_browser,pollingJsonp=JSONPPolling,rNewline=/\n/g,rEscapedNewline=/\\n/g,callbacks;function empty(){}function JSONPPolling(e){Polling.call(this,e),this.query=this.query||{},callbacks||(callbacks=globalThis$1.___eio=globalThis$1.___eio||[]),this.index=callbacks.length;var t=this;callbacks.push(function(r){t.onData(r)}),this.query.j=this.index,typeof addEventListener=="function"&&addEventListener("beforeunload",function(){t.script&&(t.script.onerror=empty)},!1)}inherit$1(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=!1;JSONPPolling.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(o){e.onError("jsonp poll error",o)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(t,r):(document.head||document.body).appendChild(t),this.script=t;var n=typeof navigator<"u"&&/gecko/i.test(navigator.userAgent);n&&setTimeout(function(){var o=document.createElement("iframe");document.body.appendChild(o),document.body.removeChild(o)},100)};JSONPPolling.prototype.doWrite=function(e,t){var r=this;if(!this.form){var n=document.createElement("form"),o=document.createElement("textarea"),a=this.iframeId="eio_iframe_"+this.index,l;n.className="socketio",n.style.position="absolute",n.style.top="-1000px",n.style.left="-1000px",n.target=a,n.method="POST",n.setAttribute("accept-charset","utf-8"),o.name="d",n.appendChild(o),document.body.appendChild(n),this.form=n,this.area=o}this.form.action=this.uri();function c(){u(),t()}function u(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(b){r.onError("jsonp polling iframe removal error",b)}try{var _='