libp2p 0.45.4 → 0.45.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -12,13 +12,13 @@
12
12
  `,r};Tf.decode=function(t){for(var e=[],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^:]+)/,i=/\r?\n/,s;s=r.exec(t),!!s;){var o=s[1];o==="NEW CERTIFICATE REQUEST"&&(o="CERTIFICATE REQUEST");var a={type:o,procType:null,contentDomain:null,dekInfo:null,headers:[],body:ks.util.decode64(s[3])};if(e.push(a),!!s[2]){for(var c=s[2].split(i),u=0;s&&u<c.length;){for(var l=c[u].replace(/\s+$/,""),f=u+1;f<c.length;++f){var h=c[f];if(!/\s/.test(h[0]))break;l+=h,u=f}if(s=l.match(n),s){for(var d={name:s[1],values:[]},p=s[2].split(","),m=0;m<p.length;++m)d.values.push(Tg(p[m]));if(a.procType)if(!a.contentDomain&&d.name==="Content-Domain")a.contentDomain=p[0]||"";else if(!a.dekInfo&&d.name==="DEK-Info"){if(d.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');a.dekInfo={algorithm:p[0],parameters:p[1]||null}}else a.headers.push(d);else{if(d.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(d.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');a.procType={version:p[0],type:p[1]}}}++u}if(a.procType==="ENCRYPTED"&&!a.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(e.length===0)throw new Error("Invalid PEM formatted message.");return e};function Ns(t){for(var e=t.name+": ",r=[],n=function(c,u){return" "+u},i=0;i<t.values.length;++i)r.push(t.values[i].replace(/^(\S+\r\n)/,n));e+=r.join(",")+`\r
13
13
  `;for(var s=0,o=-1,i=0;i<e.length;++i,++s)if(s>65&&o!==-1){var a=e[o];a===","?(++o,e=e.substr(0,o)+`\r
14
14
  `+e.substr(o)):e=e.substr(0,o)+`\r
15
- `+a+e.substr(o+1),s=i-o-1,o=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(o=i);return e}function Tg(t){return t.replace(/^\s+/,"")}});var Mf=R(($_,Of)=>{var Mt=se();$r();Ie();var Df=Of.exports=Mt.sha256=Mt.sha256||{};Mt.md.sha256=Mt.md.algorithms.sha256=Df;Df.create=function(){Nf||Bg();var t=null,e=Mt.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 i=n.messageLengthSize/4,s=0;s<i;++s)n.fullMessageLength.push(0);return e=Mt.util.createBuffer(),t={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=Mt.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),Pf(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Mt.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Va.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4,h5:t.h5,h6:t.h6,h7:t.h7};Pf(f,r,i);var h=Mt.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var Va=null,Nf=!1,kf=null;function Bg(){Va=String.fromCharCode(128),Va+=Mt.util.fillString(String.fromCharCode(0),64),kf=[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],Nf=!0}function Pf(t,e,r){for(var n,i,s,o,a,c,u,l,f,h,d,p,m,y,g,w=r.length();w>=64;){for(u=0;u<16;++u)e[u]=r.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=t.h0,f=t.h1,h=t.h2,d=t.h3,p=t.h4,m=t.h5,y=t.h6,g=t.h7,u=0;u<64;++u)o=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=y^p&(m^y),s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|h&(l^f),n=g+o+a+kf[u]+e[u],i=s+c,g=y,y=m,m=p,p=d+n>>>0,d=h,h=f,f=l,l=n+i>>>0;t.h0=t.h0+l|0,t.h1=t.h1+f|0,t.h2=t.h2+h|0,t.h3=t.h3+d|0,t.h4=t.h4+p|0,t.h5=t.h5+m|0,t.h6=t.h6+y|0,t.h7=t.h7+g|0,w-=64}}});var Uf=R((z_,Ff)=>{var Ft=se();Ie();var Os=null;Ft.util.isNodejs&&!Ft.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Os=zr());var Lg=Ff.exports=Ft.prng=Ft.prng||{};Lg.create=function(t){for(var e={plugin:t,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=t.md,n=new Array(32),i=0;i<32;++i)n[i]=r.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,h=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,m=Ft.util.createBuffer();e.key=null,y();function y(g){if(g)return l(g);if(m.length()>=u)return l(null,m.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return Ft.util.nextTick(function(){s(y)});var w=f(e.key,e.seed);e.generated+=w.length,m.putBytes(w),e.key=d(f(e.key,h(e.seed))),e.seed=p(f(e.key,e.seed)),Ft.util.setImmediate(y)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,h=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=Ft.util.createBuffer();p.length()<u;){e.generated>1048575&&(e.key=null),e.key===null&&o();var m=l(e.key,e.seed);e.generated+=m.length,p.putBytes(m),e.key=h(l(e.key,f(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function s(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,h){if(f)return u(f);e.collect(h),a(),u()})}function o(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l===0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var h=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(h),e.generated=0}function c(u){var l=null,f=Ft.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(l=function(C){return h.getRandomValues(C)});var d=Ft.util.createBuffer();if(l)for(;d.length()<u;){var p=Math.max(1,Math.min(u-d.length(),65536)/4),m=new Uint32Array(Math.floor(p));try{l(m);for(var y=0;y<m.length;++y)d.putInt32(m[y])}catch(C){if(!(typeof QuotaExceededError<"u"&&C instanceof QuotaExceededError))throw C}}if(d.length()<u)for(var g,w,_,N=Math.floor(Math.random()*65536);d.length()<u;){w=16807*(N&65535),g=16807*(N>>16),w+=(g&32767)<<16,w+=g>>15,w=(w&2147483647)+(w>>31),N=w&4294967295;for(var y=0;y<3;++y)_=N>>>(y<<3),_^=Math.floor(Math.random()*256),d.putByte(_&255)}return d.getBytes(u)}return Os?(e.seedFile=function(u,l){Os.randomBytes(u,function(f,h){if(f)return l(f);l(null,h.toString())})},e.seedFileSync=function(u){return Os.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f<l;++f)e.pools[e.pool].update(u.substr(f,1)),e.pool=e.pool===31?0:e.pool+1},e.collectInt=function(u,l){for(var f="",h=0;h<l;h+=8)f+=String.fromCharCode(u>>h&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,h){function d(p){var m=p.data;m.forge&&m.forge.prng&&(self.removeEventListener("message",d),h(m.forge.prng.err,m.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var h=f.data;h.forge&&h.forge.prng&&e.seedFile(h.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var Ri=R((H_,qa)=>{var Me=se();Ls();Mf();Uf();Ie();(function(){if(Me.random&&Me.random.getBytes){qa.exports=Me.random;return}(function(t){var e={},r=new Array(4),n=Me.util.createBuffer();e.formatKey=function(f){var h=Me.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),Me.aes._expandKey(f,!1)},e.formatSeed=function(f){var h=Me.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},e.cipher=function(f,h){return Me.aes._updateBlock(f,h,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=Me.md.sha256;function i(){var f=Me.prng.create(e);return f.getBytes=function(h,d){return f.generate(h,d)},f.getBytesSync=function(h){return f.generate(h)},f}var s=i(),o=null,a=Me.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(o=function(f){return c.getRandomValues(f)}),Me.options.usePureJavaScript||!Me.util.isNodejs&&!o){if(typeof window>"u"||window.document,s.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}s.collect(u),u=null}t&&(t().mousemove(function(f){s.collectInt(f.clientX,16),s.collectInt(f.clientY,16)}),t().keypress(function(f){s.collectInt(f.charCode,8)}))}if(!Me.random)Me.random=s;else for(var l in s)Me.random[l]=s[l];Me.random.createInstance=i,qa.exports=Me.random})(typeof jQuery<"u"?jQuery:null)})()});var $f=R((G_,qf)=>{var et=se();Ie();var $a=[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],Kf=[1,2,3,5],Pg=function(t,e){return t<<e&65535|(t&65535)>>16-e},Dg=function(t,e){return(t&65535)>>e|t<<16-e&65535};qf.exports=et.rc2=et.rc2||{};et.rc2.expandKey=function(t,e){typeof t=="string"&&(t=et.util.createBuffer(t)),e=e||128;var r=t,n=t.length(),i=e,s=Math.ceil(i/8),o=255>>(i&7),a;for(a=n;a<128;a++)r.putByte($a[r.at(a-1)+r.at(a-n)&255]);for(r.setAt(128-s,$a[r.at(128-s)&o]),a=127-s;a>=0;a--)r.setAt(a,$a[r.at(a+1)^r.at(a+s)]);return r};var Vf=function(t,e,r){var n=!1,i=null,s=null,o=null,a,c,u,l,f=[];for(t=et.rc2.expandKey(t,e),u=0;u<64;u++)f.push(t.getInt16Le());r?(a=function(p){for(u=0;u<4;u++)p[u]+=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=Pg(p[u],Kf[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=f[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=Dg(p[u],Kf[u]),p[u]-=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),l--},c=function(p){for(u=3;u>=0;u--)p[u]-=f[p[(u+3)%4]&63]});var h=function(p){var m=[];for(u=0;u<4;u++){var y=i.getInt16Le();o!==null&&(r?y^=o.getInt16Le():o.putInt16Le(y)),m.push(y&65535)}l=r?0:63;for(var g=0;g<p.length;g++)for(var w=0;w<p[g][0];w++)p[g][1](m);for(u=0;u<4;u++)o!==null&&(r?o.putInt16Le(m[u]):m[u]^=o.getInt16Le()),s.putInt16Le(m[u])},d=null;return d={start:function(p,m){p&&typeof p=="string"&&(p=et.util.createBuffer(p)),n=!1,i=et.util.createBuffer(),s=m||new et.util.createBuffer,o=p,d.output=s},update:function(p){for(n||i.putBuffer(p);i.length()>=8;)h([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var m=!0;if(r)if(p)m=p(8,i,!r);else{var y=i.length()===8?8:8-i.length();i.fillWithByte(y,y)}if(m&&(n=!0,d.update()),!r&&(m=i.length()===0,m))if(p)m=p(8,s,!r);else{var g=s.length(),w=s.at(g-1);w>g?m=!1:s.truncate(w)}return m}},d};et.rc2.startEncrypting=function(t,e,r){var n=et.rc2.createEncryptionCipher(t,128);return n.start(e,r),n};et.rc2.createEncryptionCipher=function(t,e){return Vf(t,e,!0)};et.rc2.startDecrypting=function(t,e,r){var n=et.rc2.createDecryptionCipher(t,128);return n.start(e,r),n};et.rc2.createDecryptionCipher=function(t,e){return Vf(t,e,!1)}});var Us=R((Y_,Zf)=>{var za=se();Zf.exports=za.jsbn=za.jsbn||{};var tr,Ng=0xdeadbeefcafe,zf=(Ng&16777215)==15715070;function S(t,e,r){this.data=[],t!=null&&(typeof t=="number"?this.fromNumber(t,e,r):e==null&&typeof t!="string"?this.fromString(t,256):this.fromString(t,e))}za.jsbn.BigInteger=S;function J(){return new S(null)}function kg(t,e,r,n,i,s){for(;--s>=0;){var o=e*this.data[t++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=o&67108863}return i}function Og(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this.data[t]&32767,u=this.data[t++]>>15,l=a*c+u*o;c=o*c+((l&32767)<<15)+r.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=c&1073741823}return i}function Hf(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this.data[t]&16383,u=this.data[t++]>>14,l=a*c+u*o;c=o*c+((l&16383)<<14)+r.data[n]+i,i=(c>>28)+(l>>14)+a*u,r.data[n++]=c&268435455}return i}typeof navigator>"u"?(S.prototype.am=Hf,tr=28):zf&&navigator.appName=="Microsoft Internet Explorer"?(S.prototype.am=Og,tr=30):zf&&navigator.appName!="Netscape"?(S.prototype.am=kg,tr=26):(S.prototype.am=Hf,tr=28);S.prototype.DB=tr;S.prototype.DM=(1<<tr)-1;S.prototype.DV=1<<tr;var Ha=52;S.prototype.FV=Math.pow(2,Ha);S.prototype.F1=Ha-tr;S.prototype.F2=2*tr-Ha;var Mg="0123456789abcdefghijklmnopqrstuvwxyz",Ms=new Array,Rn,mt;Rn="0".charCodeAt(0);for(mt=0;mt<=9;++mt)Ms[Rn++]=mt;Rn="a".charCodeAt(0);for(mt=10;mt<36;++mt)Ms[Rn++]=mt;Rn="A".charCodeAt(0);for(mt=10;mt<36;++mt)Ms[Rn++]=mt;function Gf(t){return Mg.charAt(t)}function Yf(t,e){var r=Ms[t.charCodeAt(e)];return r??-1}function Fg(t){for(var e=this.t-1;e>=0;--e)t.data[e]=this.data[e];t.t=this.t,t.s=this.s}function Ug(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0}function yr(t){var e=J();return e.fromInt(t),e}function Kg(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==256)r=8;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else{this.fromRadix(t,e);return}this.t=0,this.s=0;for(var n=t.length,i=!1,s=0;--n>=0;){var o=r==8?t[n]&255:Yf(t,n);if(o<0){t.charAt(n)=="-"&&(i=!0);continue}i=!1,s==0?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this.data[this.t++]=o>>this.DB-s):this.data[this.t-1]|=o<<s,s+=r,s>=this.DB&&(s-=this.DB)}r==8&&t[0]&128&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&S.ZERO.subTo(this,this)}function Vg(){for(var t=this.s&this.DM;this.t>0&&this.data[this.t-1]==t;)--this.t}function qg(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else return this.toRadix(t);var r=(1<<e)-1,n,i=!1,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this.data[o]>>a)>0&&(i=!0,s=Gf(n));o>=0;)a<e?(n=(this.data[o]&(1<<a)-1)<<e-a,n|=this.data[--o]>>(a+=this.DB-e)):(n=this.data[o]>>(a-=e)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=Gf(n));return i?s:"0"}function $g(){var t=J();return S.ZERO.subTo(this,t),t}function zg(){return this.s<0?this.negate():this}function Hg(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this.data[r]-t.data[r])!=0)return e;return 0}function Fs(t){var e=1,r;return(r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function Gg(){return this.t<=0?0:this.DB*(this.t-1)+Fs(this.data[this.t-1]^this.s&this.DM)}function Yg(t,e){var r;for(r=this.t-1;r>=0;--r)e.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)e.data[r]=0;e.t=this.t+t,e.s=this.s}function Wg(t,e){for(var r=t;r<this.t;++r)e.data[r-t]=this.data[r];e.t=Math.max(this.t-t,0),e.s=this.s}function Qg(t,e){var r=t%this.DB,n=this.DB-r,i=(1<<n)-1,s=Math.floor(t/this.DB),o=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)e.data[a+s+1]=this.data[a]>>n|o,o=(this.data[a]&i)<<r;for(a=s-1;a>=0;--a)e.data[a]=0;e.data[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp()}function Xg(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<<n)-1;e.data[0]=this.data[r]>>n;for(var o=r+1;o<this.t;++o)e.data[o-r-1]|=(this.data[o]&s)<<i,e.data[o-r]=this.data[o]>>n;n>0&&(e.data[this.t-r-1]|=(this.s&s)<<i),e.t=this.t-r,e.clamp()}function Zg(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this.data[r]-t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n-=t.s;r<this.t;)n+=this.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<t.t;)n-=t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n-=t.s}e.s=n<0?-1:0,n<-1?e.data[r++]=this.DV+n:n>0&&(e.data[r++]=n),e.t=r,e.clamp()}function jg(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i<n.t;++i)e.data[i+r.t]=r.am(0,n.data[i],e,i,0,r.t);e.s=0,e.clamp(),this.s!=t.s&&S.ZERO.subTo(e,e)}function Jg(t){for(var e=this.abs(),r=t.t=2*e.t;--r>=0;)t.data[r]=0;for(r=0;r<e.t-1;++r){var n=e.am(r,e.data[r],t,2*r,0,1);(t.data[r+e.t]+=e.am(r+1,2*e.data[r],t,2*r+1,n,e.t-r-1))>=e.DV&&(t.data[r+e.t]-=e.DV,t.data[r+e.t+1]=1)}t.t>0&&(t.data[t.t-1]+=e.am(r,e.data[r],t,2*r,0,1)),t.s=0,t.clamp()}function e1(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=J());var s=J(),o=this.s,a=t.s,c=this.DB-Fs(n.data[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var u=s.t,l=s.data[u-1];if(l!=0){var f=l*(1<<this.F1)+(u>1?s.data[u-2]>>this.F2:0),h=this.FV/f,d=(1<<this.F1)/f,p=1<<this.F2,m=r.t,y=m-u,g=e??J();for(s.dlShiftTo(y,g),r.compareTo(g)>=0&&(r.data[r.t++]=1,r.subTo(g,r)),S.ONE.dlShiftTo(u,g),g.subTo(s,s);s.t<u;)s.data[s.t++]=0;for(;--y>=0;){var w=r.data[--m]==l?this.DM:Math.floor(r.data[m]*h+(r.data[m-1]+p)*d);if((r.data[m]+=s.am(0,w,r,y,0,u))<w)for(s.dlShiftTo(y,g),r.subTo(g,r);r.data[m]<--w;)r.subTo(g,r)}e!=null&&(r.drShiftTo(u,e),o!=a&&S.ZERO.subTo(e,e)),r.t=u,r.clamp(),c>0&&r.rShiftTo(c,r),o<0&&S.ZERO.subTo(r,r)}}}function t1(t){var e=J();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(S.ZERO)>0&&t.subTo(e,e),e}function Hr(t){this.m=t}function r1(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function n1(t){return t}function i1(t){t.divRemTo(this.m,null,t)}function s1(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function o1(t,e){t.squareTo(e),this.reduce(e)}Hr.prototype.convert=r1;Hr.prototype.revert=n1;Hr.prototype.reduce=i1;Hr.prototype.mulTo=s1;Hr.prototype.sqrTo=o1;function a1(){if(this.t<1)return 0;var t=this.data[0];if(!(t&1))return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Gr(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t}function c1(t){var e=J();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(S.ZERO)>0&&this.m.subTo(e,e),e}function u1(t){var e=J();return t.copyTo(e),this.reduce(e),e}function l1(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var e=0;e<this.m.t;++e){var r=t.data[e]&32767,n=r*this.mpl+((r*this.mph+(t.data[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t.data[r]+=this.m.am(0,n,t,e,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function f1(t,e){t.squareTo(e),this.reduce(e)}function h1(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Gr.prototype.convert=c1;Gr.prototype.revert=u1;Gr.prototype.reduce=l1;Gr.prototype.mulTo=h1;Gr.prototype.sqrTo=f1;function d1(){return(this.t>0?this.data[0]&1:this.s)==0}function p1(t,e){if(t>4294967295||t<1)return S.ONE;var r=J(),n=J(),i=e.convert(this),s=Fs(t)-1;for(i.copyTo(r);--s>=0;)if(e.sqrTo(r,n),(t&1<<s)>0)e.mulTo(n,i,r);else{var o=r;r=n,n=o}return e.revert(r)}function m1(t,e){var r;return t<256||e.isEven()?r=new Hr(e):r=new Gr(e),this.exp(t,r)}S.prototype.copyTo=Fg;S.prototype.fromInt=Ug;S.prototype.fromString=Kg;S.prototype.clamp=Vg;S.prototype.dlShiftTo=Yg;S.prototype.drShiftTo=Wg;S.prototype.lShiftTo=Qg;S.prototype.rShiftTo=Xg;S.prototype.subTo=Zg;S.prototype.multiplyTo=jg;S.prototype.squareTo=Jg;S.prototype.divRemTo=e1;S.prototype.invDigit=a1;S.prototype.isEven=d1;S.prototype.exp=p1;S.prototype.toString=qg;S.prototype.negate=$g;S.prototype.abs=zg;S.prototype.compareTo=Hg;S.prototype.bitLength=Gg;S.prototype.mod=t1;S.prototype.modPowInt=m1;S.ZERO=yr(0);S.ONE=yr(1);function y1(){var t=J();return this.copyTo(t),t}function g1(){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)<<this.DB|this.data[0]}function x1(){return this.t==0?this.s:this.data[0]<<24>>24}function w1(){return this.t==0?this.s:this.data[0]<<16>>16}function v1(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function E1(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function b1(t){if(t==null&&(t=10),this.signum()==0||t<2||t>36)return"0";var e=this.chunkSize(t),r=Math.pow(t,e),n=yr(r),i=J(),s=J(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(t).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(t)+o}function _1(t,e){this.fromInt(0),e==null&&(e=10);for(var r=this.chunkSize(e),n=Math.pow(e,r),i=!1,s=0,o=0,a=0;a<t.length;++a){var c=Yf(t,a);if(c<0){t.charAt(a)=="-"&&this.signum()==0&&(i=!0);continue}o=e*o+c,++s>=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),i&&S.ZERO.subTo(this,this)}function S1(t,e,r){if(typeof e=="number")if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(S.ONE.shiftLeft(t-1),Ga,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(S.ONE.shiftLeft(t-1),this);else{var n=new Array,i=t&7;n.length=(t>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<<i)-1:n[0]=0,this.fromString(n,256)}}function A1(){var t=this.t,e=new Array;e[0]=this.s;var r=this.DB-t*this.DB%8,n,i=0;if(t-- >0)for(r<this.DB&&(n=this.data[t]>>r)!=(this.s&this.DM)>>r&&(e[i++]=n|this.s<<this.DB-r);t>=0;)r<8?(n=(this.data[t]&(1<<r)-1)<<8-r,n|=this.data[--t]>>(r+=this.DB-8)):(n=this.data[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function I1(t){return this.compareTo(t)==0}function R1(t){return this.compareTo(t)<0?this:t}function C1(t){return this.compareTo(t)>0?this:t}function T1(t,e,r){var n,i,s=Math.min(t.t,this.t);for(n=0;n<s;++n)r.data[n]=e(this.data[n],t.data[n]);if(t.t<this.t){for(i=t.s&this.DM,n=s;n<this.t;++n)r.data[n]=e(this.data[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<t.t;++n)r.data[n]=e(i,t.data[n]);r.t=t.t}r.s=e(this.s,t.s),r.clamp()}function B1(t,e){return t&e}function L1(t){var e=J();return this.bitwiseTo(t,B1,e),e}function Ga(t,e){return t|e}function P1(t){var e=J();return this.bitwiseTo(t,Ga,e),e}function Wf(t,e){return t^e}function D1(t){var e=J();return this.bitwiseTo(t,Wf,e),e}function Qf(t,e){return t&~e}function N1(t){var e=J();return this.bitwiseTo(t,Qf,e),e}function k1(){for(var t=J(),e=0;e<this.t;++e)t.data[e]=this.DM&~this.data[e];return t.t=this.t,t.s=~this.s,t}function O1(t){var e=J();return t<0?this.rShiftTo(-t,e):this.lShiftTo(t,e),e}function M1(t){var e=J();return t<0?this.lShiftTo(-t,e):this.rShiftTo(t,e),e}function F1(t){if(t==0)return-1;var e=0;return t&65535||(t>>=16,e+=16),t&255||(t>>=8,e+=8),t&15||(t>>=4,e+=4),t&3||(t>>=2,e+=2),t&1||++e,e}function U1(){for(var t=0;t<this.t;++t)if(this.data[t]!=0)return t*this.DB+F1(this.data[t]);return this.s<0?this.t*this.DB:-1}function K1(t){for(var e=0;t!=0;)t&=t-1,++e;return e}function V1(){for(var t=0,e=this.s&this.DM,r=0;r<this.t;++r)t+=K1(this.data[r]^e);return t}function q1(t){var e=Math.floor(t/this.DB);return e>=this.t?this.s!=0:(this.data[e]&1<<t%this.DB)!=0}function $1(t,e){var r=S.ONE.shiftLeft(t);return this.bitwiseTo(r,e,r),r}function z1(t){return this.changeBit(t,Ga)}function H1(t){return this.changeBit(t,Qf)}function G1(t){return this.changeBit(t,Wf)}function Y1(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this.data[r]+t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n+=t.s;r<this.t;)n+=this.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<t.t;)n+=t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=t.s}e.s=n<0?-1:0,n>0?e.data[r++]=n:n<-1&&(e.data[r++]=this.DV+n),e.t=r,e.clamp()}function W1(t){var e=J();return this.addTo(t,e),e}function Q1(t){var e=J();return this.subTo(t,e),e}function X1(t){var e=J();return this.multiplyTo(t,e),e}function Z1(t){var e=J();return this.divRemTo(t,e,null),e}function j1(t){var e=J();return this.divRemTo(t,null,e),e}function J1(t){var e=J(),r=J();return this.divRemTo(t,e,r),new Array(e,r)}function ex(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function tx(t,e){if(t!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=t;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function Ci(){}function Xf(t){return t}function rx(t,e,r){t.multiplyTo(e,r)}function nx(t,e){t.squareTo(e)}Ci.prototype.convert=Xf;Ci.prototype.revert=Xf;Ci.prototype.mulTo=rx;Ci.prototype.sqrTo=nx;function ix(t){return this.exp(t,new Ci)}function sx(t,e,r){var n=Math.min(this.t+t.t,e);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var i;for(i=r.t-this.t;n<i;++n)r.data[n+this.t]=this.am(0,t.data[n],r,n,0,this.t);for(i=Math.min(t.t,e);n<i;++n)this.am(0,t.data[n],r,n,0,e-n);r.clamp()}function ox(t,e,r){--e;var n=r.t=this.t+t.t-e;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(e-this.t,0);n<t.t;++n)r.data[this.t+n-e]=this.am(e-n,t.data[n],r,0,0,this.t+n-e);r.clamp(),r.drShiftTo(1,r)}function Cn(t){this.r2=J(),this.q3=J(),S.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}function ax(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=J();return t.copyTo(e),this.reduce(e),e}function cx(t){return t}function ux(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function lx(t,e){t.squareTo(e),this.reduce(e)}function fx(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Cn.prototype.convert=ax;Cn.prototype.revert=cx;Cn.prototype.reduce=ux;Cn.prototype.mulTo=fx;Cn.prototype.sqrTo=lx;function hx(t,e){var r=t.bitLength(),n,i=yr(1),s;if(r<=0)return i;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?s=new Hr(e):e.isEven()?s=new Cn(e):s=new Gr(e);var o=new Array,a=3,c=n-1,u=(1<<n)-1;if(o[1]=s.convert(this),n>1){var l=J();for(s.sqrTo(o[1],l);a<=u;)o[a]=J(),s.mulTo(l,o[a-2],o[a]),a+=2}var f=t.t-1,h,d=!0,p=J(),m;for(r=Fs(t.data[f])-1;f>=0;){for(r>=c?h=t.data[f]>>r-c&u:(h=(t.data[f]&(1<<r+1)-1)<<c-r,f>0&&(h|=t.data[f-1]>>this.DB+r-c)),a=n;!(h&1);)h>>=1,--a;if((r-=a)<0&&(r+=this.DB,--f),d)o[h].copyTo(i),d=!1;else{for(;a>1;)s.sqrTo(i,p),s.sqrTo(p,i),a-=2;a>0?s.sqrTo(i,p):(m=i,i=p,p=m),s.mulTo(p,o[h],i)}for(;f>=0&&!(t.data[f]&1<<r);)s.sqrTo(i,p),m=i,i=p,p=m,--r<0&&(r=this.DB-1,--f)}return s.revert(i)}function dx(t){var e=this.s<0?this.negate():this.clone(),r=t.s<0?t.negate():t.clone();if(e.compareTo(r)<0){var n=e;e=r,r=n}var i=e.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return e;for(i<s&&(s=i),s>0&&(e.rShiftTo(s,e),r.rShiftTo(s,r));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),e.compareTo(r)>=0?(e.subTo(r,e),e.rShiftTo(1,e)):(r.subTo(e,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r}function px(t){if(t<=0)return 0;var e=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(e==0)r=this.data[0]%t;else for(var n=this.t-1;n>=0;--n)r=(e*r+this.data[n])%t;return r}function mx(t){var e=t.isEven();if(this.isEven()&&e||t.signum()==0)return S.ZERO;for(var r=t.clone(),n=this.clone(),i=yr(1),s=yr(0),o=yr(0),a=yr(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),e?((!i.isEven()||!s.isEven())&&(i.addTo(this,i),s.subTo(t,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(t,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),e&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(r,n),e&&o.subTo(i,o),a.subTo(s,a))}if(n.compareTo(S.ONE)!=0)return S.ZERO;if(a.compareTo(t)>=0)return a.subtract(t);if(a.signum()<0)a.addTo(t,a);else return a;return a.signum()<0?a.add(t):a}var _t=[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],yx=(1<<26)/_t[_t.length-1];function gx(t){var e,r=this.abs();if(r.t==1&&r.data[0]<=_t[_t.length-1]){for(e=0;e<_t.length;++e)if(r.data[0]==_t[e])return!0;return!1}if(r.isEven())return!1;for(e=1;e<_t.length;){for(var n=_t[e],i=e+1;i<_t.length&&n<yx;)n*=_t[i++];for(n=r.modInt(n);e<i;)if(n%_t[e++]==0)return!1}return r.millerRabin(t)}function xx(t){var e=this.subtract(S.ONE),r=e.getLowestSetBit();if(r<=0)return!1;for(var n=e.shiftRight(r),i=wx(),s,o=0;o<t;++o){do s=new S(this.bitLength(),i);while(s.compareTo(S.ONE)<=0||s.compareTo(e)>=0);var a=s.modPow(n,this);if(a.compareTo(S.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++<r&&a.compareTo(e)!=0;)if(a=a.modPowInt(2,this),a.compareTo(S.ONE)==0)return!1;if(a.compareTo(e)!=0)return!1}}return!0}function wx(){return{nextBytes:function(t){for(var e=0;e<t.length;++e)t[e]=Math.floor(Math.random()*256)}}}S.prototype.chunkSize=v1;S.prototype.toRadix=b1;S.prototype.fromRadix=_1;S.prototype.fromNumber=S1;S.prototype.bitwiseTo=T1;S.prototype.changeBit=$1;S.prototype.addTo=Y1;S.prototype.dMultiply=ex;S.prototype.dAddOffset=tx;S.prototype.multiplyLowerTo=sx;S.prototype.multiplyUpperTo=ox;S.prototype.modInt=px;S.prototype.millerRabin=xx;S.prototype.clone=y1;S.prototype.intValue=g1;S.prototype.byteValue=x1;S.prototype.shortValue=w1;S.prototype.signum=E1;S.prototype.toByteArray=A1;S.prototype.equals=I1;S.prototype.min=R1;S.prototype.max=C1;S.prototype.and=L1;S.prototype.or=P1;S.prototype.xor=D1;S.prototype.andNot=N1;S.prototype.not=k1;S.prototype.shiftLeft=O1;S.prototype.shiftRight=M1;S.prototype.getLowestSetBit=U1;S.prototype.bitCount=V1;S.prototype.testBit=q1;S.prototype.setBit=z1;S.prototype.clearBit=H1;S.prototype.flipBit=G1;S.prototype.add=W1;S.prototype.subtract=Q1;S.prototype.multiply=X1;S.prototype.divide=Z1;S.prototype.remainder=j1;S.prototype.divideAndRemainder=J1;S.prototype.modPow=hx;S.prototype.modInverse=mx;S.prototype.pow=ix;S.prototype.gcd=dx;S.prototype.isProbablePrime=gx});var r0=R((W_,t0)=>{var Ut=se();$r();Ie();var Jf=t0.exports=Ut.sha1=Ut.sha1||{};Ut.md.sha1=Ut.md.algorithms.sha1=Jf;Jf.create=function(){e0||vx();var t=null,e=Ut.util.createBuffer(),r=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s<i;++s)n.fullMessageLength.push(0);return e=Ut.util.createBuffer(),t={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=Ut.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),jf(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Ut.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Ya.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4};jf(f,r,i);var h=Ut.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var Ya=null,e0=!1;function vx(){Ya=String.fromCharCode(128),Ya+=Ut.util.fillString(String.fromCharCode(0),64),e0=!0}function jf(t,e,r){for(var n,i,s,o,a,c,u,l,f=r.length();f>=64;){for(i=t.h0,s=t.h1,o=t.h2,a=t.h3,c=t.h4,l=0;l<16;++l)n=r.getInt32(),e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s&o|a&(s^o),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;t.h0=t.h0+i|0,t.h1=t.h1+s|0,t.h2=t.h2+o|0,t.h3=t.h3+a|0,t.h4=t.h4+c|0,f-=64}}});var s0=R((Q_,i0)=>{var Kt=se();Ie();Ri();r0();var n0=i0.exports=Kt.pkcs1=Kt.pkcs1||{};n0.encode_rsa_oaep=function(t,e,r){var n,i,s,o;typeof r=="string"?(n=r,i=arguments[3]||void 0,s=arguments[4]||void 0):r&&(n=r.label||void 0,i=r.seed||void 0,s=r.md||void 0,r.mgf1&&r.mgf1.md&&(o=r.mgf1.md)),s?s.start():s=Kt.md.sha1.create(),o||(o=s);var a=Math.ceil(t.n.bitLength()/8),c=a-2*s.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),s.update(n,"raw");for(var l=s.digest(),f="",h=c-e.length,d=0;d<h;d++)f+="\0";var p=l.getBytes()+f+""+e;if(!i)i=Kt.random.getBytes(s.digestLength);else if(i.length!==s.digestLength){var u=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=s.digestLength,u}var m=Ks(i,a-s.digestLength-1,o),y=Kt.util.xorBytes(p,m,p.length),g=Ks(y,s.digestLength,o),w=Kt.util.xorBytes(i,g,i.length);return"\0"+w+y};n0.decode_rsa_oaep=function(t,e,r){var n,i,s;typeof r=="string"?(n=r,i=arguments[3]||void 0):r&&(n=r.label||void 0,i=r.md||void 0,r.mgf1&&r.mgf1.md&&(s=r.mgf1.md));var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var y=new Error("RSAES-OAEP encoded message length is invalid.");throw y.length=e.length,y.expectedLength=o,y}if(i===void 0?i=Kt.md.sha1.create():i.start(),s||(s=i),o<2*i.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");n||(n=""),i.update(n,"raw");for(var a=i.digest().getBytes(),c=e.charAt(0),u=e.substring(1,i.digestLength+1),l=e.substring(1+i.digestLength),f=Ks(l,i.digestLength,s),h=Kt.util.xorBytes(u,f,u.length),d=Ks(h,o-i.digestLength-1,s),p=Kt.util.xorBytes(l,d,l.length),m=p.substring(0,i.digestLength),y=c!=="\0",g=0;g<i.digestLength;++g)y|=a.charAt(g)!==m.charAt(g);for(var w=1,_=i.digestLength,N=i.digestLength;N<p.length;N++){var C=p.charCodeAt(N),T=C&1^1,H=w?65534:0;y|=C&H,w=w&T,_+=w}if(y||p.charCodeAt(_)!==1)throw new Error("Invalid RSAES-OAEP padding.");return p.substring(_+1)};function Ks(t,e,r){r||(r=Kt.md.sha1.create());for(var n="",i=Math.ceil(e/r.digestLength),s=0;s<i;++s){var o=String.fromCharCode(s>>24&255,s>>16&255,s>>8&255,s&255);r.start(),r.update(t+o),n+=r.digest().getBytes()}return n.substring(0,e)}});var o0=R((X_,Wa)=>{var gr=se();Ie();Us();Ri();(function(){if(gr.prime){Wa.exports=gr.prime;return}var t=Wa.exports=gr.prime=gr.prime||{},e=gr.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,h){return f|h};t.generateProbablePrime=function(f,h,d){typeof h=="function"&&(d=h,h={}),h=h||{};var p=h.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var m=h.prng||gr.random,y={nextBytes:function(g){for(var w=m.getBytesSync(g.length),_=0;_<g.length;++_)g[_]=w.charCodeAt(_)}};if(p.name==="PRIMEINC")return s(f,y,p.options,d);throw new Error("Invalid prime generation algorithm: "+p.name)};function s(f,h,d,p){return"workers"in d?c(f,h,d,p):o(f,h,d,p)}function o(f,h,d,p){var m=u(f,h),y=0,g=l(m.bitLength());"millerRabinTests"in d&&(g=d.millerRabinTests);var w=10;"maxBlockTime"in d&&(w=d.maxBlockTime),a(m,f,h,y,g,w,p)}function a(f,h,d,p,m,y,g){var w=+new Date;do{if(f.bitLength()>h&&(f=u(h,d)),f.isProbablePrime(m))return g(null,f);f.dAddOffset(r[p++%8],0)}while(y<0||+new Date-w<y);gr.util.setImmediate(function(){a(f,h,d,p,m,y,g)})}function c(f,h,d,p){if(typeof Worker>"u")return o(f,h,d,p);var m=u(f,h),y=d.workers,g=d.workLoad||100,w=g*30/8,_=d.workerScript||"forge/prime.worker.js";if(y===-1)return gr.util.estimateCores(function(C,T){C&&(T=2),y=T-1,N()});N();function N(){y=Math.max(1,y);for(var C=[],T=0;T<y;++T)C[T]=new Worker(_);for(var H=y,T=0;T<y;++T)C[T].addEventListener("message",De);var W=!1;function De(Et){if(!W){--H;var it=Et.data;if(it.found){for(var We=0;We<C.length;++We)C[We].terminate();return W=!0,p(null,new e(it.prime,16))}m.bitLength()>f&&(m=u(f,h));var _n=m.toString(16);Et.target.postMessage({hex:_n,workLoad:g}),m.dAddOffset(w,0)}}}}function u(f,h){var d=new e(f,h),p=f-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var qs=R((Z_,d0)=>{var M=se();Ii();Us();Is();s0();o0();Ri();Ie();typeof Q>"u"&&(Q=M.jsbn.BigInteger);var Q,Qa=M.util.isNodejs?zr():null,v=M.asn1,yt=M.util;M.pki=M.pki||{};d0.exports=M.pki.rsa=M.rsa=M.rsa||{};var K=M.pki,Ex=[6,4,2,4,2,4,6,2],bx={name:"PrivateKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},_x={name:"RSAPrivateKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Sx={name:"RSAPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Ax=M.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Ix={name:"DigestInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:v.Class.UNIVERSAL,type:v.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:v.Class.UNIVERSAL,type:v.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Rx=function(t){var e;if(t.algorithm in K.oids)e=K.oids[t.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=t.algorithm,r}var n=v.oidToDer(e).getBytes(),i=v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[]),s=v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[]);s.value.push(v.create(v.Class.UNIVERSAL,v.Type.OID,!1,n)),s.value.push(v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,""));var o=v.create(v.Class.UNIVERSAL,v.Type.OCTETSTRING,!1,t.digest().getBytes());return i.value.push(s),i.value.push(o),v.toDer(i).getBytes()},f0=function(t,e,r){if(r)return t.modPow(e.e,e.n);if(!e.p||!e.q)return t.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(Q.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(Q.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new Q(M.util.bytesToHex(M.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(Q.ONE));t=t.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=t.mod(e.p).modPow(e.dP,e.p),s=t.mod(e.q).modPow(e.dQ,e.q);i.compareTo(s)<0;)i=i.add(e.p);var o=i.subtract(s).multiply(e.qInv).mod(e.p).multiply(e.q).add(s);return o=o.multiply(n.modInverse(e.n)).mod(e.n),o};K.rsa.encrypt=function(t,e,r){var n=r,i,s=Math.ceil(e.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,i=h0(t,e,r)):(i=M.util.createBuffer(),i.putBytes(t));for(var o=new Q(i.toHex(),16),a=f0(o,e,n),c=a.toString(16),u=M.util.createBuffer(),l=s-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(M.util.hexToBytes(c)),u.getBytes()};K.rsa.decrypt=function(t,e,r,n){var i=Math.ceil(e.n.bitLength()/8);if(t.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=t.length,s.expected=i,s}var o=new Q(M.util.createBuffer(t).toHex(),16);if(o.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=f0(o,e,r),c=a.toString(16),u=M.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(M.util.hexToBytes(c)),n!==!1?Vs(u.getBytes(),e,r):u.getBytes()};K.rsa.createKeyPairGenerationState=function(t,e,r){typeof t=="string"&&(t=parseInt(t,10)),t=t||2048,r=r||{};var n=r.prng||M.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},s=r.algorithm||"PRIMEINC",o;if(s==="PRIMEINC")o={algorithm:s,state:0,bits:t,rng:i,eInt:e||65537,e:new Q(null),p:null,q:null,qBits:t>>1,pBits:t-(t>>1),pqState:0,num:null,keys:null},o.e.fromInt(o.eInt);else throw new Error("Invalid key generation algorithm: "+s);return o};K.rsa.stepKeyPairGenerationState=function(t,e){"algorithm"in t||(t.algorithm="PRIMEINC");var r=new Q(null);r.fromInt(30);for(var n=0,i=function(f,h){return f|h},s=+new Date,o,a=0;t.keys===null&&(e<=0||a<e);){if(t.state===0){var c=t.p===null?t.pBits:t.qBits,u=c-1;t.pqState===0?(t.num=new Q(c,t.rng),t.num.testBit(u)||t.num.bitwiseTo(Q.ONE.shiftLeft(u),i,t.num),t.num.dAddOffset(31-t.num.mod(r).byteValue(),0),n=0,++t.pqState):t.pqState===1?t.num.bitLength()>c?t.pqState=0:t.num.isProbablePrime(Tx(t.num.bitLength()))?++t.pqState:t.num.dAddOffset(Ex[n++%8],0):t.pqState===2?t.pqState=t.num.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)===0?3:0:t.pqState===3&&(t.pqState=0,t.p===null?t.p=t.num:t.q=t.num,t.p!==null&&t.q!==null&&++t.state,t.num=null)}else if(t.state===1)t.p.compareTo(t.q)<0&&(t.num=t.p,t.p=t.q,t.q=t.num),++t.state;else if(t.state===2)t.p1=t.p.subtract(Q.ONE),t.q1=t.q.subtract(Q.ONE),t.phi=t.p1.multiply(t.q1),++t.state;else if(t.state===3)t.phi.gcd(t.e).compareTo(Q.ONE)===0?++t.state:(t.p=null,t.q=null,t.state=0);else if(t.state===4)t.n=t.p.multiply(t.q),t.n.bitLength()===t.bits?++t.state:(t.q=null,t.state=0);else if(t.state===5){var l=t.e.modInverse(t.phi);t.keys={privateKey:K.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:K.rsa.setPublicKey(t.n,t.e)}}o=+new Date,a+=o-s,s=o}return t.keys!==null};K.rsa.generateKeyPair=function(t,e,r,n){if(arguments.length===1?typeof t=="object"?(r=t,t=void 0):typeof t=="function"&&(n=t,t=void 0):arguments.length===2?typeof t=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(r=e,e=void 0):(r=t,n=e,t=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=e,e=void 0)),r=r||{},t===void 0&&(t=r.bits||2048),e===void 0&&(e=r.e||65537),!M.options.usePureJavaScript&&!r.prng&&t>=256&&t<=16384&&(e===65537||e===3)){if(n){if(a0("generateKeyPair"))return Qa.generateKeyPair("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:K.privateKeyFromPem(u),publicKey:K.publicKeyFromPem(c)})});if(c0("generateKey")&&c0("exportKey"))return yt.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:l0(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return yt.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=K.privateKeyFromAsn1(v.fromDer(M.util.createBuffer(a)));n(null,{privateKey:c,publicKey:K.setRsaPublicKey(c.n,c.e)})}});if(u0("generateKey")&&u0("exportKey")){var i=yt.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:l0(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=yt.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,h=K.privateKeyFromAsn1(v.fromDer(M.util.createBuffer(f)));n(null,{privateKey:h,publicKey:K.setRsaPublicKey(h.n,h.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(a0("generateKeyPairSync")){var s=Qa.generateKeyPairSync("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:K.privateKeyFromPem(s.privateKey),publicKey:K.publicKeyFromPem(s.publicKey)}}}var o=K.rsa.createKeyPairGenerationState(t,e,r);if(!n)return K.rsa.stepKeyPairGenerationState(o,0),o.keys;Cx(o,r,n)};K.setRsaPublicKey=K.rsa.setPublicKey=function(t,e){var r={n:t,e};return r.encrypt=function(n,i,s){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return h0(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return M.pkcs1.encode_rsa_oaep(c,a,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var o=i.encode(n,r,!0);return K.rsa.encrypt(o,r,!0)},r.verify=function(n,i,s,o){typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSASSA-PKCS1-V1_5"),o===void 0&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),s==="RSASSA-PKCS1-V1_5"?s={verify:function(c,u){u=Vs(u,r,!0);var l=v.fromDer(u,{parseAllBytes:o._parseAllDigestBytes}),f={},h=[];if(!v.validate(l,Ix,f,h)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=h,d}var p=v.derToOid(f.algorithmIdentifier);if(!(p===M.oids.md2||p===M.oids.md5||p===M.oids.sha1||p===M.oids.sha224||p===M.oids.sha256||p===M.oids.sha384||p===M.oids.sha512||p===M.oids["sha512-224"]||p===M.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===M.oids.md2||p===M.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(s==="NONE"||s==="NULL"||s===null)&&(s={verify:function(c,u){return u=Vs(u,r,!0),c===u}});var a=K.rsa.decrypt(i,r,!0,!1);return s.verify(n,a,r.n.bitLength())},r};K.setRsaPrivateKey=K.rsa.setPrivateKey=function(t,e,r,n,i,s,o,a){var c={n:t,e,d:r,p:n,q:i,dP:s,dQ:o,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var h=K.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Vs};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return M.pkcs1.decode_rsa_oaep(p,d,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(d){return d}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(h,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:Rx},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var h=l.encode(u,c.n.bitLength());return K.rsa.encrypt(h,c,f)},c};K.wrapRsaPrivateKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,v.integerToDer(0).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.OID,!1,v.oidToDer(K.oids.rsaEncryption).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,"")]),v.create(v.Class.UNIVERSAL,v.Type.OCTETSTRING,!1,v.toDer(t).getBytes())])};K.privateKeyFromAsn1=function(t){var e={},r=[];if(v.validate(t,bx,e,r)&&(t=v.fromDer(M.util.createBuffer(e.privateKey))),e={},r=[],!v.validate(t,_x,e,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var i,s,o,a,c,u,l,f;return i=M.util.createBuffer(e.privateKeyModulus).toHex(),s=M.util.createBuffer(e.privateKeyPublicExponent).toHex(),o=M.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=M.util.createBuffer(e.privateKeyPrime1).toHex(),c=M.util.createBuffer(e.privateKeyPrime2).toHex(),u=M.util.createBuffer(e.privateKeyExponent1).toHex(),l=M.util.createBuffer(e.privateKeyExponent2).toHex(),f=M.util.createBuffer(e.privateKeyCoefficient).toHex(),K.setRsaPrivateKey(new Q(i,16),new Q(s,16),new Q(o,16),new Q(a,16),new Q(c,16),new Q(u,16),new Q(l,16),new Q(f,16))};K.privateKeyToAsn1=K.privateKeyToRSAPrivateKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,v.integerToDer(0).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.n)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.e)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.d)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.p)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.q)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.dP)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.dQ)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.qInv))])};K.publicKeyFromAsn1=function(t){var e={},r=[];if(v.validate(t,Ax,e,r)){var n=v.derToOid(e.publicKeyOid);if(n!==K.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}t=e.rsaPublicKey}if(r=[],!v.validate(t,Sx,e,r)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=r,i}var s=M.util.createBuffer(e.publicKeyModulus).toHex(),o=M.util.createBuffer(e.publicKeyExponent).toHex();return K.setRsaPublicKey(new Q(s,16),new Q(o,16))};K.publicKeyToAsn1=K.publicKeyToSubjectPublicKeyInfo=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.OID,!1,v.oidToDer(K.oids.rsaEncryption).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,"")]),v.create(v.Class.UNIVERSAL,v.Type.BITSTRING,!1,[K.publicKeyToRSAPublicKey(t)])])};K.publicKeyToRSAPublicKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.n)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.e))])};function h0(t,e,r){var n=M.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(t.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=t.length,s.max=i-11,s}n.putByte(0),n.putByte(r);var o=i-3-t.length,a;if(r===0||r===1){a=r===0?0:255;for(var c=0;c<o;++c)n.putByte(a)}else for(;o>0;){for(var u=0,l=M.random.getBytes(o),c=0;c<o;++c)a=l.charCodeAt(c),a===0?++u:n.putByte(a);o=u}return n.putByte(0),n.putBytes(t),n}function Vs(t,e,r,n){var i=Math.ceil(e.n.bitLength()/8),s=M.util.createBuffer(t),o=s.getByte(),a=s.getByte();if(o!==0||r&&a!==0&&a!==1||!r&&a!=2||r&&a===0&&typeof n>"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u<c;++u)if(s.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(a===1)for(c=0;s.length()>1;){if(s.getByte()!==255){--s.read;break}++c}else if(a===2)for(c=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++c}var l=s.getByte();if(l!==0||c!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function Cx(t,e,r){typeof e=="function"&&(r=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){s(t.pBits,function(a,c){if(a)return r(a);if(t.p=c,t.q!==null)return o(a,t.q);s(t.qBits,o)})}function s(a,c){M.prime.generateProbablePrime(a,n,c)}function o(a,c){if(a)return r(a);if(t.q=c,t.p.compareTo(t.q)<0){var u=t.p;t.p=t.q,t.q=u}if(t.p.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)!==0){t.p=null,i();return}if(t.q.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)!==0){t.q=null,s(t.qBits,o);return}if(t.p1=t.p.subtract(Q.ONE),t.q1=t.q.subtract(Q.ONE),t.phi=t.p1.multiply(t.q1),t.phi.gcd(t.e).compareTo(Q.ONE)!==0){t.p=t.q=null,i();return}if(t.n=t.p.multiply(t.q),t.n.bitLength()!==t.bits){t.q=null,s(t.qBits,o);return}var l=t.e.modInverse(t.phi);t.keys={privateKey:K.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:K.rsa.setPublicKey(t.n,t.e)},r(null,t.keys)}}function Vt(t){var e=t.toString(16);e[0]>="8"&&(e="00"+e);var r=M.util.hexToBytes(e);return r.length>1&&(r.charCodeAt(0)===0&&!(r.charCodeAt(1)&128)||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function Tx(t){return t<=100?27:t<=150?18:t<=200?15:t<=250?12:t<=300?9:t<=350?8:t<=400?7:t<=500?6:t<=600?5:t<=800?4:t<=1250?3:2}function a0(t){return M.util.isNodejs&&typeof Qa[t]=="function"}function c0(t){return typeof yt.globalScope<"u"&&typeof yt.globalScope.crypto=="object"&&typeof yt.globalScope.crypto.subtle=="object"&&typeof yt.globalScope.crypto.subtle[t]=="function"}function u0(t){return typeof yt.globalScope<"u"&&typeof yt.globalScope.msCrypto=="object"&&typeof yt.globalScope.msCrypto.subtle=="object"&&typeof yt.globalScope.msCrypto.subtle[t]=="function"}function l0(t){for(var e=M.util.hexToBytes(t.toString(16)),r=new Uint8Array(e.length),n=0;n<e.length;++n)r[n]=e.charCodeAt(n);return r}});var w0=R((j_,x0)=>{var L=se();Ls();Ii();Sf();$r();Is();Ka();Lf();Ri();$f();qs();Ie();typeof p0>"u"&&(p0=L.jsbn.BigInteger);var p0,b=L.asn1,q=L.pki=L.pki||{};x0.exports=q.pbe=L.pbe=L.pbe||{};var Yr=q.oids,Bx={name:"EncryptedPrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},Lx={name:"PBES2Algorithms",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},Px={name:"pkcs-12PbeParams",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"iterations"}]};q.encryptPrivateKeyInfo=function(t,e,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=L.random.getBytesSync(r.saltSize),i=r.count,s=b.integerToDer(i),o,a,c;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var u,l,f;switch(r.algorithm){case"aes128":o=16,u=16,l=Yr["aes128-CBC"],f=L.aes.createEncryptionCipher;break;case"aes192":o=24,u=16,l=Yr["aes192-CBC"],f=L.aes.createEncryptionCipher;break;case"aes256":o=32,u=16,l=Yr["aes256-CBC"],f=L.aes.createEncryptionCipher;break;case"des":o=8,u=8,l=Yr.desCBC,f=L.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var d="hmacWith"+r.prfAlgorithm.toUpperCase(),p=g0(d),m=L.pkcs5.pbkdf2(e,n,i,o,p),y=L.random.getBytesSync(u),g=f(m);g.start(y),g.update(b.toDer(t)),g.finish(),c=g.output.getBytes();var w=Dx(n,s,o,d);a=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr.pkcs5PBES2).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr.pkcs5PBKDF2).getBytes()),w]),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(l).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,y)])])])}else if(r.algorithm==="3des"){o=24;var _=new L.util.ByteBuffer(n),m=q.pbe.generatePkcs12Key(e,_,1,i,o),y=q.pbe.generatePkcs12Key(e,_,2,i,o),g=L.des.createEncryptionCipher(m);g.start(y),g.update(b.toDer(t)),g.finish(),c=g.output.getBytes(),a=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,n),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,s.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var N=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[a,b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,c)]);return N};q.decryptPrivateKeyInfo=function(t,e){var r=null,n={},i=[];if(!b.validate(t,Bx,n,i)){var s=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=b.derToOid(n.encryptionOid),a=q.pbe.getCipher(o,n.encryptionParams,e),c=L.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(r=b.fromDer(a.output)),r};q.encryptedPrivateKeyToPem=function(t,e){var r={type:"ENCRYPTED PRIVATE KEY",body:b.toDer(t).getBytes()};return L.pem.encode(r,{maxline:e})};q.encryptedPrivateKeyFromPem=function(t){var e=L.pem.decode(t)[0];if(e.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=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return b.fromDer(e.body)};q.encryptRsaPrivateKey=function(t,e,r){if(r=r||{},!r.legacy){var n=q.wrapRsaPrivateKey(q.privateKeyToAsn1(t));return n=q.encryptPrivateKeyInfo(n,e,r),q.encryptedPrivateKeyToPem(n)}var i,s,o,a;switch(r.algorithm){case"aes128":i="AES-128-CBC",o=16,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",o=24,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",o=32,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",o=24,s=L.random.getBytesSync(8),a=L.des.createEncryptionCipher;break;case"des":i="DES-CBC",o=8,s=L.random.getBytesSync(8),a=L.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw c.algorithm=r.algorithm,c}var u=L.pbe.opensslDeriveBytes(e,s.substr(0,8),o),l=a(u);l.start(s),l.update(b.toDer(q.privateKeyToAsn1(t))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:L.util.bytesToHex(s).toUpperCase()},body:l.output.getBytes()};return L.pem.encode(f)};q.decryptRsaPrivateKey=function(t,e){var r=null,n=L.pem.decode(t)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var s,o;switch(n.dekInfo.algorithm){case"DES-CBC":s=8,o=L.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,o=L.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,o=L.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,o=L.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,o=L.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,o=function(f){return L.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":s=8,o=function(f){return L.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":s=16,o=function(f){return L.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=L.util.hexToBytes(n.dekInfo.parameters),c=L.pbe.opensslDeriveBytes(e,a.substr(0,8),s),u=o(c);if(u.start(a),u.update(L.util.createBuffer(n.body)),u.finish())r=u.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=q.decryptPrivateKeyInfo(b.fromDer(r),e):r=b.fromDer(r),r!==null&&(r=q.privateKeyFromAsn1(r)),r};q.pbe.generatePkcs12Key=function(t,e,r,n,i,s){var o,a;if(typeof s>"u"||s===null){if(!("sha1"in L.md))throw new Error('"sha1" hash algorithm unavailable.');s=L.md.sha1.create()}var c=s.digestLength,u=s.blockLength,l=new L.util.ByteBuffer,f=new L.util.ByteBuffer;if(t!=null){for(a=0;a<t.length;a++)f.putInt16(t.charCodeAt(a));f.putInt16(0)}var h=f.length(),d=e.length(),p=new L.util.ByteBuffer;p.fillWithByte(r,u);var m=u*Math.ceil(d/u),y=new L.util.ByteBuffer;for(a=0;a<m;a++)y.putByte(e.at(a%d));var g=u*Math.ceil(h/u),w=new L.util.ByteBuffer;for(a=0;a<g;a++)w.putByte(f.at(a%h));var _=y;_.putBuffer(w);for(var N=Math.ceil(i/c),C=1;C<=N;C++){var T=new L.util.ByteBuffer;T.putBytes(p.bytes()),T.putBytes(_.bytes());for(var H=0;H<n;H++)s.start(),s.update(T.getBytes()),T=s.digest();var W=new L.util.ByteBuffer;for(a=0;a<u;a++)W.putByte(T.at(a%c));var De=Math.ceil(d/u)+Math.ceil(h/u),Et=new L.util.ByteBuffer;for(o=0;o<De;o++){var it=new L.util.ByteBuffer(_.getBytes(u)),We=511;for(a=W.length()-1;a>=0;a--)We=We>>8,We+=W.at(a)+it.at(a),it.setAt(a,We&255);Et.putBuffer(it)}_=Et,l.putBuffer(T)}return l.truncate(l.length()-i),l};q.pbe.getCipher=function(t,e,r){switch(t){case q.oids.pkcs5PBES2:return q.pbe.getCipherForPBES2(t,e,r);case q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case q.oids["pbewithSHAAnd40BitRC2-CBC"]:return q.pbe.getCipherForPKCS12PBE(t,e,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=t,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};q.pbe.getCipherForPBES2=function(t,e,r){var n={},i=[];if(!b.validate(e,Lx,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(t=b.derToOid(n.kdfOid),t!==q.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=t,s.supportedOids=["pkcs5PBKDF2"],s}if(t=b.derToOid(n.encOid),t!==q.oids["aes128-CBC"]&&t!==q.oids["aes192-CBC"]&&t!==q.oids["aes256-CBC"]&&t!==q.oids["des-EDE3-CBC"]&&t!==q.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=t,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var o=n.kdfSalt,a=L.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(q.oids[t]){case"aes128-CBC":c=16,u=L.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=L.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=L.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=L.des.createDecryptionCipher;break;case"desCBC":c=8,u=L.des.createDecryptionCipher;break}var l=y0(n.prfOid),f=L.pkcs5.pbkdf2(r,o,a,c,l),h=n.encIv,d=u(f);return d.start(h),d};q.pbe.getCipherForPKCS12PBE=function(t,e,r){var n={},i=[];if(!b.validate(e,Px,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=L.util.createBuffer(n.salt),a=L.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(t){case q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=L.des.startDecrypting;break;case q.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(m,y){var g=L.rc2.createDecryptionCipher(m,40);return g.start(y,null),g};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=t,s}var f=y0(n.prfOid),h=q.pbe.generatePkcs12Key(r,o,1,a,c,f);f.start();var d=q.pbe.generatePkcs12Key(r,o,2,a,u,f);return l(h,d)};q.pbe.opensslDeriveBytes=function(t,e,r,n){if(typeof n>"u"||n===null){if(!("md5"in L.md))throw new Error('"md5" hash algorithm unavailable.');n=L.md.md5.create()}e===null&&(e="");for(var i=[m0(n,t+e)],s=16,o=1;s<r;++o,s+=16)i.push(m0(n,i[o-1]+t+e));return i.join("").substr(0,r)};function m0(t,e){return t.start().update(e).digest().getBytes()}function y0(t){var e;if(!t)e="hmacWithSHA1";else if(e=q.oids[b.derToOid(t)],!e){var r=new Error("Unsupported PRF OID.");throw r.oid=t,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}return g0(e)}function g0(t){var e=L.md;switch(t){case"hmacWithSHA224":e=L.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":t=t.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=t,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!e||!(t in e))throw new Error("Unknown hash algorithm: "+t);return e[t].create()}function Dx(t,e,r,n){var i=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,t),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,e.getBytes())]);return n!=="hmacWithSHA1"&&i.value.push(b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,L.util.hexToBytes(r.toString(16))),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(q.oids[n]).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")])),i}});var rh=R((rA,th)=>{"use strict";th.exports=n2;function n2(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i<arguments.length;)r[n++]=arguments[i++];return new Promise(function(a,c){r[n]=function(l){if(s)if(s=!1,l)c(l);else{for(var f=new Array(arguments.length-1),h=0;h<f.length;)f[h++]=arguments[h];a.apply(null,f)}};try{t.apply(e||null,r)}catch(u){s&&(s=!1,c(u))}})}});var oh=R(sh=>{"use strict";var js=sh;js.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var kn=new Array(64),ih=new Array(123);for(At=0;At<64;)ih[kn[At]=At<26?At+65:At<52?At+71:At<62?At-4:At-59|43]=At++;var At;js.encode=function(e,r,n){for(var i=null,s=[],o=0,a=0,c;r<n;){var u=e[r++];switch(a){case 0:s[o++]=kn[u>>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=kn[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=kn[c|u>>6],s[o++]=kn[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=kn[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var nh="invalid encoding";js.decode=function(e,r,n){for(var i=n,s=0,o,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&s>1)break;if((c=ih[c])===void 0)throw Error(nh);switch(s){case 0:o=c,s=1;break;case 1:r[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:r[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:r[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(nh);return n-i};js.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var ch=R((iA,ah)=>{"use strict";ah.exports=Js;function Js(){this._listeners={}}Js.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};Js.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i<n.length;)n[i].fn===r?n.splice(i,1):++i;return this};Js.prototype.emit=function(e){var r=this._listeners[e];if(r){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<r.length;)r[i].fn.apply(r[i++].ctx,n)}return this}});var mh=R((sA,ph)=>{"use strict";ph.exports=uh(uh);function uh(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3]}function s(c,u,l){e[0]=c,u[l]=r[3],u[l+1]=r[2],u[l+2]=r[1],u[l+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],e[0]}function a(c,u){return r[3]=c[u],r[2]=c[u+1],r[1]=c[u+2],r[0]=c[u+3],e[0]}t.readFloatLE=n?o:a,t.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,o)}}t.writeFloatLE=e.bind(null,lh),t.writeFloatBE=e.bind(null,fh);function r(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}t.readFloatLE=r.bind(null,hh),t.readFloatBE=r.bind(null,dh)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3],u[l+4]=r[4],u[l+5]=r[5],u[l+6]=r[6],u[l+7]=r[7]}function s(c,u,l){e[0]=c,u[l]=r[7],u[l+1]=r[6],u[l+2]=r[5],u[l+3]=r[4],u[l+4]=r[3],u[l+5]=r[2],u[l+6]=r[1],u[l+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],r[4]=c[u+4],r[5]=c[u+5],r[6]=c[u+6],r[7]=c[u+7],e[0]}function a(c,u){return r[7]=c[u],r[6]=c[u+1],r[5]=c[u+2],r[4]=c[u+3],r[3]=c[u+4],r[2]=c[u+5],r[1]=c[u+6],r[0]=c[u+7],e[0]}t.readDoubleLE=n?o:a,t.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var f=Math.floor(Math.log(o)/Math.LN2);f===1024&&(f=1023),l=o*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}t.writeDoubleLE=e.bind(null,lh,0,4),t.writeDoubleBE=e.bind(null,fh,4,0);function r(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,f=u>>>20&2047,h=4294967296*(u&1048575)+c;return f===2047?h?NaN:l*(1/0):f===0?l*5e-324*h:l*Math.pow(2,f-1075)*(h+4503599627370496)}t.readDoubleLE=r.bind(null,hh,0,4),t.readDoubleBE=r.bind(null,dh,4,0)}(),t}function lh(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function fh(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function hh(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function dh(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var yh=R((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var xh=R(gh=>{"use strict";var Ic=gh;Ic.length=function(e){for(var r=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?r+=1:n<2048?r+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,r+=4):r+=3;return r};Ic.read=function(e,r,n){var i=n-r;if(i<1)return"";for(var s=null,o=[],a=0,c;r<n;)c=e[r++],c<128?o[a++]=c:c>191&&c<224?o[a++]=(c&31)<<6|e[r++]&63:c>239&&c<365?(c=((c&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};Ic.write=function(e,r,n){for(var i=n,s,o,a=0;a<e.length;++a)s=e.charCodeAt(a),s<128?r[n++]=s:s<2048?(r[n++]=s>>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var vh=R((aA,wh)=>{"use strict";wh.exports=i2;function i2(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return t(c);o+c>n&&(s=t(n),o=0);var u=e.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var bh=R((cA,Eh)=>{"use strict";Eh.exports=Ue;var Oi=en();function Ue(t,e){this.lo=t>>>0,this.hi=e>>>0}var Jr=Ue.zero=new Ue(0,0);Jr.toNumber=function(){return 0};Jr.zzEncode=Jr.zzDecode=function(){return this};Jr.length=function(){return 1};var s2=Ue.zeroHash="\0\0\0\0\0\0\0\0";Ue.fromNumber=function(e){if(e===0)return Jr;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Ue(n,i)};Ue.from=function(e){if(typeof e=="number")return Ue.fromNumber(e);if(Oi.isString(e))if(Oi.Long)e=Oi.Long.fromString(e);else return Ue.fromNumber(parseInt(e,10));return e.low||e.high?new Ue(e.low>>>0,e.high>>>0):Jr};Ue.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};Ue.prototype.toLong=function(e){return Oi.Long?new Oi.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Rr=String.prototype.charCodeAt;Ue.fromHash=function(e){return e===s2?Jr:new Ue((Rr.call(e,0)|Rr.call(e,1)<<8|Rr.call(e,2)<<16|Rr.call(e,3)<<24)>>>0,(Rr.call(e,4)|Rr.call(e,5)<<8|Rr.call(e,6)<<16|Rr.call(e,7)<<24)>>>0)};Ue.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)};Ue.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};Ue.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};Ue.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var en=R(Rc=>{"use strict";var O=Rc;O.asPromise=rh();O.base64=oh();O.EventEmitter=ch();O.float=mh();O.inquire=yh();O.utf8=xh();O.pool=vh();O.LongBits=bh();O.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);O.global=O.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Rc;O.emptyArray=Object.freeze?Object.freeze([]):[];O.emptyObject=Object.freeze?Object.freeze({}):{};O.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};O.isString=function(e){return typeof e=="string"||e instanceof String};O.isObject=function(e){return e&&typeof e=="object"};O.isset=O.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};O.Buffer=function(){try{var t=O.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();O._Buffer_from=null;O._Buffer_allocUnsafe=null;O.newBuffer=function(e){return typeof e=="number"?O.Buffer?O._Buffer_allocUnsafe(e):new O.Array(e):O.Buffer?O._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};O.Array=typeof Uint8Array<"u"?Uint8Array:Array;O.Long=O.global.dcodeIO&&O.global.dcodeIO.Long||O.global.Long||O.inquire("long");O.key2Re=/^true|false|0|1$/;O.key32Re=/^-?(?:0|[1-9][0-9]*)$/;O.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;O.longToHash=function(e){return e?O.LongBits.from(e).toHash():O.LongBits.zeroHash};O.longFromHash=function(e,r){var n=O.LongBits.fromHash(e);return O.Long?O.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function _h(t,e,r){for(var n=Object.keys(e),i=0;i<n.length;++i)(t[n[i]]===void 0||!r)&&(t[n[i]]=e[n[i]]);return t}O.merge=_h;O.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Sh(t){function e(r,n){if(!(this instanceof e))return new e(r,n);Object.defineProperty(this,"message",{get:function(){return r}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&_h(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}O.newError=Sh;O.ProtocolError=Sh("ProtocolError");O.oneOfGetter=function(e){for(var r={},n=0;n<e.length;++n)r[e[n]]=1;return function(){for(var i=Object.keys(this),s=i.length-1;s>-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};O.oneOfSetter=function(e){return function(r){for(var n=0;n<e.length;++n)e[n]!==r&&delete this[e[n]]}};O.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};O._configure=function(){var t=O.Buffer;if(!t){O._Buffer_from=O._Buffer_allocUnsafe=null;return}O._Buffer_from=t.from!==Uint8Array.from&&t.from||function(r,n){return new t(r,n)},O._Buffer_allocUnsafe=t.allocUnsafe||function(r){return new t(r)}}});var Bc=R((lA,Th)=>{"use strict";Th.exports=Te;var zt=en(),Tc,Rh=zt.LongBits,o2=zt.utf8;function It(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Te(t){this.buf=t,this.pos=0,this.len=t.length}var Ah=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Te(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Te(e);throw Error("illegal buffer")},Ch=function(){return zt.Buffer?function(r){return(Te.create=function(i){return zt.Buffer.isBuffer(i)?new Tc(i):Ah(i)})(r)}:Ah};Te.create=Ch();Te.prototype._slice=zt.Array.prototype.subarray||zt.Array.prototype.slice;Te.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,It(this,10);return e}}();Te.prototype.int32=function(){return this.uint32()|0};Te.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Cc(){var t=new Rh(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw It(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw It(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Te.prototype.bool=function(){return this.uint32()!==0};function eo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Te.prototype.fixed32=function(){if(this.pos+4>this.len)throw It(this,4);return eo(this.buf,this.pos+=4)};Te.prototype.sfixed32=function(){if(this.pos+4>this.len)throw It(this,4);return eo(this.buf,this.pos+=4)|0};function Ih(){if(this.pos+8>this.len)throw It(this,8);return new Rh(eo(this.buf,this.pos+=4),eo(this.buf,this.pos+=4))}Te.prototype.float=function(){if(this.pos+4>this.len)throw It(this,4);var e=zt.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Te.prototype.double=function(){if(this.pos+8>this.len)throw It(this,4);var e=zt.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Te.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw It(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};Te.prototype.string=function(){var e=this.bytes();return o2.read(e,0,e.length)};Te.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw It(this,e);this.pos+=e}else do if(this.pos>=this.len)throw It(this);while(this.buf[this.pos++]&128);return this};Te.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Te._configure=function(t){Tc=t,Te.create=Ch(),Tc._configure();var e=zt.Long?"toLong":"toNumber";zt.merge(Te.prototype,{int64:function(){return Cc.call(this)[e](!1)},uint64:function(){return Cc.call(this)[e](!0)},sint64:function(){return Cc.call(this).zzDecode()[e](!1)},fixed64:function(){return Ih.call(this)[e](!0)},sfixed64:function(){return Ih.call(this)[e](!1)}})}});var Dh=R((fA,Ph)=>{"use strict";Ph.exports=tn;var Lh=Bc();(tn.prototype=Object.create(Lh.prototype)).constructor=tn;var Bh=en();function tn(t){Lh.call(this,t)}tn._configure=function(){Bh.Buffer&&(tn.prototype._slice=Bh.Buffer.prototype.slice)};tn.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};tn._configure()});var Mc=R((hA,Mh)=>{"use strict";Mh.exports=ee;var gt=en(),Lc,to=gt.LongBits,Nh=gt.base64,kh=gt.utf8;function Mi(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function Dc(){}function a2(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function ee(){this.len=0,this.head=new Mi(Dc,0,0),this.tail=this.head,this.states=null}var Oh=function(){return gt.Buffer?function(){return(ee.create=function(){return new Lc})()}:function(){return new ee}};ee.create=Oh();ee.alloc=function(e){return new gt.Array(e)};gt.Array!==Array&&(ee.alloc=gt.pool(ee.alloc,gt.Array.prototype.subarray));ee.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Mi(e,r,n),this.len+=r,this};function Nc(t,e,r){e[r]=t&255}function c2(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function kc(t,e){this.len=t,this.next=void 0,this.val=e}kc.prototype=Object.create(Mi.prototype);kc.prototype.fn=c2;ee.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new kc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};ee.prototype.int32=function(e){return e<0?this._push(Oc,10,to.fromNumber(e)):this.uint32(e)};ee.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Oc(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}ee.prototype.uint64=function(e){var r=to.from(e);return this._push(Oc,r.length(),r)};ee.prototype.int64=ee.prototype.uint64;ee.prototype.sint64=function(e){var r=to.from(e).zzEncode();return this._push(Oc,r.length(),r)};ee.prototype.bool=function(e){return this._push(Nc,1,e?1:0)};function Pc(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}ee.prototype.fixed32=function(e){return this._push(Pc,4,e>>>0)};ee.prototype.sfixed32=ee.prototype.fixed32;ee.prototype.fixed64=function(e){var r=to.from(e);return this._push(Pc,4,r.lo)._push(Pc,4,r.hi)};ee.prototype.sfixed64=ee.prototype.fixed64;ee.prototype.float=function(e){return this._push(gt.float.writeFloatLE,4,e)};ee.prototype.double=function(e){return this._push(gt.float.writeDoubleLE,8,e)};var u2=gt.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i<e.length;++i)r[n+i]=e[i]};ee.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(Nc,1,0);if(gt.isString(e)){var n=ee.alloc(r=Nh.length(e));Nh.decode(e,n,0),e=n}return this.uint32(r)._push(u2,r,e)};ee.prototype.string=function(e){var r=kh.length(e);return r?this.uint32(r)._push(kh.write,r,e):this._push(Nc,1,0)};ee.prototype.fork=function(){return this.states=new a2(this),this.head=this.tail=new Mi(Dc,0,0),this.len=0,this};ee.prototype.reset=function(){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 Mi(Dc,0,0),this.len=0),this};ee.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};ee.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};ee._configure=function(t){Lc=t,ee.create=Oh(),Lc._configure()}});var Kh=R((dA,Uh)=>{"use strict";Uh.exports=Ht;var Fh=Mc();(Ht.prototype=Object.create(Fh.prototype)).constructor=Ht;var Cr=en();function Ht(){Fh.call(this)}Ht._configure=function(){Ht.alloc=Cr._Buffer_allocUnsafe,Ht.writeBytesBuffer=Cr.Buffer&&Cr.Buffer.prototype instanceof Uint8Array&&Cr.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i<e.length;)r[n++]=e[i++]}};Ht.prototype.bytes=function(e){Cr.isString(e)&&(e=Cr._Buffer_from(e,"base64"));var r=e.length>>>0;return this.uint32(r),r&&this._push(Ht.writeBytesBuffer,r,e),this};function l2(t,e,r){t.length<40?Cr.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ht.prototype.string=function(e){var r=Cr.Buffer.byteLength(e);return this.uint32(r),r&&this._push(l2,r,e),this};Ht._configure()});var ed=R((dI,Jh)=>{var pe=se();$r();Ie();var Ui=Jh.exports=pe.sha512=pe.sha512||{};pe.md.sha512=pe.md.algorithms.sha512=Ui;var Zh=pe.sha384=pe.sha512.sha384=pe.sha512.sha384||{};Zh.create=function(){return Ui.create("SHA-384")};pe.md.sha384=pe.md.algorithms.sha384=Zh;pe.sha512.sha256=pe.sha512.sha256||{create:function(){return Ui.create("SHA-512/256")}};pe.md["sha512/256"]=pe.md.algorithms["sha512/256"]=pe.sha512.sha256;pe.sha512.sha224=pe.sha512.sha224||{create:function(){return Ui.create("SHA-512/224")}};pe.md["sha512/224"]=pe.md.algorithms["sha512/224"]=pe.sha512.sha224;Ui.create=function(t){if(jh||w2(),typeof t>"u"&&(t="SHA-512"),!(t in nn))throw new Error("Invalid SHA-512 algorithm: "+t);for(var e=nn[t],r=null,n=pe.util.createBuffer(),i=new Array(80),s=0;s<80;++s)i[s]=new Array(2);var o=64;switch(t){case"SHA-384":o=48;break;case"SHA-512/256":o=32;break;case"SHA-512/224":o=28;break}var a={algorithm:t.replace("-","").toLowerCase(),blockLength:128,digestLength:o,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u<c;++u)a.fullMessageLength.push(0);n=pe.util.createBuffer(),r=new Array(e.length);for(var u=0;u<e.length;++u)r[u]=e[u].slice(0);return a},a.start(),a.update=function(c,u){u==="utf8"&&(c=pe.util.encodeUtf8(c));var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),Xh(r,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=pe.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(Hc.substr(0,a.blockLength-l));for(var f,h,d=a.fullMessageLength[0]*8,p=0;p<a.fullMessageLength.length-1;++p)f=a.fullMessageLength[p+1]*8,h=f/4294967296>>>0,d+=h,c.putInt32(d>>>0),d=f>>>0;c.putInt32(d);for(var m=new Array(r.length),p=0;p<r.length;++p)m[p]=r[p].slice(0);Xh(m,i,c);var y=pe.util.createBuffer(),g;t==="SHA-512"?g=m.length:t==="SHA-384"?g=m.length-2:g=m.length-4;for(var p=0;p<g;++p)y.putInt32(m[p][0]),(p!==g-1||t!=="SHA-512/224")&&y.putInt32(m[p][1]);return y},a};var Hc=null,jh=!1,Gc=null,nn=null;function w2(){Hc=String.fromCharCode(128),Hc+=pe.util.fillString(String.fromCharCode(0),128),Gc=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],nn={},nn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],nn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],nn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],nn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],jh=!0}function Xh(t,e,r){for(var n,i,s,o,a,c,u,l,f,h,d,p,m,y,g,w,_,N,C,T,H,W,De,Et,it,We,_n,bs,Le,Je,F,ba,_a,Sa,Aa,Gl=r.length();Gl>=128;){for(Le=0;Le<16;++Le)e[Le][0]=r.getInt32()>>>0,e[Le][1]=r.getInt32()>>>0;for(;Le<80;++Le)ba=e[Le-2],Je=ba[0],F=ba[1],n=((Je>>>19|F<<13)^(F>>>29|Je<<3)^Je>>>6)>>>0,i=((Je<<13|F>>>19)^(F<<3|Je>>>29)^(Je<<26|F>>>6))>>>0,Sa=e[Le-15],Je=Sa[0],F=Sa[1],s=((Je>>>1|F<<31)^(Je>>>8|F<<24)^Je>>>7)>>>0,o=((Je<<31|F>>>1)^(Je<<24|F>>>8)^(Je<<25|F>>>7))>>>0,_a=e[Le-7],Aa=e[Le-16],F=i+_a[1]+o+Aa[1],e[Le][0]=n+_a[0]+s+Aa[0]+(F/4294967296>>>0)>>>0,e[Le][1]=F>>>0;for(m=t[0][0],y=t[0][1],g=t[1][0],w=t[1][1],_=t[2][0],N=t[2][1],C=t[3][0],T=t[3][1],H=t[4][0],W=t[4][1],De=t[5][0],Et=t[5][1],it=t[6][0],We=t[6][1],_n=t[7][0],bs=t[7][1],Le=0;Le<80;++Le)u=((H>>>14|W<<18)^(H>>>18|W<<14)^(W>>>9|H<<23))>>>0,l=((H<<18|W>>>14)^(H<<14|W>>>18)^(W<<23|H>>>9))>>>0,f=(it^H&(De^it))>>>0,h=(We^W&(Et^We))>>>0,a=((m>>>28|y<<4)^(y>>>2|m<<30)^(y>>>7|m<<25))>>>0,c=((m<<4|y>>>28)^(y<<30|m>>>2)^(y<<25|m>>>7))>>>0,d=(m&g|_&(m^g))>>>0,p=(y&w|N&(y^w))>>>0,F=bs+l+h+Gc[Le][1]+e[Le][1],n=_n+u+f+Gc[Le][0]+e[Le][0]+(F/4294967296>>>0)>>>0,i=F>>>0,F=c+p,s=a+d+(F/4294967296>>>0)>>>0,o=F>>>0,_n=it,bs=We,it=De,We=Et,De=H,Et=W,F=T+i,H=C+n+(F/4294967296>>>0)>>>0,W=F>>>0,C=_,T=N,_=g,N=w,g=m,w=y,F=i+o,m=n+s+(F/4294967296>>>0)>>>0,y=F>>>0;F=t[0][1]+y,t[0][0]=t[0][0]+m+(F/4294967296>>>0)>>>0,t[0][1]=F>>>0,F=t[1][1]+w,t[1][0]=t[1][0]+g+(F/4294967296>>>0)>>>0,t[1][1]=F>>>0,F=t[2][1]+N,t[2][0]=t[2][0]+_+(F/4294967296>>>0)>>>0,t[2][1]=F>>>0,F=t[3][1]+T,t[3][0]=t[3][0]+C+(F/4294967296>>>0)>>>0,t[3][1]=F>>>0,F=t[4][1]+W,t[4][0]=t[4][0]+H+(F/4294967296>>>0)>>>0,t[4][1]=F>>>0,F=t[5][1]+Et,t[5][0]=t[5][0]+De+(F/4294967296>>>0)>>>0,t[5][1]=F>>>0,F=t[6][1]+We,t[6][0]=t[6][0]+it+(F/4294967296>>>0)>>>0,t[6][1]=F>>>0,F=t[7][1]+bs,t[7][0]=t[7][0]+_n+(F/4294967296>>>0)>>>0,t[7][1]=F>>>0,Gl-=128}}});var hu=R((iR,Pd)=>{var Gn=1e3,Yn=Gn*60,Wn=Yn*60,un=Wn*24,X2=un*7,Z2=un*365.25;Pd.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return j2(t);if(r==="number"&&isFinite(t))return e.long?ev(t):J2(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function j2(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Z2;case"weeks":case"week":case"w":return r*X2;case"days":case"day":case"d":return r*un;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Wn;case"minutes":case"minute":case"mins":case"min":case"m":return r*Yn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Gn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function J2(t){var e=Math.abs(t);return e>=un?Math.round(t/un)+"d":e>=Wn?Math.round(t/Wn)+"h":e>=Yn?Math.round(t/Yn)+"m":e>=Gn?Math.round(t/Gn)+"s":t+"ms"}function ev(t){var e=Math.abs(t);return e>=un?po(t,e,un,"day"):e>=Wn?po(t,e,Wn,"hour"):e>=Yn?po(t,e,Yn,"minute"):e>=Gn?po(t,e,Gn,"second"):t+" ms"}function po(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var Nd=R((sR,Dd)=>{function tv(t){r.debug=r,r.default=r,r.coerce=c,r.disable=s,r.enable=i,r.enabled=o,r.humanize=hu(),r.destroy=u,Object.keys(t).forEach(l=>{r[l]=t[l]}),r.names=[],r.skips=[],r.formatters={};function e(l){let f=0;for(let h=0;h<l.length;h++)f=(f<<5)-f+l.charCodeAt(h),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(l){let f,h=null,d,p;function m(...y){if(!m.enabled)return;let g=m,w=Number(new Date),_=w-(f||w);g.diff=_,g.prev=f,g.curr=w,f=w,y[0]=r.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let N=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,H)=>{if(T==="%%")return"%";N++;let W=r.formatters[H];if(typeof W=="function"){let De=y[N];T=W.call(g,De),y.splice(N,1),N--}return T}),r.formatArgs.call(g,y),(g.log||r.log).apply(g,y)}return m.namespace=l,m.useColors=r.useColors(),m.color=r.selectColor(l),m.extend=n,m.destroy=r.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==r.namespaces&&(d=r.namespaces,p=r.enabled(l)),p),set:y=>{h=y}}),typeof r.init=="function"&&r.init(m),m}function n(l,f){let h=r(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f<d;f++)h[f]&&(l=h[f].replace(/\*/g,".*?"),l[0]==="-"?r.skips.push(new RegExp("^"+l.slice(1)+"$")):r.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=r.skips.length;f<h;f++)if(r.skips[f].test(l))return!1;for(f=0,h=r.names.length;f<h;f++)if(r.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Dd.exports=tv});var du=R((ct,mo)=>{ct.formatArgs=nv;ct.save=iv;ct.load=sv;ct.useColors=rv;ct.storage=ov();ct.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ct.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 rv(){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 nv(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+mo.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}ct.log=console.debug||console.log||(()=>{});function iv(t){try{t?ct.storage.setItem("debug",t):ct.storage.removeItem("debug")}catch{}}function sv(){let t;try{t=ct.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function ov(){try{return localStorage}catch{}}mo.exports=Nd()(ct);var{formatters:av}=mo.exports;av.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Od=R((lR,kd)=>{"use strict";function uv(t){return t>=55296&&t<=56319}function lv(t){return t>=56320&&t<=57343}kd.exports=function(e,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var i=r.length,s=0,o,a,c=0;c<i;c+=1){if(o=r.charCodeAt(c),a=r[c],uv(o)&&lv(r.charCodeAt(c+1))&&(c+=1,a+=r[c]),s+=e(a),s===n)return r.slice(0,c+1);if(s>n)return r.slice(0,c-a.length+1)}return r}});var Fd=R((fR,Md)=>{"use strict";function fv(t){return t>=55296&&t<=56319}function hv(t){return t>=56320&&t<=57343}Md.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var r=e.length,n=0,i=null,s=null,o=0;o<r;o++)i=e.charCodeAt(o),hv(i)?s!=null&&fv(s)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var Kd=R((hR,Ud)=>{"use strict";var dv=Od(),pv=Fd();Ud.exports=dv.bind(null,pv)});var $d=R((dR,qd)=>{"use strict";var mv=Kd(),yv=/[\/\?<>\\:\*\|"]/g,gv=/[\x00-\x1f\x80-\x9f]/g,xv=/^\.+$/,wv=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,vv=/[\. ]+$/;function Vd(t,e){if(typeof t!="string")throw new Error("Input must be string");var r=t.replace(yv,e).replace(gv,e).replace(xv,e).replace(wv,e).replace(vv,e);return mv(r,255)}qd.exports=function(t,e){var r=e&&e.replacement||"",n=Vd(t,r);return r===""?n:Vd(n,"")}});var Hd=R((pR,zd)=>{"use strict";zd.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Zd=R((Qd,Xd)=>{"use strict";var yo=Hd(),{hasOwnProperty:Yd}=Object.prototype,{propertyIsEnumerable:Ev}=Object,Qn=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),bv=Qd,Gd={concatArrays:!1,ignoreUndefined:!1},go=t=>{let e=[];for(let r in t)Yd.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)Ev.call(t,n)&&e.push(n)}return e};function Xn(t){return Array.isArray(t)?_v(t):yo(t)?Sv(t):t}function _v(t){let e=t.slice(0,0);return go(t).forEach(r=>{Qn(e,r,Xn(t[r]))}),e}function Sv(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return go(t).forEach(r=>{Qn(e,r,Xn(t[r]))}),e}var Wd=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?Qn(t,i,pu(t[i],e[i],n)):Qn(t,i,Xn(e[i])))}),t),Av=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)Yd.call(s,a)&&(o.push(String(a)),s===t?Qn(n,i++,s[a]):Qn(n,i++,Xn(s[a])));n=Wd(n,s,go(s).filter(a=>!o.includes(a)),r)}),n};function pu(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?Av(t,e,r):!yo(e)||!yo(t)?Xn(e):Wd(t,e,go(e),r)}Xd.exports=function(...t){let e=pu(Xn(Gd),this!==bv&&this||{},Gd),r={_:{}};for(let n of t)if(n!==void 0){if(!yo(n))throw new TypeError("`"+n+"` is not an Option Object");r=pu(r,{_:n},e)}return r._}});var yp=R((Y4,mp)=>{mp.exports=vu;var pp=128,Gv=127,Yv=~Gv,Wv=Math.pow(2,31);function vu(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw vu.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=Wv;)e[r++]=t&255|pp,t/=128;for(;t&Yv;)e[r++]=t&255|pp,t>>>=7;return e[r]=t|0,vu.bytes=r-n+1,e}});var wp=R((W4,xp)=>{xp.exports=Eu;var Qv=128,gp=127;function Eu(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a||i>49)throw Eu.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&gp)<<i:(o&gp)*Math.pow(2,i),i+=7}while(o>=Qv);return Eu.bytes=s-n,r}});var Ep=R((Q4,vp)=>{var Xv=Math.pow(2,7),Zv=Math.pow(2,14),jv=Math.pow(2,21),Jv=Math.pow(2,28),eE=Math.pow(2,35),tE=Math.pow(2,42),rE=Math.pow(2,49),nE=Math.pow(2,56),iE=Math.pow(2,63);vp.exports=function(t){return t<Xv?1:t<Zv?2:t<jv?3:t<Jv?4:t<eE?5:t<tE?6:t<rE?7:t<nE?8:t<iE?9:10}});var So=R((X4,bp)=>{bp.exports={encode:yp(),decode:wp(),encodingLength:Ep()}});var zp=R((ST,ku)=>{"use strict";var BE=Object.prototype.hasOwnProperty,je="~";function ts(){}Object.create&&(ts.prototype=Object.create(null),new ts().__proto__||(je=!1));function LE(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function $p(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new LE(r,n||t,i),o=je?je+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function Bo(t,e){--t._eventsCount===0?t._events=new ts:delete t._events[e]}function Ge(){this._events=new ts,this._eventsCount=0}Ge.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)BE.call(r,n)&&e.push(je?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Ge.prototype.listeners=function(e){var r=je?je+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Ge.prototype.listenerCount=function(e){var r=je?je+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Ge.prototype.emit=function(e,r,n,i,s,o){var a=je?je+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var h=c.length,d;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,r);break;case 3:c[f].fn.call(c[f].context,r,n);break;case 4:c[f].fn.call(c[f].context,r,n,i);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[f].fn.apply(c[f].context,l)}}return!0};Ge.prototype.on=function(e,r,n){return $p(this,e,r,n,!1)};Ge.prototype.once=function(e,r,n){return $p(this,e,r,n,!0)};Ge.prototype.removeListener=function(e,r,n,i){var s=je?je+e:e;if(!this._events[s])return this;if(!r)return Bo(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&Bo(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:Bo(this,s)}return this};Ge.prototype.removeAllListeners=function(e){var r;return e?(r=je?je+e:e,this._events[r]&&Bo(this,r)):(this._events=new ts,this._eventsCount=0),this};Ge.prototype.off=Ge.prototype.removeListener;Ge.prototype.addListener=Ge.prototype.on;Ge.prefixed=je;Ge.EventEmitter=Ge;typeof ku<"u"&&(ku.exports=Ge)});var il=R((U8,lm)=>{"use strict";function um(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function GE(t,e,r){if(!t||typeof t=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof e=="object"&&(r=e,e=""),e&&(r.code=e);try{return um(t,r)}catch{r.message=t.message,r.stack=t.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(t)),um(new i,r)}}lm.exports=GE});var ym=R(us=>{(function(){var t,e,r,n,i,s,o,a;a=function(c){var u,l,f,h;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,h=c&255,[u,l,f,h].join(".")},o=function(c){var u,l,f,h,d,p;for(u=[],f=h=0;h<=3&&c.length!==0;f=++h){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],l=p[1],c=c.substring(l),u.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},r=function(c){return c.charCodeAt(0)},n=r("0"),s=r("a"),i=r("A"),e=function(c){var u,l,f,h,d;for(h=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),d=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)h=h*u+(r(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")h=h*u+(10+r(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")h=h*u+(10+r(c[f])-i)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[h,f]},t=function(){function c(u,l){var f,h,d,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(m){throw f=m,new Error("Invalid mask: "+l)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,h;for(h=o(this.first),f=o(this.last),l=0;h<=f;)u(a(h),h,l),l++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),us.ip2long=o,us.long2ip=a,us.Netmask=t}).call(us)});var vm=R((wm,Xo)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let m=0,y=-1,g=(d.match(a.zoneIndex)||[])[0],w,_;for(g&&(g=g.substring(1),d=d.replace(/%.+$/,""));(y=d.indexOf(":",y+1))>=0;)m++;if(d.substr(0,2)==="::"&&m--,d.substr(-2,2)==="::"&&m--,m>p)return null;for(_=p-m,w=":";_--;)w+="0:";return d=d.replace("::",w),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let N=d.split(":"),C=[];for(let T=0;T<N.length;T++)C.push(parseInt(N[T],16));return C}(),{parts:p,zoneId:g}}function u(d,p,m,y){if(d.length!==p.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let g=0,w;for(;y>0;){if(w=m-y,w<0&&(w=0),d[g]>>w!==p[g]>>w)return!1;y-=m,g+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length<p;)d=`0${d}`;return d}let h={};h.IPv4=function(){function d(p){if(p.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let m,y;for(m=0;m<p.length;m++)if(y=p[m],!(0<=y&&y<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=p}return d.prototype.SpecialRanges={unspecified:[[new d([0,0,0,0]),8]],broadcast:[[new d([255,255,255,255]),32]],multicast:[[new d([224,0,0,0]),4]],linkLocal:[[new d([169,254,0,0]),16]],loopback:[[new d([127,0,0,0]),8]],carrierGradeNat:[[new d([100,64,0,0]),10]],private:[[new d([10,0,0,0]),8],[new d([172,16,0,0]),12],[new d([192,168,0,0]),16]],reserved:[[new d([192,0,0,0]),24],[new d([192,0,2,0]),24],[new d([192,88,99,0]),24],[new d([198,51,100,0]),24],[new d([203,0,113,0]),24],[new d([240,0,0,0]),4]]},d.prototype.kind=function(){return"ipv4"},d.prototype.match=function(p,m){let y;if(m===void 0&&(y=p,p=y[0],m=y[1]),p.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,p.octets,8,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,y={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},g,w,_;for(g=3;g>=0;g-=1)if(w=this.octets[g],w in y){if(_=y[w],m&&_!==0)return null;_!==8&&(m=!0),p+=_}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),y=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],w=0;for(;w<4;)g.push(parseInt(m[w],10)|parseInt(y[w],10)^255),w++;return new this(g)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,m,y,g,w;try{for(p=this.parseCIDR(d),y=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],m=0;m<4;)g.push(parseInt(y[m],10)&parseInt(w[m],10)),m++;return new this(g)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let m=parseInt(p[2]);if(m>=0&&m<=32){let y=[this.parse(p[1]),m];return Object.defineProperty(y,"toString",{value:function(){return this.join("/")}}),y}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,m,y;if(p=d.match(r.fourOctet))return function(){let g=p.slice(1,6),w=[];for(let _=0;_<g.length;_++)m=g[_],w.push(l(m));return w}();if(p=d.match(r.longValue)){if(y=l(p[1]),y>4294967295||y<0)throw new Error("ipaddr: address outside defined range");return function(){let g=[],w;for(w=0;w<=24;w+=8)g.push(y>>w&255);return g}().reverse()}else return(p=d.match(r.twoOctet))?function(){let g=p.slice(1,4),w=[];if(y=l(g[1]),y>16777215||y<0)throw new Error("ipaddr: address outside defined range");return w.push(l(g[0])),w.push(y>>16&255),w.push(y>>8&255),w.push(y&255),w}():(p=d.match(r.threeOctet))?function(){let g=p.slice(1,5),w=[];if(y=l(g[2]),y>65535||y<0)throw new Error("ipaddr: address outside defined range");return w.push(l(g[0])),w.push(l(g[1])),w.push(y>>8&255),w.push(y&255),w}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],m=0,y=Math.floor(d/8);for(;m<y;)p[m]=255,m++;return y<4&&(p[y]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},h.IPv6=function(){function d(p,m){let y,g;if(p.length===16)for(this.parts=[],y=0;y<=14;y+=2)this.parts.push(p[y]<<8|p[y+1]);else if(p.length===8)this.parts=p;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(y=0;y<this.parts.length;y++)if(g=this.parts[y],!(0<=g&&g<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");m&&(this.zoneId=m)}return d.prototype.SpecialRanges={unspecified:[new d([0,0,0,0,0,0,0,0]),128],linkLocal:[new d([65152,0,0,0,0,0,0,0]),10],multicast:[new d([65280,0,0,0,0,0,0,0]),8],loopback:[new d([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new d([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new d([0,0,0,0,0,65535,0,0]),96],rfc6145:[new d([0,0,0,0,65535,0,0,0]),96],rfc6052:[new d([100,65435,0,0,0,0,0,0]),96],"6to4":[new d([8194,0,0,0,0,0,0,0]),16],teredo:[new d([8193,0,0,0,0,0,0,0]),32],reserved:[[new d([8193,3512,0,0,0,0,0,0]),32]]},d.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},d.prototype.kind=function(){return"ipv6"},d.prototype.match=function(p,m){let y;if(m===void 0&&(y=p,p=y[0],m=y[1]),p.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,p.parts,16,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,y={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},g,w;for(let _=7;_>=0;_-=1)if(g=this.parts[_],g in y){if(w=y[g],m&&w!==0)return null;w!==16&&(m=!0),p+=w}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,m=[],y=this.parts;for(let g=0;g<y.length;g++)p=y[g],m.push(p>>8),m.push(p&255);return m},d.prototype.toFixedLengthString=function(){let p=function(){let y=[];for(let g=0;g<this.parts.length;g++)y.push(f(this.parts[g].toString(16),4));return y}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let p=this.parts.slice(-2),m=p[0],y=p[1];return new h.IPv4([m>>8,m&255,y>>8,y&255])},d.prototype.toNormalizedString=function(){let p=function(){let y=[];for(let g=0;g<this.parts.length;g++)y.push(this.parts[g].toString(16));return y}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toRFC5952String=function(){let p=/((^|:)(0(:|$)){2,})/g,m=this.toNormalizedString(),y=0,g=-1,w;for(;w=p.exec(m);)w[0].length>g&&(y=w.index,g=w[0].length);return g<0?m:`${m.substring(0,y)}::${m.substring(y+g)}`},d.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),y=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],w=0;for(;w<16;)g.push(parseInt(m[w],10)|parseInt(y[w],10)^255),w++;return new this(g)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,m,y,g,w;try{for(p=this.parseCIDR(d),y=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],m=0;m<16;)g.push(parseInt(y[m],10)&parseInt(w[m],10)),m++;return new this(g)}catch(_){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${_})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,m,y;if((m=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(m[2]),p>=0&&p<=128))return y=[this.parse(m[1]),p],Object.defineProperty(y,"toString",{value:function(){return this.join("/")}}),y;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,m,y,g,w,_;if(y=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${y[1]}`);if(a.native.test(d))return c(d,8);if((y=d.match(a.transitional))&&(_=y[6]||"",p=c(y[1].slice(0,-1)+_,6),p.parts)){for(w=[parseInt(y[2]),parseInt(y[3]),parseInt(y[4]),parseInt(y[5])],m=0;m<w.length;m++)if(g=w[m],!(0<=g&&g<=255))return null;return p.parts.push(w[0]<<8|w[1]),p.parts.push(w[2]<<8|w[3]),{parts:p.parts,zoneId:p.zoneId}}return null},h.IPv6.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=0,y=Math.floor(d/8);for(;m<y;)p[m]=255,m++;return y<16&&(p[y]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},h.fromByteArray=function(d){let p=d.length;if(p===4)return new h.IPv4(d);if(p===16)return new h.IPv6(d);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},h.isValid=function(d){return h.IPv6.isValid(d)||h.IPv4.isValid(d)},h.parse=function(d){if(h.IPv6.isValid(d))return h.IPv6.parse(d);if(h.IPv4.isValid(d))return h.IPv4.parse(d);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},h.parseCIDR=function(d){try{return h.IPv6.parseCIDR(d)}catch{try{return h.IPv4.parseCIDR(d)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},h.process=function(d){let p=this.parse(d);return p.kind()==="ipv6"&&p.isIPv4MappedAddress()?p.toIPv4Address():p},h.subnetMatch=function(d,p,m){let y,g,w,_;m==null&&(m="unicast");for(g in p)if(Object.prototype.hasOwnProperty.call(p,g)){for(w=p[g],w[0]&&!(w[0]instanceof Array)&&(w=[w]),y=0;y<w.length;y++)if(_=w[y],d.kind()===_[0].kind()&&d.match.apply(d,_))return g}return m},typeof Xo<"u"&&Xo.exports?Xo.exports=h:t.ipaddr=h})(wm)});var Cm=R((p3,Rm)=>{"use strict";Rm.exports=Im;var ob=hu(),Kr=Im.prototype,ab=new Date%1e9;function cb(){return(Math.random()*1e9>>>0)+ab++}function Im(t){t=t||{},this.id=t.id||cb(),this.max=t.max||1/0,this.items=t.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(t.lastModified||new Date);for(var e,r,n=this.items.length;n--;)e=this.items[n],r=new Date(e.expires)-new Date,this._lookup[e.key]=e,r>0?this.expire(e.key,r):r<=0&&this.delete(e.key)}Kr.has=function(t){return t in this._lookup};Kr.get=function(t){if(!this.has(t))return null;var e=this._lookup[t];return e.refresh&&this.expire(t,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};Kr.meta=function(t){if(!this.has(t))return null;var e=this._lookup[t];return"meta"in e?e.meta:null};Kr.set=function(t,e,r){var n=this._lookup[t],i=this._lookup[t]={key:t,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),r&&("ttl"in r&&this.expire(t,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};Kr.delete=function(t){var e=this._lookup[t];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[t],this.size--,this):!1};Kr.expire=function(t,e){var r=e||0,n=this._lookup[t];if(!n)return this;if(typeof r=="string"&&(r=ob(e)),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};Kr.clear=function(){for(var t=this.items.length;t--;)this.delete(this.items[t].key);return this};Kr.toJSON=function(){for(var t=new Array(this.items.length),e,r=t.length;r--;)e=this.items[r],t[r]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:t}}});var ls=R((k3,Om)=>{Om.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.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'!")}}});var Fm=R((M3,Mm)=>{Mm.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(r=>{this._keys[r]<=e&&delete this._keys[r]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,r){this.addMs(e,r*1e3)}addMs(e,r){this._keys[e]=Date.now()+r,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let r=this._keys[e];if(r&&r>=Date.now()){this.collectExpired();let n=Date.now();return r>=n?r-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(r=>{delete this._keys[r]})}}});var Km=R((F3,Um)=>{var hb=Fm();Um.exports=hb});var dt=R((K3,Vm)=>{Vm.exports=class{constructor(e,r,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_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()}}});var fi=R((q3,$m)=>{var dl=ls(),db=Km(),qm=dt();$m.exports=class extends dl{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new db}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,r,n,i,s,o={}){let a=this._getRateLimiterRes(n,i,s);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?r(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{r(a)}).catch(u=>{r(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,r,n,i,s,o=!1,a={}){this.insuranceLimiter instanceof dl?this.insuranceLimiter[r](s,o,a).then(c=>{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):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(e){if(this._inMemoryBlockDuration=e?parseInt(e):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(e){if(typeof e<"u"&&!(e instanceof dl))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,r,n={}){let i=r*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,r,n,i={}){let s=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),r,s,i)}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return s(new qm(0,a));this._upsert(o,r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,s,o,r,c)}).catch(c=>{this._handleError(c,"consume",i,s,e,r,n)})})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,r,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,r,a))}).catch(a=>{this._handleError(a,"penalty",s,o,e,r,n)})})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,-r,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,-r,a))}).catch(a=>{this._handleError(a,"reward",s,o,e,r,n)})})}get(e,r={}){let n=this.getKey(e);return new Promise((i,s)=>{this._get(n,r).then(o=>{i(o===null||typeof o>"u"?null:this._getRateLimiterRes(n,0,o))}).catch(o=>{this._handleError(o,"get",i,s,e,r)})})}delete(e,r={}){let n=this.getKey(e);return new Promise((i,s)=>{this._delete(n,r).then(o=>{this._inMemoryBlockedKeys.delete(n),i(o)}).catch(o=>{this._handleError(o,"delete",i,s,e,r)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,r,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,r,n,i={}){return new Promise((s,o)=>{this._upsert(e,r,n,!0,i).then(()=>{s(new qm(0,n>0?n:-1,r))}).catch(a=>{this._handleError(a,"block",s,o,this.parseKey(e),n/1e3,i)})})}_get(e,r={}){throw new Error("You have to implement the method '_get'!")}_delete(e,r={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,r,n,i=!1,s={}){throw new Error("You have to implement the method '_upsert'!")}}});var Gm=R(($3,Hm)=>{var pb=fi(),mb=dt(),zm="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} ",pl=class extends pb{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:zm})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,r,n){let[i,s]=n;Array.isArray(i)&&([,i]=i,[,s]=s);let o=new mb;return o.consumedPoints=parseInt(i),o.isFirstInDuration=o.consumedPoints===r,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=s,o}_upsert(e,r,n,i=!1){return new Promise((s,o)=>{if(!this._isRedisReady())return o(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,r,"EX",a):c.set(e,r),c.pttl(e).exec((u,l)=>u?o(u):s(l));else if(a>0){let u=function(l,f){return l?o(l):s(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,r,a,u):this.client.eval(zm,1,e,r,a,u)}else c.incrby(e,r).pttl(e).exec((u,l)=>u?o(u):s(l))})}_get(e){return new Promise((r,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,s)=>{if(i)n(i);else{let[o]=s;if(o===null)return r(null);r(s)}})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,s)=>{i?n(i):r(s>0)})})}};Hm.exports=pl});var Qm=R((z3,Wm)=>{var yb=fi(),gb=dt();function Ym(t){try{let e=t.client?t.client:t,{version:r}=e.topology.s.options.metadata.driver,n=r.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var fs=class extends yb{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(r=>{this.client=r,this._initCollection(),this._driverVersion=Ym(this.client)}):(this._initCollection(),this._driverVersion=Ym(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?fs.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let 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(e,r,n){let i=new gb,s;return typeof n.value>"u"?s=n:s=n.value,i.isFirstInDuration=s.points===r,i.consumedPoints=s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire!==null?Math.max(new Date(s.expire).getTime()-Date.now(),0):-1,i}_upsert(e,r,n,i=!1,s={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=s.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:r,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:r}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),p={$set:Object.assign({key:e,points:r,expire:n>0?new Date(Date.now()+n):null},o)};this._collection.findOneAndUpdate(d,p,u).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,r,n,i).then(y=>l(y)).catch(y=>f(y)):f(m)})}else f(h)})})}_get(e,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=r.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=r.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(s=>s.deletedCount>0)}};Wm.exports=fs});var Zm=R((H3,Xm)=>{var xb=fi(),wb=dt(),ml=class extends xb{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.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(e){return new Promise(r=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{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((e,r)=>{this.client.getConnection((n,i)=>{if(n)return r(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,r)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),r(i);n.query(this._getCreateTableStmt(),s=>{if(s)return this._releaseConnection(n),r(s);this._releaseConnection(n),e()})})}).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(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,r,n){let i=new wb,[s]=n;return i.isFirstInDuration=r===s.points,i.consumedPoints=i.isFirstInDuration?r:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_upsertTransaction(e,r,n,i,s){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;s?(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
15
+ `+a+e.substr(o+1),s=i-o-1,o=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(o=i);return e}function Tg(t){return t.replace(/^\s+/,"")}});var Mf=R(($_,Of)=>{var Mt=se();$r();Ie();var Df=Of.exports=Mt.sha256=Mt.sha256||{};Mt.md.sha256=Mt.md.algorithms.sha256=Df;Df.create=function(){Nf||Bg();var t=null,e=Mt.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 i=n.messageLengthSize/4,s=0;s<i;++s)n.fullMessageLength.push(0);return e=Mt.util.createBuffer(),t={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=Mt.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),Pf(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Mt.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Va.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4,h5:t.h5,h6:t.h6,h7:t.h7};Pf(f,r,i);var h=Mt.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var Va=null,Nf=!1,kf=null;function Bg(){Va=String.fromCharCode(128),Va+=Mt.util.fillString(String.fromCharCode(0),64),kf=[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],Nf=!0}function Pf(t,e,r){for(var n,i,s,o,a,c,u,l,f,h,d,p,m,y,g,w=r.length();w>=64;){for(u=0;u<16;++u)e[u]=r.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=t.h0,f=t.h1,h=t.h2,d=t.h3,p=t.h4,m=t.h5,y=t.h6,g=t.h7,u=0;u<64;++u)o=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=y^p&(m^y),s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|h&(l^f),n=g+o+a+kf[u]+e[u],i=s+c,g=y,y=m,m=p,p=d+n>>>0,d=h,h=f,f=l,l=n+i>>>0;t.h0=t.h0+l|0,t.h1=t.h1+f|0,t.h2=t.h2+h|0,t.h3=t.h3+d|0,t.h4=t.h4+p|0,t.h5=t.h5+m|0,t.h6=t.h6+y|0,t.h7=t.h7+g|0,w-=64}}});var Uf=R((z_,Ff)=>{var Ft=se();Ie();var Os=null;Ft.util.isNodejs&&!Ft.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Os=zr());var Lg=Ff.exports=Ft.prng=Ft.prng||{};Lg.create=function(t){for(var e={plugin:t,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=t.md,n=new Array(32),i=0;i<32;++i)n[i]=r.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,h=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,m=Ft.util.createBuffer();e.key=null,y();function y(g){if(g)return l(g);if(m.length()>=u)return l(null,m.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return Ft.util.nextTick(function(){s(y)});var w=f(e.key,e.seed);e.generated+=w.length,m.putBytes(w),e.key=d(f(e.key,h(e.seed))),e.seed=p(f(e.key,e.seed)),Ft.util.setImmediate(y)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,h=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=Ft.util.createBuffer();p.length()<u;){e.generated>1048575&&(e.key=null),e.key===null&&o();var m=l(e.key,e.seed);e.generated+=m.length,p.putBytes(m),e.key=h(l(e.key,f(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function s(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,h){if(f)return u(f);e.collect(h),a(),u()})}function o(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l===0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var h=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(h),e.generated=0}function c(u){var l=null,f=Ft.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(l=function(C){return h.getRandomValues(C)});var d=Ft.util.createBuffer();if(l)for(;d.length()<u;){var p=Math.max(1,Math.min(u-d.length(),65536)/4),m=new Uint32Array(Math.floor(p));try{l(m);for(var y=0;y<m.length;++y)d.putInt32(m[y])}catch(C){if(!(typeof QuotaExceededError<"u"&&C instanceof QuotaExceededError))throw C}}if(d.length()<u)for(var g,w,_,N=Math.floor(Math.random()*65536);d.length()<u;){w=16807*(N&65535),g=16807*(N>>16),w+=(g&32767)<<16,w+=g>>15,w=(w&2147483647)+(w>>31),N=w&4294967295;for(var y=0;y<3;++y)_=N>>>(y<<3),_^=Math.floor(Math.random()*256),d.putByte(_&255)}return d.getBytes(u)}return Os?(e.seedFile=function(u,l){Os.randomBytes(u,function(f,h){if(f)return l(f);l(null,h.toString())})},e.seedFileSync=function(u){return Os.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f<l;++f)e.pools[e.pool].update(u.substr(f,1)),e.pool=e.pool===31?0:e.pool+1},e.collectInt=function(u,l){for(var f="",h=0;h<l;h+=8)f+=String.fromCharCode(u>>h&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,h){function d(p){var m=p.data;m.forge&&m.forge.prng&&(self.removeEventListener("message",d),h(m.forge.prng.err,m.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var h=f.data;h.forge&&h.forge.prng&&e.seedFile(h.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var Ri=R((H_,qa)=>{var Me=se();Ls();Mf();Uf();Ie();(function(){if(Me.random&&Me.random.getBytes){qa.exports=Me.random;return}(function(t){var e={},r=new Array(4),n=Me.util.createBuffer();e.formatKey=function(f){var h=Me.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),Me.aes._expandKey(f,!1)},e.formatSeed=function(f){var h=Me.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},e.cipher=function(f,h){return Me.aes._updateBlock(f,h,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=Me.md.sha256;function i(){var f=Me.prng.create(e);return f.getBytes=function(h,d){return f.generate(h,d)},f.getBytesSync=function(h){return f.generate(h)},f}var s=i(),o=null,a=Me.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(o=function(f){return c.getRandomValues(f)}),Me.options.usePureJavaScript||!Me.util.isNodejs&&!o){if(typeof window>"u"||window.document,s.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}s.collect(u),u=null}t&&(t().mousemove(function(f){s.collectInt(f.clientX,16),s.collectInt(f.clientY,16)}),t().keypress(function(f){s.collectInt(f.charCode,8)}))}if(!Me.random)Me.random=s;else for(var l in s)Me.random[l]=s[l];Me.random.createInstance=i,qa.exports=Me.random})(typeof jQuery<"u"?jQuery:null)})()});var $f=R((G_,qf)=>{var et=se();Ie();var $a=[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],Kf=[1,2,3,5],Pg=function(t,e){return t<<e&65535|(t&65535)>>16-e},Dg=function(t,e){return(t&65535)>>e|t<<16-e&65535};qf.exports=et.rc2=et.rc2||{};et.rc2.expandKey=function(t,e){typeof t=="string"&&(t=et.util.createBuffer(t)),e=e||128;var r=t,n=t.length(),i=e,s=Math.ceil(i/8),o=255>>(i&7),a;for(a=n;a<128;a++)r.putByte($a[r.at(a-1)+r.at(a-n)&255]);for(r.setAt(128-s,$a[r.at(128-s)&o]),a=127-s;a>=0;a--)r.setAt(a,$a[r.at(a+1)^r.at(a+s)]);return r};var Vf=function(t,e,r){var n=!1,i=null,s=null,o=null,a,c,u,l,f=[];for(t=et.rc2.expandKey(t,e),u=0;u<64;u++)f.push(t.getInt16Le());r?(a=function(p){for(u=0;u<4;u++)p[u]+=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=Pg(p[u],Kf[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=f[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=Dg(p[u],Kf[u]),p[u]-=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),l--},c=function(p){for(u=3;u>=0;u--)p[u]-=f[p[(u+3)%4]&63]});var h=function(p){var m=[];for(u=0;u<4;u++){var y=i.getInt16Le();o!==null&&(r?y^=o.getInt16Le():o.putInt16Le(y)),m.push(y&65535)}l=r?0:63;for(var g=0;g<p.length;g++)for(var w=0;w<p[g][0];w++)p[g][1](m);for(u=0;u<4;u++)o!==null&&(r?o.putInt16Le(m[u]):m[u]^=o.getInt16Le()),s.putInt16Le(m[u])},d=null;return d={start:function(p,m){p&&typeof p=="string"&&(p=et.util.createBuffer(p)),n=!1,i=et.util.createBuffer(),s=m||new et.util.createBuffer,o=p,d.output=s},update:function(p){for(n||i.putBuffer(p);i.length()>=8;)h([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var m=!0;if(r)if(p)m=p(8,i,!r);else{var y=i.length()===8?8:8-i.length();i.fillWithByte(y,y)}if(m&&(n=!0,d.update()),!r&&(m=i.length()===0,m))if(p)m=p(8,s,!r);else{var g=s.length(),w=s.at(g-1);w>g?m=!1:s.truncate(w)}return m}},d};et.rc2.startEncrypting=function(t,e,r){var n=et.rc2.createEncryptionCipher(t,128);return n.start(e,r),n};et.rc2.createEncryptionCipher=function(t,e){return Vf(t,e,!0)};et.rc2.startDecrypting=function(t,e,r){var n=et.rc2.createDecryptionCipher(t,128);return n.start(e,r),n};et.rc2.createDecryptionCipher=function(t,e){return Vf(t,e,!1)}});var Us=R((Y_,Zf)=>{var za=se();Zf.exports=za.jsbn=za.jsbn||{};var tr,Ng=0xdeadbeefcafe,zf=(Ng&16777215)==15715070;function S(t,e,r){this.data=[],t!=null&&(typeof t=="number"?this.fromNumber(t,e,r):e==null&&typeof t!="string"?this.fromString(t,256):this.fromString(t,e))}za.jsbn.BigInteger=S;function J(){return new S(null)}function kg(t,e,r,n,i,s){for(;--s>=0;){var o=e*this.data[t++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=o&67108863}return i}function Og(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this.data[t]&32767,u=this.data[t++]>>15,l=a*c+u*o;c=o*c+((l&32767)<<15)+r.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=c&1073741823}return i}function Hf(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this.data[t]&16383,u=this.data[t++]>>14,l=a*c+u*o;c=o*c+((l&16383)<<14)+r.data[n]+i,i=(c>>28)+(l>>14)+a*u,r.data[n++]=c&268435455}return i}typeof navigator>"u"?(S.prototype.am=Hf,tr=28):zf&&navigator.appName=="Microsoft Internet Explorer"?(S.prototype.am=Og,tr=30):zf&&navigator.appName!="Netscape"?(S.prototype.am=kg,tr=26):(S.prototype.am=Hf,tr=28);S.prototype.DB=tr;S.prototype.DM=(1<<tr)-1;S.prototype.DV=1<<tr;var Ha=52;S.prototype.FV=Math.pow(2,Ha);S.prototype.F1=Ha-tr;S.prototype.F2=2*tr-Ha;var Mg="0123456789abcdefghijklmnopqrstuvwxyz",Ms=new Array,Rn,yt;Rn="0".charCodeAt(0);for(yt=0;yt<=9;++yt)Ms[Rn++]=yt;Rn="a".charCodeAt(0);for(yt=10;yt<36;++yt)Ms[Rn++]=yt;Rn="A".charCodeAt(0);for(yt=10;yt<36;++yt)Ms[Rn++]=yt;function Gf(t){return Mg.charAt(t)}function Yf(t,e){var r=Ms[t.charCodeAt(e)];return r??-1}function Fg(t){for(var e=this.t-1;e>=0;--e)t.data[e]=this.data[e];t.t=this.t,t.s=this.s}function Ug(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0}function yr(t){var e=J();return e.fromInt(t),e}function Kg(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==256)r=8;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else{this.fromRadix(t,e);return}this.t=0,this.s=0;for(var n=t.length,i=!1,s=0;--n>=0;){var o=r==8?t[n]&255:Yf(t,n);if(o<0){t.charAt(n)=="-"&&(i=!0);continue}i=!1,s==0?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this.data[this.t++]=o>>this.DB-s):this.data[this.t-1]|=o<<s,s+=r,s>=this.DB&&(s-=this.DB)}r==8&&t[0]&128&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&S.ZERO.subTo(this,this)}function Vg(){for(var t=this.s&this.DM;this.t>0&&this.data[this.t-1]==t;)--this.t}function qg(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else return this.toRadix(t);var r=(1<<e)-1,n,i=!1,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this.data[o]>>a)>0&&(i=!0,s=Gf(n));o>=0;)a<e?(n=(this.data[o]&(1<<a)-1)<<e-a,n|=this.data[--o]>>(a+=this.DB-e)):(n=this.data[o]>>(a-=e)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=Gf(n));return i?s:"0"}function $g(){var t=J();return S.ZERO.subTo(this,t),t}function zg(){return this.s<0?this.negate():this}function Hg(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this.data[r]-t.data[r])!=0)return e;return 0}function Fs(t){var e=1,r;return(r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function Gg(){return this.t<=0?0:this.DB*(this.t-1)+Fs(this.data[this.t-1]^this.s&this.DM)}function Yg(t,e){var r;for(r=this.t-1;r>=0;--r)e.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)e.data[r]=0;e.t=this.t+t,e.s=this.s}function Wg(t,e){for(var r=t;r<this.t;++r)e.data[r-t]=this.data[r];e.t=Math.max(this.t-t,0),e.s=this.s}function Qg(t,e){var r=t%this.DB,n=this.DB-r,i=(1<<n)-1,s=Math.floor(t/this.DB),o=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)e.data[a+s+1]=this.data[a]>>n|o,o=(this.data[a]&i)<<r;for(a=s-1;a>=0;--a)e.data[a]=0;e.data[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp()}function Xg(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<<n)-1;e.data[0]=this.data[r]>>n;for(var o=r+1;o<this.t;++o)e.data[o-r-1]|=(this.data[o]&s)<<i,e.data[o-r]=this.data[o]>>n;n>0&&(e.data[this.t-r-1]|=(this.s&s)<<i),e.t=this.t-r,e.clamp()}function Zg(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this.data[r]-t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n-=t.s;r<this.t;)n+=this.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<t.t;)n-=t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n-=t.s}e.s=n<0?-1:0,n<-1?e.data[r++]=this.DV+n:n>0&&(e.data[r++]=n),e.t=r,e.clamp()}function jg(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i<n.t;++i)e.data[i+r.t]=r.am(0,n.data[i],e,i,0,r.t);e.s=0,e.clamp(),this.s!=t.s&&S.ZERO.subTo(e,e)}function Jg(t){for(var e=this.abs(),r=t.t=2*e.t;--r>=0;)t.data[r]=0;for(r=0;r<e.t-1;++r){var n=e.am(r,e.data[r],t,2*r,0,1);(t.data[r+e.t]+=e.am(r+1,2*e.data[r],t,2*r+1,n,e.t-r-1))>=e.DV&&(t.data[r+e.t]-=e.DV,t.data[r+e.t+1]=1)}t.t>0&&(t.data[t.t-1]+=e.am(r,e.data[r],t,2*r,0,1)),t.s=0,t.clamp()}function e1(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=J());var s=J(),o=this.s,a=t.s,c=this.DB-Fs(n.data[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var u=s.t,l=s.data[u-1];if(l!=0){var f=l*(1<<this.F1)+(u>1?s.data[u-2]>>this.F2:0),h=this.FV/f,d=(1<<this.F1)/f,p=1<<this.F2,m=r.t,y=m-u,g=e??J();for(s.dlShiftTo(y,g),r.compareTo(g)>=0&&(r.data[r.t++]=1,r.subTo(g,r)),S.ONE.dlShiftTo(u,g),g.subTo(s,s);s.t<u;)s.data[s.t++]=0;for(;--y>=0;){var w=r.data[--m]==l?this.DM:Math.floor(r.data[m]*h+(r.data[m-1]+p)*d);if((r.data[m]+=s.am(0,w,r,y,0,u))<w)for(s.dlShiftTo(y,g),r.subTo(g,r);r.data[m]<--w;)r.subTo(g,r)}e!=null&&(r.drShiftTo(u,e),o!=a&&S.ZERO.subTo(e,e)),r.t=u,r.clamp(),c>0&&r.rShiftTo(c,r),o<0&&S.ZERO.subTo(r,r)}}}function t1(t){var e=J();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(S.ZERO)>0&&t.subTo(e,e),e}function Hr(t){this.m=t}function r1(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function n1(t){return t}function i1(t){t.divRemTo(this.m,null,t)}function s1(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function o1(t,e){t.squareTo(e),this.reduce(e)}Hr.prototype.convert=r1;Hr.prototype.revert=n1;Hr.prototype.reduce=i1;Hr.prototype.mulTo=s1;Hr.prototype.sqrTo=o1;function a1(){if(this.t<1)return 0;var t=this.data[0];if(!(t&1))return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Gr(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t}function c1(t){var e=J();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(S.ZERO)>0&&this.m.subTo(e,e),e}function u1(t){var e=J();return t.copyTo(e),this.reduce(e),e}function l1(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var e=0;e<this.m.t;++e){var r=t.data[e]&32767,n=r*this.mpl+((r*this.mph+(t.data[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t.data[r]+=this.m.am(0,n,t,e,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function f1(t,e){t.squareTo(e),this.reduce(e)}function h1(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Gr.prototype.convert=c1;Gr.prototype.revert=u1;Gr.prototype.reduce=l1;Gr.prototype.mulTo=h1;Gr.prototype.sqrTo=f1;function d1(){return(this.t>0?this.data[0]&1:this.s)==0}function p1(t,e){if(t>4294967295||t<1)return S.ONE;var r=J(),n=J(),i=e.convert(this),s=Fs(t)-1;for(i.copyTo(r);--s>=0;)if(e.sqrTo(r,n),(t&1<<s)>0)e.mulTo(n,i,r);else{var o=r;r=n,n=o}return e.revert(r)}function m1(t,e){var r;return t<256||e.isEven()?r=new Hr(e):r=new Gr(e),this.exp(t,r)}S.prototype.copyTo=Fg;S.prototype.fromInt=Ug;S.prototype.fromString=Kg;S.prototype.clamp=Vg;S.prototype.dlShiftTo=Yg;S.prototype.drShiftTo=Wg;S.prototype.lShiftTo=Qg;S.prototype.rShiftTo=Xg;S.prototype.subTo=Zg;S.prototype.multiplyTo=jg;S.prototype.squareTo=Jg;S.prototype.divRemTo=e1;S.prototype.invDigit=a1;S.prototype.isEven=d1;S.prototype.exp=p1;S.prototype.toString=qg;S.prototype.negate=$g;S.prototype.abs=zg;S.prototype.compareTo=Hg;S.prototype.bitLength=Gg;S.prototype.mod=t1;S.prototype.modPowInt=m1;S.ZERO=yr(0);S.ONE=yr(1);function y1(){var t=J();return this.copyTo(t),t}function g1(){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)<<this.DB|this.data[0]}function x1(){return this.t==0?this.s:this.data[0]<<24>>24}function w1(){return this.t==0?this.s:this.data[0]<<16>>16}function v1(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function E1(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function b1(t){if(t==null&&(t=10),this.signum()==0||t<2||t>36)return"0";var e=this.chunkSize(t),r=Math.pow(t,e),n=yr(r),i=J(),s=J(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(t).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(t)+o}function _1(t,e){this.fromInt(0),e==null&&(e=10);for(var r=this.chunkSize(e),n=Math.pow(e,r),i=!1,s=0,o=0,a=0;a<t.length;++a){var c=Yf(t,a);if(c<0){t.charAt(a)=="-"&&this.signum()==0&&(i=!0);continue}o=e*o+c,++s>=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),i&&S.ZERO.subTo(this,this)}function S1(t,e,r){if(typeof e=="number")if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(S.ONE.shiftLeft(t-1),Ga,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(S.ONE.shiftLeft(t-1),this);else{var n=new Array,i=t&7;n.length=(t>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<<i)-1:n[0]=0,this.fromString(n,256)}}function A1(){var t=this.t,e=new Array;e[0]=this.s;var r=this.DB-t*this.DB%8,n,i=0;if(t-- >0)for(r<this.DB&&(n=this.data[t]>>r)!=(this.s&this.DM)>>r&&(e[i++]=n|this.s<<this.DB-r);t>=0;)r<8?(n=(this.data[t]&(1<<r)-1)<<8-r,n|=this.data[--t]>>(r+=this.DB-8)):(n=this.data[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function I1(t){return this.compareTo(t)==0}function R1(t){return this.compareTo(t)<0?this:t}function C1(t){return this.compareTo(t)>0?this:t}function T1(t,e,r){var n,i,s=Math.min(t.t,this.t);for(n=0;n<s;++n)r.data[n]=e(this.data[n],t.data[n]);if(t.t<this.t){for(i=t.s&this.DM,n=s;n<this.t;++n)r.data[n]=e(this.data[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<t.t;++n)r.data[n]=e(i,t.data[n]);r.t=t.t}r.s=e(this.s,t.s),r.clamp()}function B1(t,e){return t&e}function L1(t){var e=J();return this.bitwiseTo(t,B1,e),e}function Ga(t,e){return t|e}function P1(t){var e=J();return this.bitwiseTo(t,Ga,e),e}function Wf(t,e){return t^e}function D1(t){var e=J();return this.bitwiseTo(t,Wf,e),e}function Qf(t,e){return t&~e}function N1(t){var e=J();return this.bitwiseTo(t,Qf,e),e}function k1(){for(var t=J(),e=0;e<this.t;++e)t.data[e]=this.DM&~this.data[e];return t.t=this.t,t.s=~this.s,t}function O1(t){var e=J();return t<0?this.rShiftTo(-t,e):this.lShiftTo(t,e),e}function M1(t){var e=J();return t<0?this.lShiftTo(-t,e):this.rShiftTo(t,e),e}function F1(t){if(t==0)return-1;var e=0;return t&65535||(t>>=16,e+=16),t&255||(t>>=8,e+=8),t&15||(t>>=4,e+=4),t&3||(t>>=2,e+=2),t&1||++e,e}function U1(){for(var t=0;t<this.t;++t)if(this.data[t]!=0)return t*this.DB+F1(this.data[t]);return this.s<0?this.t*this.DB:-1}function K1(t){for(var e=0;t!=0;)t&=t-1,++e;return e}function V1(){for(var t=0,e=this.s&this.DM,r=0;r<this.t;++r)t+=K1(this.data[r]^e);return t}function q1(t){var e=Math.floor(t/this.DB);return e>=this.t?this.s!=0:(this.data[e]&1<<t%this.DB)!=0}function $1(t,e){var r=S.ONE.shiftLeft(t);return this.bitwiseTo(r,e,r),r}function z1(t){return this.changeBit(t,Ga)}function H1(t){return this.changeBit(t,Qf)}function G1(t){return this.changeBit(t,Wf)}function Y1(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this.data[r]+t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n+=t.s;r<this.t;)n+=this.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<t.t;)n+=t.data[r],e.data[r++]=n&this.DM,n>>=this.DB;n+=t.s}e.s=n<0?-1:0,n>0?e.data[r++]=n:n<-1&&(e.data[r++]=this.DV+n),e.t=r,e.clamp()}function W1(t){var e=J();return this.addTo(t,e),e}function Q1(t){var e=J();return this.subTo(t,e),e}function X1(t){var e=J();return this.multiplyTo(t,e),e}function Z1(t){var e=J();return this.divRemTo(t,e,null),e}function j1(t){var e=J();return this.divRemTo(t,null,e),e}function J1(t){var e=J(),r=J();return this.divRemTo(t,e,r),new Array(e,r)}function ex(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function tx(t,e){if(t!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=t;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function Ci(){}function Xf(t){return t}function rx(t,e,r){t.multiplyTo(e,r)}function nx(t,e){t.squareTo(e)}Ci.prototype.convert=Xf;Ci.prototype.revert=Xf;Ci.prototype.mulTo=rx;Ci.prototype.sqrTo=nx;function ix(t){return this.exp(t,new Ci)}function sx(t,e,r){var n=Math.min(this.t+t.t,e);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var i;for(i=r.t-this.t;n<i;++n)r.data[n+this.t]=this.am(0,t.data[n],r,n,0,this.t);for(i=Math.min(t.t,e);n<i;++n)this.am(0,t.data[n],r,n,0,e-n);r.clamp()}function ox(t,e,r){--e;var n=r.t=this.t+t.t-e;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(e-this.t,0);n<t.t;++n)r.data[this.t+n-e]=this.am(e-n,t.data[n],r,0,0,this.t+n-e);r.clamp(),r.drShiftTo(1,r)}function Cn(t){this.r2=J(),this.q3=J(),S.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}function ax(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=J();return t.copyTo(e),this.reduce(e),e}function cx(t){return t}function ux(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function lx(t,e){t.squareTo(e),this.reduce(e)}function fx(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Cn.prototype.convert=ax;Cn.prototype.revert=cx;Cn.prototype.reduce=ux;Cn.prototype.mulTo=fx;Cn.prototype.sqrTo=lx;function hx(t,e){var r=t.bitLength(),n,i=yr(1),s;if(r<=0)return i;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?s=new Hr(e):e.isEven()?s=new Cn(e):s=new Gr(e);var o=new Array,a=3,c=n-1,u=(1<<n)-1;if(o[1]=s.convert(this),n>1){var l=J();for(s.sqrTo(o[1],l);a<=u;)o[a]=J(),s.mulTo(l,o[a-2],o[a]),a+=2}var f=t.t-1,h,d=!0,p=J(),m;for(r=Fs(t.data[f])-1;f>=0;){for(r>=c?h=t.data[f]>>r-c&u:(h=(t.data[f]&(1<<r+1)-1)<<c-r,f>0&&(h|=t.data[f-1]>>this.DB+r-c)),a=n;!(h&1);)h>>=1,--a;if((r-=a)<0&&(r+=this.DB,--f),d)o[h].copyTo(i),d=!1;else{for(;a>1;)s.sqrTo(i,p),s.sqrTo(p,i),a-=2;a>0?s.sqrTo(i,p):(m=i,i=p,p=m),s.mulTo(p,o[h],i)}for(;f>=0&&!(t.data[f]&1<<r);)s.sqrTo(i,p),m=i,i=p,p=m,--r<0&&(r=this.DB-1,--f)}return s.revert(i)}function dx(t){var e=this.s<0?this.negate():this.clone(),r=t.s<0?t.negate():t.clone();if(e.compareTo(r)<0){var n=e;e=r,r=n}var i=e.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return e;for(i<s&&(s=i),s>0&&(e.rShiftTo(s,e),r.rShiftTo(s,r));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),e.compareTo(r)>=0?(e.subTo(r,e),e.rShiftTo(1,e)):(r.subTo(e,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r}function px(t){if(t<=0)return 0;var e=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(e==0)r=this.data[0]%t;else for(var n=this.t-1;n>=0;--n)r=(e*r+this.data[n])%t;return r}function mx(t){var e=t.isEven();if(this.isEven()&&e||t.signum()==0)return S.ZERO;for(var r=t.clone(),n=this.clone(),i=yr(1),s=yr(0),o=yr(0),a=yr(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),e?((!i.isEven()||!s.isEven())&&(i.addTo(this,i),s.subTo(t,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(t,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),e&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(r,n),e&&o.subTo(i,o),a.subTo(s,a))}if(n.compareTo(S.ONE)!=0)return S.ZERO;if(a.compareTo(t)>=0)return a.subtract(t);if(a.signum()<0)a.addTo(t,a);else return a;return a.signum()<0?a.add(t):a}var _t=[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],yx=(1<<26)/_t[_t.length-1];function gx(t){var e,r=this.abs();if(r.t==1&&r.data[0]<=_t[_t.length-1]){for(e=0;e<_t.length;++e)if(r.data[0]==_t[e])return!0;return!1}if(r.isEven())return!1;for(e=1;e<_t.length;){for(var n=_t[e],i=e+1;i<_t.length&&n<yx;)n*=_t[i++];for(n=r.modInt(n);e<i;)if(n%_t[e++]==0)return!1}return r.millerRabin(t)}function xx(t){var e=this.subtract(S.ONE),r=e.getLowestSetBit();if(r<=0)return!1;for(var n=e.shiftRight(r),i=wx(),s,o=0;o<t;++o){do s=new S(this.bitLength(),i);while(s.compareTo(S.ONE)<=0||s.compareTo(e)>=0);var a=s.modPow(n,this);if(a.compareTo(S.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++<r&&a.compareTo(e)!=0;)if(a=a.modPowInt(2,this),a.compareTo(S.ONE)==0)return!1;if(a.compareTo(e)!=0)return!1}}return!0}function wx(){return{nextBytes:function(t){for(var e=0;e<t.length;++e)t[e]=Math.floor(Math.random()*256)}}}S.prototype.chunkSize=v1;S.prototype.toRadix=b1;S.prototype.fromRadix=_1;S.prototype.fromNumber=S1;S.prototype.bitwiseTo=T1;S.prototype.changeBit=$1;S.prototype.addTo=Y1;S.prototype.dMultiply=ex;S.prototype.dAddOffset=tx;S.prototype.multiplyLowerTo=sx;S.prototype.multiplyUpperTo=ox;S.prototype.modInt=px;S.prototype.millerRabin=xx;S.prototype.clone=y1;S.prototype.intValue=g1;S.prototype.byteValue=x1;S.prototype.shortValue=w1;S.prototype.signum=E1;S.prototype.toByteArray=A1;S.prototype.equals=I1;S.prototype.min=R1;S.prototype.max=C1;S.prototype.and=L1;S.prototype.or=P1;S.prototype.xor=D1;S.prototype.andNot=N1;S.prototype.not=k1;S.prototype.shiftLeft=O1;S.prototype.shiftRight=M1;S.prototype.getLowestSetBit=U1;S.prototype.bitCount=V1;S.prototype.testBit=q1;S.prototype.setBit=z1;S.prototype.clearBit=H1;S.prototype.flipBit=G1;S.prototype.add=W1;S.prototype.subtract=Q1;S.prototype.multiply=X1;S.prototype.divide=Z1;S.prototype.remainder=j1;S.prototype.divideAndRemainder=J1;S.prototype.modPow=hx;S.prototype.modInverse=mx;S.prototype.pow=ix;S.prototype.gcd=dx;S.prototype.isProbablePrime=gx});var r0=R((W_,t0)=>{var Ut=se();$r();Ie();var Jf=t0.exports=Ut.sha1=Ut.sha1||{};Ut.md.sha1=Ut.md.algorithms.sha1=Jf;Jf.create=function(){e0||vx();var t=null,e=Ut.util.createBuffer(),r=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s<i;++s)n.fullMessageLength.push(0);return e=Ut.util.createBuffer(),t={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=Ut.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),jf(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Ut.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Ya.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4};jf(f,r,i);var h=Ut.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var Ya=null,e0=!1;function vx(){Ya=String.fromCharCode(128),Ya+=Ut.util.fillString(String.fromCharCode(0),64),e0=!0}function jf(t,e,r){for(var n,i,s,o,a,c,u,l,f=r.length();f>=64;){for(i=t.h0,s=t.h1,o=t.h2,a=t.h3,c=t.h4,l=0;l<16;++l)n=r.getInt32(),e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s&o|a&(s^o),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;t.h0=t.h0+i|0,t.h1=t.h1+s|0,t.h2=t.h2+o|0,t.h3=t.h3+a|0,t.h4=t.h4+c|0,f-=64}}});var s0=R((Q_,i0)=>{var Kt=se();Ie();Ri();r0();var n0=i0.exports=Kt.pkcs1=Kt.pkcs1||{};n0.encode_rsa_oaep=function(t,e,r){var n,i,s,o;typeof r=="string"?(n=r,i=arguments[3]||void 0,s=arguments[4]||void 0):r&&(n=r.label||void 0,i=r.seed||void 0,s=r.md||void 0,r.mgf1&&r.mgf1.md&&(o=r.mgf1.md)),s?s.start():s=Kt.md.sha1.create(),o||(o=s);var a=Math.ceil(t.n.bitLength()/8),c=a-2*s.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),s.update(n,"raw");for(var l=s.digest(),f="",h=c-e.length,d=0;d<h;d++)f+="\0";var p=l.getBytes()+f+""+e;if(!i)i=Kt.random.getBytes(s.digestLength);else if(i.length!==s.digestLength){var u=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=s.digestLength,u}var m=Ks(i,a-s.digestLength-1,o),y=Kt.util.xorBytes(p,m,p.length),g=Ks(y,s.digestLength,o),w=Kt.util.xorBytes(i,g,i.length);return"\0"+w+y};n0.decode_rsa_oaep=function(t,e,r){var n,i,s;typeof r=="string"?(n=r,i=arguments[3]||void 0):r&&(n=r.label||void 0,i=r.md||void 0,r.mgf1&&r.mgf1.md&&(s=r.mgf1.md));var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var y=new Error("RSAES-OAEP encoded message length is invalid.");throw y.length=e.length,y.expectedLength=o,y}if(i===void 0?i=Kt.md.sha1.create():i.start(),s||(s=i),o<2*i.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");n||(n=""),i.update(n,"raw");for(var a=i.digest().getBytes(),c=e.charAt(0),u=e.substring(1,i.digestLength+1),l=e.substring(1+i.digestLength),f=Ks(l,i.digestLength,s),h=Kt.util.xorBytes(u,f,u.length),d=Ks(h,o-i.digestLength-1,s),p=Kt.util.xorBytes(l,d,l.length),m=p.substring(0,i.digestLength),y=c!=="\0",g=0;g<i.digestLength;++g)y|=a.charAt(g)!==m.charAt(g);for(var w=1,_=i.digestLength,N=i.digestLength;N<p.length;N++){var C=p.charCodeAt(N),T=C&1^1,H=w?65534:0;y|=C&H,w=w&T,_+=w}if(y||p.charCodeAt(_)!==1)throw new Error("Invalid RSAES-OAEP padding.");return p.substring(_+1)};function Ks(t,e,r){r||(r=Kt.md.sha1.create());for(var n="",i=Math.ceil(e/r.digestLength),s=0;s<i;++s){var o=String.fromCharCode(s>>24&255,s>>16&255,s>>8&255,s&255);r.start(),r.update(t+o),n+=r.digest().getBytes()}return n.substring(0,e)}});var o0=R((X_,Wa)=>{var gr=se();Ie();Us();Ri();(function(){if(gr.prime){Wa.exports=gr.prime;return}var t=Wa.exports=gr.prime=gr.prime||{},e=gr.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,h){return f|h};t.generateProbablePrime=function(f,h,d){typeof h=="function"&&(d=h,h={}),h=h||{};var p=h.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var m=h.prng||gr.random,y={nextBytes:function(g){for(var w=m.getBytesSync(g.length),_=0;_<g.length;++_)g[_]=w.charCodeAt(_)}};if(p.name==="PRIMEINC")return s(f,y,p.options,d);throw new Error("Invalid prime generation algorithm: "+p.name)};function s(f,h,d,p){return"workers"in d?c(f,h,d,p):o(f,h,d,p)}function o(f,h,d,p){var m=u(f,h),y=0,g=l(m.bitLength());"millerRabinTests"in d&&(g=d.millerRabinTests);var w=10;"maxBlockTime"in d&&(w=d.maxBlockTime),a(m,f,h,y,g,w,p)}function a(f,h,d,p,m,y,g){var w=+new Date;do{if(f.bitLength()>h&&(f=u(h,d)),f.isProbablePrime(m))return g(null,f);f.dAddOffset(r[p++%8],0)}while(y<0||+new Date-w<y);gr.util.setImmediate(function(){a(f,h,d,p,m,y,g)})}function c(f,h,d,p){if(typeof Worker>"u")return o(f,h,d,p);var m=u(f,h),y=d.workers,g=d.workLoad||100,w=g*30/8,_=d.workerScript||"forge/prime.worker.js";if(y===-1)return gr.util.estimateCores(function(C,T){C&&(T=2),y=T-1,N()});N();function N(){y=Math.max(1,y);for(var C=[],T=0;T<y;++T)C[T]=new Worker(_);for(var H=y,T=0;T<y;++T)C[T].addEventListener("message",De);var W=!1;function De(Et){if(!W){--H;var it=Et.data;if(it.found){for(var We=0;We<C.length;++We)C[We].terminate();return W=!0,p(null,new e(it.prime,16))}m.bitLength()>f&&(m=u(f,h));var _n=m.toString(16);Et.target.postMessage({hex:_n,workLoad:g}),m.dAddOffset(w,0)}}}}function u(f,h){var d=new e(f,h),p=f-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var qs=R((Z_,d0)=>{var M=se();Ii();Us();Is();s0();o0();Ri();Ie();typeof Q>"u"&&(Q=M.jsbn.BigInteger);var Q,Qa=M.util.isNodejs?zr():null,v=M.asn1,gt=M.util;M.pki=M.pki||{};d0.exports=M.pki.rsa=M.rsa=M.rsa||{};var K=M.pki,Ex=[6,4,2,4,2,4,6,2],bx={name:"PrivateKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},_x={name:"RSAPrivateKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Sx={name:"RSAPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:v.Class.UNIVERSAL,type:v.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Ax=M.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Ix={name:"DigestInfo",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:v.Class.UNIVERSAL,type:v.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:v.Class.UNIVERSAL,type:v.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:v.Class.UNIVERSAL,type:v.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:v.Class.UNIVERSAL,type:v.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Rx=function(t){var e;if(t.algorithm in K.oids)e=K.oids[t.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=t.algorithm,r}var n=v.oidToDer(e).getBytes(),i=v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[]),s=v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[]);s.value.push(v.create(v.Class.UNIVERSAL,v.Type.OID,!1,n)),s.value.push(v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,""));var o=v.create(v.Class.UNIVERSAL,v.Type.OCTETSTRING,!1,t.digest().getBytes());return i.value.push(s),i.value.push(o),v.toDer(i).getBytes()},f0=function(t,e,r){if(r)return t.modPow(e.e,e.n);if(!e.p||!e.q)return t.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(Q.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(Q.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new Q(M.util.bytesToHex(M.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(Q.ONE));t=t.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=t.mod(e.p).modPow(e.dP,e.p),s=t.mod(e.q).modPow(e.dQ,e.q);i.compareTo(s)<0;)i=i.add(e.p);var o=i.subtract(s).multiply(e.qInv).mod(e.p).multiply(e.q).add(s);return o=o.multiply(n.modInverse(e.n)).mod(e.n),o};K.rsa.encrypt=function(t,e,r){var n=r,i,s=Math.ceil(e.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,i=h0(t,e,r)):(i=M.util.createBuffer(),i.putBytes(t));for(var o=new Q(i.toHex(),16),a=f0(o,e,n),c=a.toString(16),u=M.util.createBuffer(),l=s-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(M.util.hexToBytes(c)),u.getBytes()};K.rsa.decrypt=function(t,e,r,n){var i=Math.ceil(e.n.bitLength()/8);if(t.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=t.length,s.expected=i,s}var o=new Q(M.util.createBuffer(t).toHex(),16);if(o.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=f0(o,e,r),c=a.toString(16),u=M.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(M.util.hexToBytes(c)),n!==!1?Vs(u.getBytes(),e,r):u.getBytes()};K.rsa.createKeyPairGenerationState=function(t,e,r){typeof t=="string"&&(t=parseInt(t,10)),t=t||2048,r=r||{};var n=r.prng||M.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},s=r.algorithm||"PRIMEINC",o;if(s==="PRIMEINC")o={algorithm:s,state:0,bits:t,rng:i,eInt:e||65537,e:new Q(null),p:null,q:null,qBits:t>>1,pBits:t-(t>>1),pqState:0,num:null,keys:null},o.e.fromInt(o.eInt);else throw new Error("Invalid key generation algorithm: "+s);return o};K.rsa.stepKeyPairGenerationState=function(t,e){"algorithm"in t||(t.algorithm="PRIMEINC");var r=new Q(null);r.fromInt(30);for(var n=0,i=function(f,h){return f|h},s=+new Date,o,a=0;t.keys===null&&(e<=0||a<e);){if(t.state===0){var c=t.p===null?t.pBits:t.qBits,u=c-1;t.pqState===0?(t.num=new Q(c,t.rng),t.num.testBit(u)||t.num.bitwiseTo(Q.ONE.shiftLeft(u),i,t.num),t.num.dAddOffset(31-t.num.mod(r).byteValue(),0),n=0,++t.pqState):t.pqState===1?t.num.bitLength()>c?t.pqState=0:t.num.isProbablePrime(Tx(t.num.bitLength()))?++t.pqState:t.num.dAddOffset(Ex[n++%8],0):t.pqState===2?t.pqState=t.num.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)===0?3:0:t.pqState===3&&(t.pqState=0,t.p===null?t.p=t.num:t.q=t.num,t.p!==null&&t.q!==null&&++t.state,t.num=null)}else if(t.state===1)t.p.compareTo(t.q)<0&&(t.num=t.p,t.p=t.q,t.q=t.num),++t.state;else if(t.state===2)t.p1=t.p.subtract(Q.ONE),t.q1=t.q.subtract(Q.ONE),t.phi=t.p1.multiply(t.q1),++t.state;else if(t.state===3)t.phi.gcd(t.e).compareTo(Q.ONE)===0?++t.state:(t.p=null,t.q=null,t.state=0);else if(t.state===4)t.n=t.p.multiply(t.q),t.n.bitLength()===t.bits?++t.state:(t.q=null,t.state=0);else if(t.state===5){var l=t.e.modInverse(t.phi);t.keys={privateKey:K.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:K.rsa.setPublicKey(t.n,t.e)}}o=+new Date,a+=o-s,s=o}return t.keys!==null};K.rsa.generateKeyPair=function(t,e,r,n){if(arguments.length===1?typeof t=="object"?(r=t,t=void 0):typeof t=="function"&&(n=t,t=void 0):arguments.length===2?typeof t=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(r=e,e=void 0):(r=t,n=e,t=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=e,e=void 0)),r=r||{},t===void 0&&(t=r.bits||2048),e===void 0&&(e=r.e||65537),!M.options.usePureJavaScript&&!r.prng&&t>=256&&t<=16384&&(e===65537||e===3)){if(n){if(a0("generateKeyPair"))return Qa.generateKeyPair("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:K.privateKeyFromPem(u),publicKey:K.publicKeyFromPem(c)})});if(c0("generateKey")&&c0("exportKey"))return gt.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:l0(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return gt.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=K.privateKeyFromAsn1(v.fromDer(M.util.createBuffer(a)));n(null,{privateKey:c,publicKey:K.setRsaPublicKey(c.n,c.e)})}});if(u0("generateKey")&&u0("exportKey")){var i=gt.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:l0(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=gt.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,h=K.privateKeyFromAsn1(v.fromDer(M.util.createBuffer(f)));n(null,{privateKey:h,publicKey:K.setRsaPublicKey(h.n,h.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(a0("generateKeyPairSync")){var s=Qa.generateKeyPairSync("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:K.privateKeyFromPem(s.privateKey),publicKey:K.publicKeyFromPem(s.publicKey)}}}var o=K.rsa.createKeyPairGenerationState(t,e,r);if(!n)return K.rsa.stepKeyPairGenerationState(o,0),o.keys;Cx(o,r,n)};K.setRsaPublicKey=K.rsa.setPublicKey=function(t,e){var r={n:t,e};return r.encrypt=function(n,i,s){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return h0(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return M.pkcs1.encode_rsa_oaep(c,a,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var o=i.encode(n,r,!0);return K.rsa.encrypt(o,r,!0)},r.verify=function(n,i,s,o){typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSASSA-PKCS1-V1_5"),o===void 0&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),s==="RSASSA-PKCS1-V1_5"?s={verify:function(c,u){u=Vs(u,r,!0);var l=v.fromDer(u,{parseAllBytes:o._parseAllDigestBytes}),f={},h=[];if(!v.validate(l,Ix,f,h)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=h,d}var p=v.derToOid(f.algorithmIdentifier);if(!(p===M.oids.md2||p===M.oids.md5||p===M.oids.sha1||p===M.oids.sha224||p===M.oids.sha256||p===M.oids.sha384||p===M.oids.sha512||p===M.oids["sha512-224"]||p===M.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===M.oids.md2||p===M.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(s==="NONE"||s==="NULL"||s===null)&&(s={verify:function(c,u){return u=Vs(u,r,!0),c===u}});var a=K.rsa.decrypt(i,r,!0,!1);return s.verify(n,a,r.n.bitLength())},r};K.setRsaPrivateKey=K.rsa.setPrivateKey=function(t,e,r,n,i,s,o,a){var c={n:t,e,d:r,p:n,q:i,dP:s,dQ:o,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var h=K.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Vs};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return M.pkcs1.decode_rsa_oaep(p,d,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(d){return d}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(h,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:Rx},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var h=l.encode(u,c.n.bitLength());return K.rsa.encrypt(h,c,f)},c};K.wrapRsaPrivateKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,v.integerToDer(0).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.OID,!1,v.oidToDer(K.oids.rsaEncryption).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,"")]),v.create(v.Class.UNIVERSAL,v.Type.OCTETSTRING,!1,v.toDer(t).getBytes())])};K.privateKeyFromAsn1=function(t){var e={},r=[];if(v.validate(t,bx,e,r)&&(t=v.fromDer(M.util.createBuffer(e.privateKey))),e={},r=[],!v.validate(t,_x,e,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var i,s,o,a,c,u,l,f;return i=M.util.createBuffer(e.privateKeyModulus).toHex(),s=M.util.createBuffer(e.privateKeyPublicExponent).toHex(),o=M.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=M.util.createBuffer(e.privateKeyPrime1).toHex(),c=M.util.createBuffer(e.privateKeyPrime2).toHex(),u=M.util.createBuffer(e.privateKeyExponent1).toHex(),l=M.util.createBuffer(e.privateKeyExponent2).toHex(),f=M.util.createBuffer(e.privateKeyCoefficient).toHex(),K.setRsaPrivateKey(new Q(i,16),new Q(s,16),new Q(o,16),new Q(a,16),new Q(c,16),new Q(u,16),new Q(l,16),new Q(f,16))};K.privateKeyToAsn1=K.privateKeyToRSAPrivateKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,v.integerToDer(0).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.n)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.e)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.d)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.p)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.q)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.dP)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.dQ)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.qInv))])};K.publicKeyFromAsn1=function(t){var e={},r=[];if(v.validate(t,Ax,e,r)){var n=v.derToOid(e.publicKeyOid);if(n!==K.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}t=e.rsaPublicKey}if(r=[],!v.validate(t,Sx,e,r)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=r,i}var s=M.util.createBuffer(e.publicKeyModulus).toHex(),o=M.util.createBuffer(e.publicKeyExponent).toHex();return K.setRsaPublicKey(new Q(s,16),new Q(o,16))};K.publicKeyToAsn1=K.publicKeyToSubjectPublicKeyInfo=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.OID,!1,v.oidToDer(K.oids.rsaEncryption).getBytes()),v.create(v.Class.UNIVERSAL,v.Type.NULL,!1,"")]),v.create(v.Class.UNIVERSAL,v.Type.BITSTRING,!1,[K.publicKeyToRSAPublicKey(t)])])};K.publicKeyToRSAPublicKey=function(t){return v.create(v.Class.UNIVERSAL,v.Type.SEQUENCE,!0,[v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.n)),v.create(v.Class.UNIVERSAL,v.Type.INTEGER,!1,Vt(t.e))])};function h0(t,e,r){var n=M.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(t.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=t.length,s.max=i-11,s}n.putByte(0),n.putByte(r);var o=i-3-t.length,a;if(r===0||r===1){a=r===0?0:255;for(var c=0;c<o;++c)n.putByte(a)}else for(;o>0;){for(var u=0,l=M.random.getBytes(o),c=0;c<o;++c)a=l.charCodeAt(c),a===0?++u:n.putByte(a);o=u}return n.putByte(0),n.putBytes(t),n}function Vs(t,e,r,n){var i=Math.ceil(e.n.bitLength()/8),s=M.util.createBuffer(t),o=s.getByte(),a=s.getByte();if(o!==0||r&&a!==0&&a!==1||!r&&a!=2||r&&a===0&&typeof n>"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u<c;++u)if(s.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(a===1)for(c=0;s.length()>1;){if(s.getByte()!==255){--s.read;break}++c}else if(a===2)for(c=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++c}var l=s.getByte();if(l!==0||c!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function Cx(t,e,r){typeof e=="function"&&(r=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){s(t.pBits,function(a,c){if(a)return r(a);if(t.p=c,t.q!==null)return o(a,t.q);s(t.qBits,o)})}function s(a,c){M.prime.generateProbablePrime(a,n,c)}function o(a,c){if(a)return r(a);if(t.q=c,t.p.compareTo(t.q)<0){var u=t.p;t.p=t.q,t.q=u}if(t.p.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)!==0){t.p=null,i();return}if(t.q.subtract(Q.ONE).gcd(t.e).compareTo(Q.ONE)!==0){t.q=null,s(t.qBits,o);return}if(t.p1=t.p.subtract(Q.ONE),t.q1=t.q.subtract(Q.ONE),t.phi=t.p1.multiply(t.q1),t.phi.gcd(t.e).compareTo(Q.ONE)!==0){t.p=t.q=null,i();return}if(t.n=t.p.multiply(t.q),t.n.bitLength()!==t.bits){t.q=null,s(t.qBits,o);return}var l=t.e.modInverse(t.phi);t.keys={privateKey:K.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:K.rsa.setPublicKey(t.n,t.e)},r(null,t.keys)}}function Vt(t){var e=t.toString(16);e[0]>="8"&&(e="00"+e);var r=M.util.hexToBytes(e);return r.length>1&&(r.charCodeAt(0)===0&&!(r.charCodeAt(1)&128)||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function Tx(t){return t<=100?27:t<=150?18:t<=200?15:t<=250?12:t<=300?9:t<=350?8:t<=400?7:t<=500?6:t<=600?5:t<=800?4:t<=1250?3:2}function a0(t){return M.util.isNodejs&&typeof Qa[t]=="function"}function c0(t){return typeof gt.globalScope<"u"&&typeof gt.globalScope.crypto=="object"&&typeof gt.globalScope.crypto.subtle=="object"&&typeof gt.globalScope.crypto.subtle[t]=="function"}function u0(t){return typeof gt.globalScope<"u"&&typeof gt.globalScope.msCrypto=="object"&&typeof gt.globalScope.msCrypto.subtle=="object"&&typeof gt.globalScope.msCrypto.subtle[t]=="function"}function l0(t){for(var e=M.util.hexToBytes(t.toString(16)),r=new Uint8Array(e.length),n=0;n<e.length;++n)r[n]=e.charCodeAt(n);return r}});var w0=R((j_,x0)=>{var L=se();Ls();Ii();Sf();$r();Is();Ka();Lf();Ri();$f();qs();Ie();typeof p0>"u"&&(p0=L.jsbn.BigInteger);var p0,b=L.asn1,q=L.pki=L.pki||{};x0.exports=q.pbe=L.pbe=L.pbe||{};var Yr=q.oids,Bx={name:"EncryptedPrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},Lx={name:"PBES2Algorithms",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},Px={name:"pkcs-12PbeParams",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"iterations"}]};q.encryptPrivateKeyInfo=function(t,e,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=L.random.getBytesSync(r.saltSize),i=r.count,s=b.integerToDer(i),o,a,c;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var u,l,f;switch(r.algorithm){case"aes128":o=16,u=16,l=Yr["aes128-CBC"],f=L.aes.createEncryptionCipher;break;case"aes192":o=24,u=16,l=Yr["aes192-CBC"],f=L.aes.createEncryptionCipher;break;case"aes256":o=32,u=16,l=Yr["aes256-CBC"],f=L.aes.createEncryptionCipher;break;case"des":o=8,u=8,l=Yr.desCBC,f=L.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var d="hmacWith"+r.prfAlgorithm.toUpperCase(),p=g0(d),m=L.pkcs5.pbkdf2(e,n,i,o,p),y=L.random.getBytesSync(u),g=f(m);g.start(y),g.update(b.toDer(t)),g.finish(),c=g.output.getBytes();var w=Dx(n,s,o,d);a=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr.pkcs5PBES2).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr.pkcs5PBKDF2).getBytes()),w]),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(l).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,y)])])])}else if(r.algorithm==="3des"){o=24;var _=new L.util.ByteBuffer(n),m=q.pbe.generatePkcs12Key(e,_,1,i,o),y=q.pbe.generatePkcs12Key(e,_,2,i,o),g=L.des.createEncryptionCipher(m);g.start(y),g.update(b.toDer(t)),g.finish(),c=g.output.getBytes(),a=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(Yr["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,n),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,s.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var N=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[a,b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,c)]);return N};q.decryptPrivateKeyInfo=function(t,e){var r=null,n={},i=[];if(!b.validate(t,Bx,n,i)){var s=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=b.derToOid(n.encryptionOid),a=q.pbe.getCipher(o,n.encryptionParams,e),c=L.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(r=b.fromDer(a.output)),r};q.encryptedPrivateKeyToPem=function(t,e){var r={type:"ENCRYPTED PRIVATE KEY",body:b.toDer(t).getBytes()};return L.pem.encode(r,{maxline:e})};q.encryptedPrivateKeyFromPem=function(t){var e=L.pem.decode(t)[0];if(e.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=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return b.fromDer(e.body)};q.encryptRsaPrivateKey=function(t,e,r){if(r=r||{},!r.legacy){var n=q.wrapRsaPrivateKey(q.privateKeyToAsn1(t));return n=q.encryptPrivateKeyInfo(n,e,r),q.encryptedPrivateKeyToPem(n)}var i,s,o,a;switch(r.algorithm){case"aes128":i="AES-128-CBC",o=16,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",o=24,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",o=32,s=L.random.getBytesSync(16),a=L.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",o=24,s=L.random.getBytesSync(8),a=L.des.createEncryptionCipher;break;case"des":i="DES-CBC",o=8,s=L.random.getBytesSync(8),a=L.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw c.algorithm=r.algorithm,c}var u=L.pbe.opensslDeriveBytes(e,s.substr(0,8),o),l=a(u);l.start(s),l.update(b.toDer(q.privateKeyToAsn1(t))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:L.util.bytesToHex(s).toUpperCase()},body:l.output.getBytes()};return L.pem.encode(f)};q.decryptRsaPrivateKey=function(t,e){var r=null,n=L.pem.decode(t)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var s,o;switch(n.dekInfo.algorithm){case"DES-CBC":s=8,o=L.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,o=L.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,o=L.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,o=L.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,o=L.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,o=function(f){return L.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":s=8,o=function(f){return L.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":s=16,o=function(f){return L.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=L.util.hexToBytes(n.dekInfo.parameters),c=L.pbe.opensslDeriveBytes(e,a.substr(0,8),s),u=o(c);if(u.start(a),u.update(L.util.createBuffer(n.body)),u.finish())r=u.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=q.decryptPrivateKeyInfo(b.fromDer(r),e):r=b.fromDer(r),r!==null&&(r=q.privateKeyFromAsn1(r)),r};q.pbe.generatePkcs12Key=function(t,e,r,n,i,s){var o,a;if(typeof s>"u"||s===null){if(!("sha1"in L.md))throw new Error('"sha1" hash algorithm unavailable.');s=L.md.sha1.create()}var c=s.digestLength,u=s.blockLength,l=new L.util.ByteBuffer,f=new L.util.ByteBuffer;if(t!=null){for(a=0;a<t.length;a++)f.putInt16(t.charCodeAt(a));f.putInt16(0)}var h=f.length(),d=e.length(),p=new L.util.ByteBuffer;p.fillWithByte(r,u);var m=u*Math.ceil(d/u),y=new L.util.ByteBuffer;for(a=0;a<m;a++)y.putByte(e.at(a%d));var g=u*Math.ceil(h/u),w=new L.util.ByteBuffer;for(a=0;a<g;a++)w.putByte(f.at(a%h));var _=y;_.putBuffer(w);for(var N=Math.ceil(i/c),C=1;C<=N;C++){var T=new L.util.ByteBuffer;T.putBytes(p.bytes()),T.putBytes(_.bytes());for(var H=0;H<n;H++)s.start(),s.update(T.getBytes()),T=s.digest();var W=new L.util.ByteBuffer;for(a=0;a<u;a++)W.putByte(T.at(a%c));var De=Math.ceil(d/u)+Math.ceil(h/u),Et=new L.util.ByteBuffer;for(o=0;o<De;o++){var it=new L.util.ByteBuffer(_.getBytes(u)),We=511;for(a=W.length()-1;a>=0;a--)We=We>>8,We+=W.at(a)+it.at(a),it.setAt(a,We&255);Et.putBuffer(it)}_=Et,l.putBuffer(T)}return l.truncate(l.length()-i),l};q.pbe.getCipher=function(t,e,r){switch(t){case q.oids.pkcs5PBES2:return q.pbe.getCipherForPBES2(t,e,r);case q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case q.oids["pbewithSHAAnd40BitRC2-CBC"]:return q.pbe.getCipherForPKCS12PBE(t,e,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=t,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};q.pbe.getCipherForPBES2=function(t,e,r){var n={},i=[];if(!b.validate(e,Lx,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(t=b.derToOid(n.kdfOid),t!==q.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=t,s.supportedOids=["pkcs5PBKDF2"],s}if(t=b.derToOid(n.encOid),t!==q.oids["aes128-CBC"]&&t!==q.oids["aes192-CBC"]&&t!==q.oids["aes256-CBC"]&&t!==q.oids["des-EDE3-CBC"]&&t!==q.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=t,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var o=n.kdfSalt,a=L.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(q.oids[t]){case"aes128-CBC":c=16,u=L.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=L.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=L.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=L.des.createDecryptionCipher;break;case"desCBC":c=8,u=L.des.createDecryptionCipher;break}var l=y0(n.prfOid),f=L.pkcs5.pbkdf2(r,o,a,c,l),h=n.encIv,d=u(f);return d.start(h),d};q.pbe.getCipherForPKCS12PBE=function(t,e,r){var n={},i=[];if(!b.validate(e,Px,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=L.util.createBuffer(n.salt),a=L.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(t){case q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=L.des.startDecrypting;break;case q.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(m,y){var g=L.rc2.createDecryptionCipher(m,40);return g.start(y,null),g};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=t,s}var f=y0(n.prfOid),h=q.pbe.generatePkcs12Key(r,o,1,a,c,f);f.start();var d=q.pbe.generatePkcs12Key(r,o,2,a,u,f);return l(h,d)};q.pbe.opensslDeriveBytes=function(t,e,r,n){if(typeof n>"u"||n===null){if(!("md5"in L.md))throw new Error('"md5" hash algorithm unavailable.');n=L.md.md5.create()}e===null&&(e="");for(var i=[m0(n,t+e)],s=16,o=1;s<r;++o,s+=16)i.push(m0(n,i[o-1]+t+e));return i.join("").substr(0,r)};function m0(t,e){return t.start().update(e).digest().getBytes()}function y0(t){var e;if(!t)e="hmacWithSHA1";else if(e=q.oids[b.derToOid(t)],!e){var r=new Error("Unsupported PRF OID.");throw r.oid=t,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}return g0(e)}function g0(t){var e=L.md;switch(t){case"hmacWithSHA224":e=L.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":t=t.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=t,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!e||!(t in e))throw new Error("Unknown hash algorithm: "+t);return e[t].create()}function Dx(t,e,r,n){var i=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,t),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,e.getBytes())]);return n!=="hmacWithSHA1"&&i.value.push(b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,L.util.hexToBytes(r.toString(16))),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(q.oids[n]).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")])),i}});var rh=R((rA,th)=>{"use strict";th.exports=n2;function n2(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i<arguments.length;)r[n++]=arguments[i++];return new Promise(function(a,c){r[n]=function(l){if(s)if(s=!1,l)c(l);else{for(var f=new Array(arguments.length-1),h=0;h<f.length;)f[h++]=arguments[h];a.apply(null,f)}};try{t.apply(e||null,r)}catch(u){s&&(s=!1,c(u))}})}});var oh=R(sh=>{"use strict";var js=sh;js.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var kn=new Array(64),ih=new Array(123);for(At=0;At<64;)ih[kn[At]=At<26?At+65:At<52?At+71:At<62?At-4:At-59|43]=At++;var At;js.encode=function(e,r,n){for(var i=null,s=[],o=0,a=0,c;r<n;){var u=e[r++];switch(a){case 0:s[o++]=kn[u>>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=kn[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=kn[c|u>>6],s[o++]=kn[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=kn[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var nh="invalid encoding";js.decode=function(e,r,n){for(var i=n,s=0,o,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&s>1)break;if((c=ih[c])===void 0)throw Error(nh);switch(s){case 0:o=c,s=1;break;case 1:r[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:r[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:r[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(nh);return n-i};js.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var ch=R((iA,ah)=>{"use strict";ah.exports=Js;function Js(){this._listeners={}}Js.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};Js.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i<n.length;)n[i].fn===r?n.splice(i,1):++i;return this};Js.prototype.emit=function(e){var r=this._listeners[e];if(r){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<r.length;)r[i].fn.apply(r[i++].ctx,n)}return this}});var mh=R((sA,ph)=>{"use strict";ph.exports=uh(uh);function uh(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3]}function s(c,u,l){e[0]=c,u[l]=r[3],u[l+1]=r[2],u[l+2]=r[1],u[l+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],e[0]}function a(c,u){return r[3]=c[u],r[2]=c[u+1],r[1]=c[u+2],r[0]=c[u+3],e[0]}t.readFloatLE=n?o:a,t.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,o)}}t.writeFloatLE=e.bind(null,lh),t.writeFloatBE=e.bind(null,fh);function r(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}t.readFloatLE=r.bind(null,hh),t.readFloatBE=r.bind(null,dh)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3],u[l+4]=r[4],u[l+5]=r[5],u[l+6]=r[6],u[l+7]=r[7]}function s(c,u,l){e[0]=c,u[l]=r[7],u[l+1]=r[6],u[l+2]=r[5],u[l+3]=r[4],u[l+4]=r[3],u[l+5]=r[2],u[l+6]=r[1],u[l+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],r[4]=c[u+4],r[5]=c[u+5],r[6]=c[u+6],r[7]=c[u+7],e[0]}function a(c,u){return r[7]=c[u],r[6]=c[u+1],r[5]=c[u+2],r[4]=c[u+3],r[3]=c[u+4],r[2]=c[u+5],r[1]=c[u+6],r[0]=c[u+7],e[0]}t.readDoubleLE=n?o:a,t.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var f=Math.floor(Math.log(o)/Math.LN2);f===1024&&(f=1023),l=o*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}t.writeDoubleLE=e.bind(null,lh,0,4),t.writeDoubleBE=e.bind(null,fh,4,0);function r(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,f=u>>>20&2047,h=4294967296*(u&1048575)+c;return f===2047?h?NaN:l*(1/0):f===0?l*5e-324*h:l*Math.pow(2,f-1075)*(h+4503599627370496)}t.readDoubleLE=r.bind(null,hh,0,4),t.readDoubleBE=r.bind(null,dh,4,0)}(),t}function lh(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function fh(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function hh(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function dh(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var yh=R((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var xh=R(gh=>{"use strict";var Ic=gh;Ic.length=function(e){for(var r=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?r+=1:n<2048?r+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,r+=4):r+=3;return r};Ic.read=function(e,r,n){var i=n-r;if(i<1)return"";for(var s=null,o=[],a=0,c;r<n;)c=e[r++],c<128?o[a++]=c:c>191&&c<224?o[a++]=(c&31)<<6|e[r++]&63:c>239&&c<365?(c=((c&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};Ic.write=function(e,r,n){for(var i=n,s,o,a=0;a<e.length;++a)s=e.charCodeAt(a),s<128?r[n++]=s:s<2048?(r[n++]=s>>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var vh=R((aA,wh)=>{"use strict";wh.exports=i2;function i2(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return t(c);o+c>n&&(s=t(n),o=0);var u=e.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var bh=R((cA,Eh)=>{"use strict";Eh.exports=Ue;var Oi=en();function Ue(t,e){this.lo=t>>>0,this.hi=e>>>0}var Jr=Ue.zero=new Ue(0,0);Jr.toNumber=function(){return 0};Jr.zzEncode=Jr.zzDecode=function(){return this};Jr.length=function(){return 1};var s2=Ue.zeroHash="\0\0\0\0\0\0\0\0";Ue.fromNumber=function(e){if(e===0)return Jr;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Ue(n,i)};Ue.from=function(e){if(typeof e=="number")return Ue.fromNumber(e);if(Oi.isString(e))if(Oi.Long)e=Oi.Long.fromString(e);else return Ue.fromNumber(parseInt(e,10));return e.low||e.high?new Ue(e.low>>>0,e.high>>>0):Jr};Ue.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};Ue.prototype.toLong=function(e){return Oi.Long?new Oi.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Rr=String.prototype.charCodeAt;Ue.fromHash=function(e){return e===s2?Jr:new Ue((Rr.call(e,0)|Rr.call(e,1)<<8|Rr.call(e,2)<<16|Rr.call(e,3)<<24)>>>0,(Rr.call(e,4)|Rr.call(e,5)<<8|Rr.call(e,6)<<16|Rr.call(e,7)<<24)>>>0)};Ue.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)};Ue.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};Ue.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};Ue.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var en=R(Rc=>{"use strict";var O=Rc;O.asPromise=rh();O.base64=oh();O.EventEmitter=ch();O.float=mh();O.inquire=yh();O.utf8=xh();O.pool=vh();O.LongBits=bh();O.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);O.global=O.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Rc;O.emptyArray=Object.freeze?Object.freeze([]):[];O.emptyObject=Object.freeze?Object.freeze({}):{};O.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};O.isString=function(e){return typeof e=="string"||e instanceof String};O.isObject=function(e){return e&&typeof e=="object"};O.isset=O.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};O.Buffer=function(){try{var t=O.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();O._Buffer_from=null;O._Buffer_allocUnsafe=null;O.newBuffer=function(e){return typeof e=="number"?O.Buffer?O._Buffer_allocUnsafe(e):new O.Array(e):O.Buffer?O._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};O.Array=typeof Uint8Array<"u"?Uint8Array:Array;O.Long=O.global.dcodeIO&&O.global.dcodeIO.Long||O.global.Long||O.inquire("long");O.key2Re=/^true|false|0|1$/;O.key32Re=/^-?(?:0|[1-9][0-9]*)$/;O.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;O.longToHash=function(e){return e?O.LongBits.from(e).toHash():O.LongBits.zeroHash};O.longFromHash=function(e,r){var n=O.LongBits.fromHash(e);return O.Long?O.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function _h(t,e,r){for(var n=Object.keys(e),i=0;i<n.length;++i)(t[n[i]]===void 0||!r)&&(t[n[i]]=e[n[i]]);return t}O.merge=_h;O.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Sh(t){function e(r,n){if(!(this instanceof e))return new e(r,n);Object.defineProperty(this,"message",{get:function(){return r}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&_h(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}O.newError=Sh;O.ProtocolError=Sh("ProtocolError");O.oneOfGetter=function(e){for(var r={},n=0;n<e.length;++n)r[e[n]]=1;return function(){for(var i=Object.keys(this),s=i.length-1;s>-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};O.oneOfSetter=function(e){return function(r){for(var n=0;n<e.length;++n)e[n]!==r&&delete this[e[n]]}};O.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};O._configure=function(){var t=O.Buffer;if(!t){O._Buffer_from=O._Buffer_allocUnsafe=null;return}O._Buffer_from=t.from!==Uint8Array.from&&t.from||function(r,n){return new t(r,n)},O._Buffer_allocUnsafe=t.allocUnsafe||function(r){return new t(r)}}});var Bc=R((lA,Th)=>{"use strict";Th.exports=Te;var zt=en(),Tc,Rh=zt.LongBits,o2=zt.utf8;function It(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Te(t){this.buf=t,this.pos=0,this.len=t.length}var Ah=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Te(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Te(e);throw Error("illegal buffer")},Ch=function(){return zt.Buffer?function(r){return(Te.create=function(i){return zt.Buffer.isBuffer(i)?new Tc(i):Ah(i)})(r)}:Ah};Te.create=Ch();Te.prototype._slice=zt.Array.prototype.subarray||zt.Array.prototype.slice;Te.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,It(this,10);return e}}();Te.prototype.int32=function(){return this.uint32()|0};Te.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Cc(){var t=new Rh(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw It(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw It(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Te.prototype.bool=function(){return this.uint32()!==0};function eo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Te.prototype.fixed32=function(){if(this.pos+4>this.len)throw It(this,4);return eo(this.buf,this.pos+=4)};Te.prototype.sfixed32=function(){if(this.pos+4>this.len)throw It(this,4);return eo(this.buf,this.pos+=4)|0};function Ih(){if(this.pos+8>this.len)throw It(this,8);return new Rh(eo(this.buf,this.pos+=4),eo(this.buf,this.pos+=4))}Te.prototype.float=function(){if(this.pos+4>this.len)throw It(this,4);var e=zt.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Te.prototype.double=function(){if(this.pos+8>this.len)throw It(this,4);var e=zt.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Te.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw It(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};Te.prototype.string=function(){var e=this.bytes();return o2.read(e,0,e.length)};Te.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw It(this,e);this.pos+=e}else do if(this.pos>=this.len)throw It(this);while(this.buf[this.pos++]&128);return this};Te.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Te._configure=function(t){Tc=t,Te.create=Ch(),Tc._configure();var e=zt.Long?"toLong":"toNumber";zt.merge(Te.prototype,{int64:function(){return Cc.call(this)[e](!1)},uint64:function(){return Cc.call(this)[e](!0)},sint64:function(){return Cc.call(this).zzDecode()[e](!1)},fixed64:function(){return Ih.call(this)[e](!0)},sfixed64:function(){return Ih.call(this)[e](!1)}})}});var Dh=R((fA,Ph)=>{"use strict";Ph.exports=tn;var Lh=Bc();(tn.prototype=Object.create(Lh.prototype)).constructor=tn;var Bh=en();function tn(t){Lh.call(this,t)}tn._configure=function(){Bh.Buffer&&(tn.prototype._slice=Bh.Buffer.prototype.slice)};tn.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};tn._configure()});var Mc=R((hA,Mh)=>{"use strict";Mh.exports=ee;var xt=en(),Lc,to=xt.LongBits,Nh=xt.base64,kh=xt.utf8;function Mi(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function Dc(){}function a2(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function ee(){this.len=0,this.head=new Mi(Dc,0,0),this.tail=this.head,this.states=null}var Oh=function(){return xt.Buffer?function(){return(ee.create=function(){return new Lc})()}:function(){return new ee}};ee.create=Oh();ee.alloc=function(e){return new xt.Array(e)};xt.Array!==Array&&(ee.alloc=xt.pool(ee.alloc,xt.Array.prototype.subarray));ee.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Mi(e,r,n),this.len+=r,this};function Nc(t,e,r){e[r]=t&255}function c2(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function kc(t,e){this.len=t,this.next=void 0,this.val=e}kc.prototype=Object.create(Mi.prototype);kc.prototype.fn=c2;ee.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new kc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};ee.prototype.int32=function(e){return e<0?this._push(Oc,10,to.fromNumber(e)):this.uint32(e)};ee.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Oc(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}ee.prototype.uint64=function(e){var r=to.from(e);return this._push(Oc,r.length(),r)};ee.prototype.int64=ee.prototype.uint64;ee.prototype.sint64=function(e){var r=to.from(e).zzEncode();return this._push(Oc,r.length(),r)};ee.prototype.bool=function(e){return this._push(Nc,1,e?1:0)};function Pc(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}ee.prototype.fixed32=function(e){return this._push(Pc,4,e>>>0)};ee.prototype.sfixed32=ee.prototype.fixed32;ee.prototype.fixed64=function(e){var r=to.from(e);return this._push(Pc,4,r.lo)._push(Pc,4,r.hi)};ee.prototype.sfixed64=ee.prototype.fixed64;ee.prototype.float=function(e){return this._push(xt.float.writeFloatLE,4,e)};ee.prototype.double=function(e){return this._push(xt.float.writeDoubleLE,8,e)};var u2=xt.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i<e.length;++i)r[n+i]=e[i]};ee.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(Nc,1,0);if(xt.isString(e)){var n=ee.alloc(r=Nh.length(e));Nh.decode(e,n,0),e=n}return this.uint32(r)._push(u2,r,e)};ee.prototype.string=function(e){var r=kh.length(e);return r?this.uint32(r)._push(kh.write,r,e):this._push(Nc,1,0)};ee.prototype.fork=function(){return this.states=new a2(this),this.head=this.tail=new Mi(Dc,0,0),this.len=0,this};ee.prototype.reset=function(){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 Mi(Dc,0,0),this.len=0),this};ee.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};ee.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};ee._configure=function(t){Lc=t,ee.create=Oh(),Lc._configure()}});var Kh=R((dA,Uh)=>{"use strict";Uh.exports=Ht;var Fh=Mc();(Ht.prototype=Object.create(Fh.prototype)).constructor=Ht;var Cr=en();function Ht(){Fh.call(this)}Ht._configure=function(){Ht.alloc=Cr._Buffer_allocUnsafe,Ht.writeBytesBuffer=Cr.Buffer&&Cr.Buffer.prototype instanceof Uint8Array&&Cr.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i<e.length;)r[n++]=e[i++]}};Ht.prototype.bytes=function(e){Cr.isString(e)&&(e=Cr._Buffer_from(e,"base64"));var r=e.length>>>0;return this.uint32(r),r&&this._push(Ht.writeBytesBuffer,r,e),this};function l2(t,e,r){t.length<40?Cr.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ht.prototype.string=function(e){var r=Cr.Buffer.byteLength(e);return this.uint32(r),r&&this._push(l2,r,e),this};Ht._configure()});var ed=R((dI,Jh)=>{var pe=se();$r();Ie();var Ui=Jh.exports=pe.sha512=pe.sha512||{};pe.md.sha512=pe.md.algorithms.sha512=Ui;var Zh=pe.sha384=pe.sha512.sha384=pe.sha512.sha384||{};Zh.create=function(){return Ui.create("SHA-384")};pe.md.sha384=pe.md.algorithms.sha384=Zh;pe.sha512.sha256=pe.sha512.sha256||{create:function(){return Ui.create("SHA-512/256")}};pe.md["sha512/256"]=pe.md.algorithms["sha512/256"]=pe.sha512.sha256;pe.sha512.sha224=pe.sha512.sha224||{create:function(){return Ui.create("SHA-512/224")}};pe.md["sha512/224"]=pe.md.algorithms["sha512/224"]=pe.sha512.sha224;Ui.create=function(t){if(jh||w2(),typeof t>"u"&&(t="SHA-512"),!(t in nn))throw new Error("Invalid SHA-512 algorithm: "+t);for(var e=nn[t],r=null,n=pe.util.createBuffer(),i=new Array(80),s=0;s<80;++s)i[s]=new Array(2);var o=64;switch(t){case"SHA-384":o=48;break;case"SHA-512/256":o=32;break;case"SHA-512/224":o=28;break}var a={algorithm:t.replace("-","").toLowerCase(),blockLength:128,digestLength:o,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u<c;++u)a.fullMessageLength.push(0);n=pe.util.createBuffer(),r=new Array(e.length);for(var u=0;u<e.length;++u)r[u]=e[u].slice(0);return a},a.start(),a.update=function(c,u){u==="utf8"&&(c=pe.util.encodeUtf8(c));var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),Xh(r,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=pe.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(Hc.substr(0,a.blockLength-l));for(var f,h,d=a.fullMessageLength[0]*8,p=0;p<a.fullMessageLength.length-1;++p)f=a.fullMessageLength[p+1]*8,h=f/4294967296>>>0,d+=h,c.putInt32(d>>>0),d=f>>>0;c.putInt32(d);for(var m=new Array(r.length),p=0;p<r.length;++p)m[p]=r[p].slice(0);Xh(m,i,c);var y=pe.util.createBuffer(),g;t==="SHA-512"?g=m.length:t==="SHA-384"?g=m.length-2:g=m.length-4;for(var p=0;p<g;++p)y.putInt32(m[p][0]),(p!==g-1||t!=="SHA-512/224")&&y.putInt32(m[p][1]);return y},a};var Hc=null,jh=!1,Gc=null,nn=null;function w2(){Hc=String.fromCharCode(128),Hc+=pe.util.fillString(String.fromCharCode(0),128),Gc=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],nn={},nn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],nn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],nn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],nn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],jh=!0}function Xh(t,e,r){for(var n,i,s,o,a,c,u,l,f,h,d,p,m,y,g,w,_,N,C,T,H,W,De,Et,it,We,_n,bs,Le,Je,F,ba,_a,Sa,Aa,Gl=r.length();Gl>=128;){for(Le=0;Le<16;++Le)e[Le][0]=r.getInt32()>>>0,e[Le][1]=r.getInt32()>>>0;for(;Le<80;++Le)ba=e[Le-2],Je=ba[0],F=ba[1],n=((Je>>>19|F<<13)^(F>>>29|Je<<3)^Je>>>6)>>>0,i=((Je<<13|F>>>19)^(F<<3|Je>>>29)^(Je<<26|F>>>6))>>>0,Sa=e[Le-15],Je=Sa[0],F=Sa[1],s=((Je>>>1|F<<31)^(Je>>>8|F<<24)^Je>>>7)>>>0,o=((Je<<31|F>>>1)^(Je<<24|F>>>8)^(Je<<25|F>>>7))>>>0,_a=e[Le-7],Aa=e[Le-16],F=i+_a[1]+o+Aa[1],e[Le][0]=n+_a[0]+s+Aa[0]+(F/4294967296>>>0)>>>0,e[Le][1]=F>>>0;for(m=t[0][0],y=t[0][1],g=t[1][0],w=t[1][1],_=t[2][0],N=t[2][1],C=t[3][0],T=t[3][1],H=t[4][0],W=t[4][1],De=t[5][0],Et=t[5][1],it=t[6][0],We=t[6][1],_n=t[7][0],bs=t[7][1],Le=0;Le<80;++Le)u=((H>>>14|W<<18)^(H>>>18|W<<14)^(W>>>9|H<<23))>>>0,l=((H<<18|W>>>14)^(H<<14|W>>>18)^(W<<23|H>>>9))>>>0,f=(it^H&(De^it))>>>0,h=(We^W&(Et^We))>>>0,a=((m>>>28|y<<4)^(y>>>2|m<<30)^(y>>>7|m<<25))>>>0,c=((m<<4|y>>>28)^(y<<30|m>>>2)^(y<<25|m>>>7))>>>0,d=(m&g|_&(m^g))>>>0,p=(y&w|N&(y^w))>>>0,F=bs+l+h+Gc[Le][1]+e[Le][1],n=_n+u+f+Gc[Le][0]+e[Le][0]+(F/4294967296>>>0)>>>0,i=F>>>0,F=c+p,s=a+d+(F/4294967296>>>0)>>>0,o=F>>>0,_n=it,bs=We,it=De,We=Et,De=H,Et=W,F=T+i,H=C+n+(F/4294967296>>>0)>>>0,W=F>>>0,C=_,T=N,_=g,N=w,g=m,w=y,F=i+o,m=n+s+(F/4294967296>>>0)>>>0,y=F>>>0;F=t[0][1]+y,t[0][0]=t[0][0]+m+(F/4294967296>>>0)>>>0,t[0][1]=F>>>0,F=t[1][1]+w,t[1][0]=t[1][0]+g+(F/4294967296>>>0)>>>0,t[1][1]=F>>>0,F=t[2][1]+N,t[2][0]=t[2][0]+_+(F/4294967296>>>0)>>>0,t[2][1]=F>>>0,F=t[3][1]+T,t[3][0]=t[3][0]+C+(F/4294967296>>>0)>>>0,t[3][1]=F>>>0,F=t[4][1]+W,t[4][0]=t[4][0]+H+(F/4294967296>>>0)>>>0,t[4][1]=F>>>0,F=t[5][1]+Et,t[5][0]=t[5][0]+De+(F/4294967296>>>0)>>>0,t[5][1]=F>>>0,F=t[6][1]+We,t[6][0]=t[6][0]+it+(F/4294967296>>>0)>>>0,t[6][1]=F>>>0,F=t[7][1]+bs,t[7][0]=t[7][0]+_n+(F/4294967296>>>0)>>>0,t[7][1]=F>>>0,Gl-=128}}});var hu=R((iR,Pd)=>{var Gn=1e3,Yn=Gn*60,Wn=Yn*60,un=Wn*24,X2=un*7,Z2=un*365.25;Pd.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return j2(t);if(r==="number"&&isFinite(t))return e.long?ev(t):J2(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function j2(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Z2;case"weeks":case"week":case"w":return r*X2;case"days":case"day":case"d":return r*un;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Wn;case"minutes":case"minute":case"mins":case"min":case"m":return r*Yn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Gn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function J2(t){var e=Math.abs(t);return e>=un?Math.round(t/un)+"d":e>=Wn?Math.round(t/Wn)+"h":e>=Yn?Math.round(t/Yn)+"m":e>=Gn?Math.round(t/Gn)+"s":t+"ms"}function ev(t){var e=Math.abs(t);return e>=un?po(t,e,un,"day"):e>=Wn?po(t,e,Wn,"hour"):e>=Yn?po(t,e,Yn,"minute"):e>=Gn?po(t,e,Gn,"second"):t+" ms"}function po(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var Nd=R((sR,Dd)=>{function tv(t){r.debug=r,r.default=r,r.coerce=c,r.disable=s,r.enable=i,r.enabled=o,r.humanize=hu(),r.destroy=u,Object.keys(t).forEach(l=>{r[l]=t[l]}),r.names=[],r.skips=[],r.formatters={};function e(l){let f=0;for(let h=0;h<l.length;h++)f=(f<<5)-f+l.charCodeAt(h),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(l){let f,h=null,d,p;function m(...y){if(!m.enabled)return;let g=m,w=Number(new Date),_=w-(f||w);g.diff=_,g.prev=f,g.curr=w,f=w,y[0]=r.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let N=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,H)=>{if(T==="%%")return"%";N++;let W=r.formatters[H];if(typeof W=="function"){let De=y[N];T=W.call(g,De),y.splice(N,1),N--}return T}),r.formatArgs.call(g,y),(g.log||r.log).apply(g,y)}return m.namespace=l,m.useColors=r.useColors(),m.color=r.selectColor(l),m.extend=n,m.destroy=r.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==r.namespaces&&(d=r.namespaces,p=r.enabled(l)),p),set:y=>{h=y}}),typeof r.init=="function"&&r.init(m),m}function n(l,f){let h=r(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f<d;f++)h[f]&&(l=h[f].replace(/\*/g,".*?"),l[0]==="-"?r.skips.push(new RegExp("^"+l.slice(1)+"$")):r.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=r.skips.length;f<h;f++)if(r.skips[f].test(l))return!1;for(f=0,h=r.names.length;f<h;f++)if(r.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Dd.exports=tv});var du=R((ct,mo)=>{ct.formatArgs=nv;ct.save=iv;ct.load=sv;ct.useColors=rv;ct.storage=ov();ct.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ct.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 rv(){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 nv(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+mo.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}ct.log=console.debug||console.log||(()=>{});function iv(t){try{t?ct.storage.setItem("debug",t):ct.storage.removeItem("debug")}catch{}}function sv(){let t;try{t=ct.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function ov(){try{return localStorage}catch{}}mo.exports=Nd()(ct);var{formatters:av}=mo.exports;av.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Od=R((lR,kd)=>{"use strict";function uv(t){return t>=55296&&t<=56319}function lv(t){return t>=56320&&t<=57343}kd.exports=function(e,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var i=r.length,s=0,o,a,c=0;c<i;c+=1){if(o=r.charCodeAt(c),a=r[c],uv(o)&&lv(r.charCodeAt(c+1))&&(c+=1,a+=r[c]),s+=e(a),s===n)return r.slice(0,c+1);if(s>n)return r.slice(0,c-a.length+1)}return r}});var Fd=R((fR,Md)=>{"use strict";function fv(t){return t>=55296&&t<=56319}function hv(t){return t>=56320&&t<=57343}Md.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var r=e.length,n=0,i=null,s=null,o=0;o<r;o++)i=e.charCodeAt(o),hv(i)?s!=null&&fv(s)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var Kd=R((hR,Ud)=>{"use strict";var dv=Od(),pv=Fd();Ud.exports=dv.bind(null,pv)});var $d=R((dR,qd)=>{"use strict";var mv=Kd(),yv=/[\/\?<>\\:\*\|"]/g,gv=/[\x00-\x1f\x80-\x9f]/g,xv=/^\.+$/,wv=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,vv=/[\. ]+$/;function Vd(t,e){if(typeof t!="string")throw new Error("Input must be string");var r=t.replace(yv,e).replace(gv,e).replace(xv,e).replace(wv,e).replace(vv,e);return mv(r,255)}qd.exports=function(t,e){var r=e&&e.replacement||"",n=Vd(t,r);return r===""?n:Vd(n,"")}});var Hd=R((pR,zd)=>{"use strict";zd.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Zd=R((Qd,Xd)=>{"use strict";var yo=Hd(),{hasOwnProperty:Yd}=Object.prototype,{propertyIsEnumerable:Ev}=Object,Qn=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),bv=Qd,Gd={concatArrays:!1,ignoreUndefined:!1},go=t=>{let e=[];for(let r in t)Yd.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)Ev.call(t,n)&&e.push(n)}return e};function Xn(t){return Array.isArray(t)?_v(t):yo(t)?Sv(t):t}function _v(t){let e=t.slice(0,0);return go(t).forEach(r=>{Qn(e,r,Xn(t[r]))}),e}function Sv(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return go(t).forEach(r=>{Qn(e,r,Xn(t[r]))}),e}var Wd=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?Qn(t,i,pu(t[i],e[i],n)):Qn(t,i,Xn(e[i])))}),t),Av=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)Yd.call(s,a)&&(o.push(String(a)),s===t?Qn(n,i++,s[a]):Qn(n,i++,Xn(s[a])));n=Wd(n,s,go(s).filter(a=>!o.includes(a)),r)}),n};function pu(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?Av(t,e,r):!yo(e)||!yo(t)?Xn(e):Wd(t,e,go(e),r)}Xd.exports=function(...t){let e=pu(Xn(Gd),this!==bv&&this||{},Gd),r={_:{}};for(let n of t)if(n!==void 0){if(!yo(n))throw new TypeError("`"+n+"` is not an Option Object");r=pu(r,{_:n},e)}return r._}});var yp=R((Y4,mp)=>{mp.exports=vu;var pp=128,Gv=127,Yv=~Gv,Wv=Math.pow(2,31);function vu(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw vu.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=Wv;)e[r++]=t&255|pp,t/=128;for(;t&Yv;)e[r++]=t&255|pp,t>>>=7;return e[r]=t|0,vu.bytes=r-n+1,e}});var wp=R((W4,xp)=>{xp.exports=Eu;var Qv=128,gp=127;function Eu(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a||i>49)throw Eu.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&gp)<<i:(o&gp)*Math.pow(2,i),i+=7}while(o>=Qv);return Eu.bytes=s-n,r}});var Ep=R((Q4,vp)=>{var Xv=Math.pow(2,7),Zv=Math.pow(2,14),jv=Math.pow(2,21),Jv=Math.pow(2,28),eE=Math.pow(2,35),tE=Math.pow(2,42),rE=Math.pow(2,49),nE=Math.pow(2,56),iE=Math.pow(2,63);vp.exports=function(t){return t<Xv?1:t<Zv?2:t<jv?3:t<Jv?4:t<eE?5:t<tE?6:t<rE?7:t<nE?8:t<iE?9:10}});var So=R((X4,bp)=>{bp.exports={encode:yp(),decode:wp(),encodingLength:Ep()}});var zp=R((ST,ku)=>{"use strict";var BE=Object.prototype.hasOwnProperty,je="~";function ts(){}Object.create&&(ts.prototype=Object.create(null),new ts().__proto__||(je=!1));function LE(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function $p(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new LE(r,n||t,i),o=je?je+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function Bo(t,e){--t._eventsCount===0?t._events=new ts:delete t._events[e]}function Ge(){this._events=new ts,this._eventsCount=0}Ge.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)BE.call(r,n)&&e.push(je?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Ge.prototype.listeners=function(e){var r=je?je+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Ge.prototype.listenerCount=function(e){var r=je?je+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Ge.prototype.emit=function(e,r,n,i,s,o){var a=je?je+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var h=c.length,d;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,r);break;case 3:c[f].fn.call(c[f].context,r,n);break;case 4:c[f].fn.call(c[f].context,r,n,i);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[f].fn.apply(c[f].context,l)}}return!0};Ge.prototype.on=function(e,r,n){return $p(this,e,r,n,!1)};Ge.prototype.once=function(e,r,n){return $p(this,e,r,n,!0)};Ge.prototype.removeListener=function(e,r,n,i){var s=je?je+e:e;if(!this._events[s])return this;if(!r)return Bo(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&Bo(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:Bo(this,s)}return this};Ge.prototype.removeAllListeners=function(e){var r;return e?(r=je?je+e:e,this._events[r]&&Bo(this,r)):(this._events=new ts,this._eventsCount=0),this};Ge.prototype.off=Ge.prototype.removeListener;Ge.prototype.addListener=Ge.prototype.on;Ge.prefixed=je;Ge.EventEmitter=Ge;typeof ku<"u"&&(ku.exports=Ge)});var il=R((U8,lm)=>{"use strict";function um(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function GE(t,e,r){if(!t||typeof t=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof e=="object"&&(r=e,e=""),e&&(r.code=e);try{return um(t,r)}catch{r.message=t.message,r.stack=t.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(t)),um(new i,r)}}lm.exports=GE});var ym=R(us=>{(function(){var t,e,r,n,i,s,o,a;a=function(c){var u,l,f,h;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,h=c&255,[u,l,f,h].join(".")},o=function(c){var u,l,f,h,d,p;for(u=[],f=h=0;h<=3&&c.length!==0;f=++h){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],l=p[1],c=c.substring(l),u.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},r=function(c){return c.charCodeAt(0)},n=r("0"),s=r("a"),i=r("A"),e=function(c){var u,l,f,h,d;for(h=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),d=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)h=h*u+(r(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")h=h*u+(10+r(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")h=h*u+(10+r(c[f])-i)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[h,f]},t=function(){function c(u,l){var f,h,d,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(m){throw f=m,new Error("Invalid mask: "+l)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,h;for(h=o(this.first),f=o(this.last),l=0;h<=f;)u(a(h),h,l),l++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),us.ip2long=o,us.long2ip=a,us.Netmask=t}).call(us)});var vm=R((wm,Xo)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let m=0,y=-1,g=(d.match(a.zoneIndex)||[])[0],w,_;for(g&&(g=g.substring(1),d=d.replace(/%.+$/,""));(y=d.indexOf(":",y+1))>=0;)m++;if(d.substr(0,2)==="::"&&m--,d.substr(-2,2)==="::"&&m--,m>p)return null;for(_=p-m,w=":";_--;)w+="0:";return d=d.replace("::",w),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let N=d.split(":"),C=[];for(let T=0;T<N.length;T++)C.push(parseInt(N[T],16));return C}(),{parts:p,zoneId:g}}function u(d,p,m,y){if(d.length!==p.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let g=0,w;for(;y>0;){if(w=m-y,w<0&&(w=0),d[g]>>w!==p[g]>>w)return!1;y-=m,g+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length<p;)d=`0${d}`;return d}let h={};h.IPv4=function(){function d(p){if(p.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let m,y;for(m=0;m<p.length;m++)if(y=p[m],!(0<=y&&y<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=p}return d.prototype.SpecialRanges={unspecified:[[new d([0,0,0,0]),8]],broadcast:[[new d([255,255,255,255]),32]],multicast:[[new d([224,0,0,0]),4]],linkLocal:[[new d([169,254,0,0]),16]],loopback:[[new d([127,0,0,0]),8]],carrierGradeNat:[[new d([100,64,0,0]),10]],private:[[new d([10,0,0,0]),8],[new d([172,16,0,0]),12],[new d([192,168,0,0]),16]],reserved:[[new d([192,0,0,0]),24],[new d([192,0,2,0]),24],[new d([192,88,99,0]),24],[new d([198,18,0,0]),15],[new d([198,51,100,0]),24],[new d([203,0,113,0]),24],[new d([240,0,0,0]),4]]},d.prototype.kind=function(){return"ipv4"},d.prototype.match=function(p,m){let y;if(m===void 0&&(y=p,p=y[0],m=y[1]),p.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,p.octets,8,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,y={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},g,w,_;for(g=3;g>=0;g-=1)if(w=this.octets[g],w in y){if(_=y[w],m&&_!==0)return null;_!==8&&(m=!0),p+=_}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),y=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],w=0;for(;w<4;)g.push(parseInt(m[w],10)|parseInt(y[w],10)^255),w++;return new this(g)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,m,y,g,w;try{for(p=this.parseCIDR(d),y=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],m=0;m<4;)g.push(parseInt(y[m],10)&parseInt(w[m],10)),m++;return new this(g)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let m=parseInt(p[2]);if(m>=0&&m<=32){let y=[this.parse(p[1]),m];return Object.defineProperty(y,"toString",{value:function(){return this.join("/")}}),y}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,m,y;if(p=d.match(r.fourOctet))return function(){let g=p.slice(1,6),w=[];for(let _=0;_<g.length;_++)m=g[_],w.push(l(m));return w}();if(p=d.match(r.longValue)){if(y=l(p[1]),y>4294967295||y<0)throw new Error("ipaddr: address outside defined range");return function(){let g=[],w;for(w=0;w<=24;w+=8)g.push(y>>w&255);return g}().reverse()}else return(p=d.match(r.twoOctet))?function(){let g=p.slice(1,4),w=[];if(y=l(g[1]),y>16777215||y<0)throw new Error("ipaddr: address outside defined range");return w.push(l(g[0])),w.push(y>>16&255),w.push(y>>8&255),w.push(y&255),w}():(p=d.match(r.threeOctet))?function(){let g=p.slice(1,5),w=[];if(y=l(g[2]),y>65535||y<0)throw new Error("ipaddr: address outside defined range");return w.push(l(g[0])),w.push(l(g[1])),w.push(y>>8&255),w.push(y&255),w}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],m=0,y=Math.floor(d/8);for(;m<y;)p[m]=255,m++;return y<4&&(p[y]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},h.IPv6=function(){function d(p,m){let y,g;if(p.length===16)for(this.parts=[],y=0;y<=14;y+=2)this.parts.push(p[y]<<8|p[y+1]);else if(p.length===8)this.parts=p;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(y=0;y<this.parts.length;y++)if(g=this.parts[y],!(0<=g&&g<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");m&&(this.zoneId=m)}return d.prototype.SpecialRanges={unspecified:[new d([0,0,0,0,0,0,0,0]),128],linkLocal:[new d([65152,0,0,0,0,0,0,0]),10],multicast:[new d([65280,0,0,0,0,0,0,0]),8],loopback:[new d([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new d([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new d([0,0,0,0,0,65535,0,0]),96],rfc6145:[new d([0,0,0,0,65535,0,0,0]),96],rfc6052:[new d([100,65435,0,0,0,0,0,0]),96],"6to4":[new d([8194,0,0,0,0,0,0,0]),16],teredo:[new d([8193,0,0,0,0,0,0,0]),32],reserved:[[new d([8193,3512,0,0,0,0,0,0]),32]],benchmarking:[new d([8193,2,0,0,0,0,0,0]),48],amt:[new d([8193,3,0,0,0,0,0,0]),32],as112v6:[new d([8193,4,274,0,0,0,0,0]),48],deprecated:[new d([8193,16,0,0,0,0,0,0]),28],orchid2:[new d([8193,32,0,0,0,0,0,0]),28]},d.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},d.prototype.kind=function(){return"ipv6"},d.prototype.match=function(p,m){let y;if(m===void 0&&(y=p,p=y[0],m=y[1]),p.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,p.parts,16,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,y={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},g,w;for(let _=7;_>=0;_-=1)if(g=this.parts[_],g in y){if(w=y[g],m&&w!==0)return null;w!==16&&(m=!0),p+=w}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,m=[],y=this.parts;for(let g=0;g<y.length;g++)p=y[g],m.push(p>>8),m.push(p&255);return m},d.prototype.toFixedLengthString=function(){let p=function(){let y=[];for(let g=0;g<this.parts.length;g++)y.push(f(this.parts[g].toString(16),4));return y}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let p=this.parts.slice(-2),m=p[0],y=p[1];return new h.IPv4([m>>8,m&255,y>>8,y&255])},d.prototype.toNormalizedString=function(){let p=function(){let y=[];for(let g=0;g<this.parts.length;g++)y.push(this.parts[g].toString(16));return y}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toRFC5952String=function(){let p=/((^|:)(0(:|$)){2,})/g,m=this.toNormalizedString(),y=0,g=-1,w;for(;w=p.exec(m);)w[0].length>g&&(y=w.index,g=w[0].length);return g<0?m:`${m.substring(0,y)}::${m.substring(y+g)}`},d.prototype.toString=function(){return this.toRFC5952String()},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),y=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],w=0;for(;w<16;)g.push(parseInt(m[w],10)|parseInt(y[w],10)^255),w++;return new this(g)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,m,y,g,w;try{for(p=this.parseCIDR(d),y=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),g=[],m=0;m<16;)g.push(parseInt(y[m],10)&parseInt(w[m],10)),m++;return new this(g)}catch(_){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${_})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,m,y;if((m=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(m[2]),p>=0&&p<=128))return y=[this.parse(m[1]),p],Object.defineProperty(y,"toString",{value:function(){return this.join("/")}}),y;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,m,y,g,w,_;if(y=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${y[1]}`);if(a.native.test(d))return c(d,8);if((y=d.match(a.transitional))&&(_=y[6]||"",p=c(y[1].slice(0,-1)+_,6),p.parts)){for(w=[parseInt(y[2]),parseInt(y[3]),parseInt(y[4]),parseInt(y[5])],m=0;m<w.length;m++)if(g=w[m],!(0<=g&&g<=255))return null;return p.parts.push(w[0]<<8|w[1]),p.parts.push(w[2]<<8|w[3]),{parts:p.parts,zoneId:p.zoneId}}return null},h.IPv6.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=0,y=Math.floor(d/8);for(;m<y;)p[m]=255,m++;return y<16&&(p[y]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},h.fromByteArray=function(d){let p=d.length;if(p===4)return new h.IPv4(d);if(p===16)return new h.IPv6(d);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},h.isValid=function(d){return h.IPv6.isValid(d)||h.IPv4.isValid(d)},h.parse=function(d){if(h.IPv6.isValid(d))return h.IPv6.parse(d);if(h.IPv4.isValid(d))return h.IPv4.parse(d);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},h.parseCIDR=function(d){try{return h.IPv6.parseCIDR(d)}catch{try{return h.IPv4.parseCIDR(d)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},h.process=function(d){let p=this.parse(d);return p.kind()==="ipv6"&&p.isIPv4MappedAddress()?p.toIPv4Address():p},h.subnetMatch=function(d,p,m){let y,g,w,_;m==null&&(m="unicast");for(g in p)if(Object.prototype.hasOwnProperty.call(p,g)){for(w=p[g],w[0]&&!(w[0]instanceof Array)&&(w=[w]),y=0;y<w.length;y++)if(_=w[y],d.kind()===_[0].kind()&&d.match.apply(d,_))return g}return m},typeof Xo<"u"&&Xo.exports?Xo.exports=h:t.ipaddr=h})(wm)});var Cm=R((p3,Rm)=>{"use strict";Rm.exports=Im;var ob=hu(),Kr=Im.prototype,ab=new Date%1e9;function cb(){return(Math.random()*1e9>>>0)+ab++}function Im(t){t=t||{},this.id=t.id||cb(),this.max=t.max||1/0,this.items=t.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(t.lastModified||new Date);for(var e,r,n=this.items.length;n--;)e=this.items[n],r=new Date(e.expires)-new Date,this._lookup[e.key]=e,r>0?this.expire(e.key,r):r<=0&&this.delete(e.key)}Kr.has=function(t){return t in this._lookup};Kr.get=function(t){if(!this.has(t))return null;var e=this._lookup[t];return e.refresh&&this.expire(t,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};Kr.meta=function(t){if(!this.has(t))return null;var e=this._lookup[t];return"meta"in e?e.meta:null};Kr.set=function(t,e,r){var n=this._lookup[t],i=this._lookup[t]={key:t,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),r&&("ttl"in r&&this.expire(t,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};Kr.delete=function(t){var e=this._lookup[t];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[t],this.size--,this):!1};Kr.expire=function(t,e){var r=e||0,n=this._lookup[t];if(!n)return this;if(typeof r=="string"&&(r=ob(e)),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};Kr.clear=function(){for(var t=this.items.length;t--;)this.delete(this.items[t].key);return this};Kr.toJSON=function(){for(var t=new Array(this.items.length),e,r=t.length;r--;)e=this.items[r],t[r]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:t}}});var ls=R((k3,Om)=>{Om.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.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'!")}}});var Fm=R((M3,Mm)=>{Mm.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(r=>{this._keys[r]<=e&&delete this._keys[r]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,r){this.addMs(e,r*1e3)}addMs(e,r){this._keys[e]=Date.now()+r,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let r=this._keys[e];if(r&&r>=Date.now()){this.collectExpired();let n=Date.now();return r>=n?r-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(r=>{delete this._keys[r]})}}});var Km=R((F3,Um)=>{var hb=Fm();Um.exports=hb});var pt=R((K3,Vm)=>{Vm.exports=class{constructor(e,r,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_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()}}});var fi=R((q3,$m)=>{var dl=ls(),db=Km(),qm=pt();$m.exports=class extends dl{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new db}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,r,n,i,s,o={}){let a=this._getRateLimiterRes(n,i,s);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?r(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{r(a)}).catch(u=>{r(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,r,n,i,s,o=!1,a={}){this.insuranceLimiter instanceof dl?this.insuranceLimiter[r](s,o,a).then(c=>{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):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(e){if(this._inMemoryBlockDuration=e?parseInt(e):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(e){if(typeof e<"u"&&!(e instanceof dl))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,r,n={}){let i=r*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,r,n,i={}){let s=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),r,s,i)}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return s(new qm(0,a));this._upsert(o,r,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,s,o,r,c)}).catch(c=>{this._handleError(c,"consume",i,s,e,r,n)})})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,r,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,r,a))}).catch(a=>{this._handleError(a,"penalty",s,o,e,r,n)})})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,-r,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,-r,a))}).catch(a=>{this._handleError(a,"reward",s,o,e,r,n)})})}get(e,r={}){let n=this.getKey(e);return new Promise((i,s)=>{this._get(n,r).then(o=>{i(o===null||typeof o>"u"?null:this._getRateLimiterRes(n,0,o))}).catch(o=>{this._handleError(o,"get",i,s,e,r)})})}delete(e,r={}){let n=this.getKey(e);return new Promise((i,s)=>{this._delete(n,r).then(o=>{this._inMemoryBlockedKeys.delete(n),i(o)}).catch(o=>{this._handleError(o,"delete",i,s,e,r)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,r,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,r,n,i={}){return new Promise((s,o)=>{this._upsert(e,r,n,!0,i).then(()=>{s(new qm(0,n>0?n:-1,r))}).catch(a=>{this._handleError(a,"block",s,o,this.parseKey(e),n/1e3,i)})})}_get(e,r={}){throw new Error("You have to implement the method '_get'!")}_delete(e,r={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,r,n,i=!1,s={}){throw new Error("You have to implement the method '_upsert'!")}}});var Gm=R(($3,Hm)=>{var pb=fi(),mb=pt(),zm="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} ",pl=class extends pb{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:zm})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,r,n){let[i,s]=n;Array.isArray(i)&&([,i]=i,[,s]=s);let o=new mb;return o.consumedPoints=parseInt(i),o.isFirstInDuration=o.consumedPoints===r,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=s,o}_upsert(e,r,n,i=!1){return new Promise((s,o)=>{if(!this._isRedisReady())return o(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,r,"EX",a):c.set(e,r),c.pttl(e).exec((u,l)=>u?o(u):s(l));else if(a>0){let u=function(l,f){return l?o(l):s(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,r,a,u):this.client.eval(zm,1,e,r,a,u)}else c.incrby(e,r).pttl(e).exec((u,l)=>u?o(u):s(l))})}_get(e){return new Promise((r,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,s)=>{if(i)n(i);else{let[o]=s;if(o===null)return r(null);r(s)}})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,s)=>{i?n(i):r(s>0)})})}};Hm.exports=pl});var Qm=R((z3,Wm)=>{var yb=fi(),gb=pt();function Ym(t){try{let e=t.client?t.client:t,{version:r}=e.topology.s.options.metadata.driver,n=r.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var fs=class extends yb{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(r=>{this.client=r,this._initCollection(),this._driverVersion=Ym(this.client)}):(this._initCollection(),this._driverVersion=Ym(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?fs.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let 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(e,r,n){let i=new gb,s;return typeof n.value>"u"?s=n:s=n.value,i.isFirstInDuration=s.points===r,i.consumedPoints=s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire!==null?Math.max(new Date(s.expire).getTime()-Date.now(),0):-1,i}_upsert(e,r,n,i=!1,s={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=s.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:r,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:r}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),p={$set:Object.assign({key:e,points:r,expire:n>0?new Date(Date.now()+n):null},o)};this._collection.findOneAndUpdate(d,p,u).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,r,n,i).then(y=>l(y)).catch(y=>f(y)):f(m)})}else f(h)})})}_get(e,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=r.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,r={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=r.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(s=>s.deletedCount>0)}};Wm.exports=fs});var Zm=R((H3,Xm)=>{var xb=fi(),wb=pt(),ml=class extends xb{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.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(e){return new Promise(r=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{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((e,r)=>{this.client.getConnection((n,i)=>{if(n)return r(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,r)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),r(i);n.query(this._getCreateTableStmt(),s=>{if(s)return this._releaseConnection(n),r(s);this._releaseConnection(n),e()})})}).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(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,r,n){let i=new wb,[s]=n;return i.isFirstInDuration=r===s.points,i.consumedPoints=i.isFirstInDuration?r:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_upsertTransaction(e,r,n,i,s){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;s?(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
16
16
  ON DUPLICATE KEY UPDATE
17
17
  points = ?,
18
18
  expire = ?;`,h=[this.dbName,this.tableName,r,n,l,n,l]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
19
19
  ON DUPLICATE KEY UPDATE
20
20
  points = IF(expire <= ?, ?, points + (?)),
21
- expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,r,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,r],(p,m)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",y=>{if(y)return e.rollback(),a(y);o(m)})})})})})}_upsert(e,r,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,r,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(s,o)=>{s?n(s):o.length===0?r(null):r(o),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(s,o)=>{s?n(s):r(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Xm.exports=ml});var Jm=R((G3,jm)=>{var vb=fi(),Eb=dt(),yl=class extends vb{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof r=="function"&&r():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}clearExpired(e){return new Promise(r=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{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 Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,r)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} (
21
+ expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,r,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,r],(p,m)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",y=>{if(y)return e.rollback(),a(y);o(m)})})})})})}_upsert(e,r,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,r,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(s,o)=>{s?n(s):o.length===0?r(null):r(o),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(s,o)=>{s?n(s):r(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Xm.exports=ml});var Jm=R((G3,jm)=>{var vb=fi(),Eb=pt(),yl=class extends vb{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof r=="function"&&r():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}clearExpired(e){return new Promise(r=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{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 Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,r)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} (
22
22
  key varchar(255) PRIMARY KEY,
23
23
  points integer NOT NULL DEFAULT 0,
24
24
  expire bigint
@@ -34,7 +34,7 @@
34
34
  END,
35
35
  expire = ${o}
36
36
  RETURNING points, expire;`,values:[e,r,s,Date.now()]})}_get(e){return this.tableCreated?new Promise((r,n)=>{this._query({name:"rlflx-get",text:`
37
- SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),r(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}};jm.exports=yl});var ey=R(()=>{});var ry=R((X3,ty)=>{ty.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var iy=R((j3,ny)=>{var bb=ry(),gl=dt();ny.exports=class{constructor(){this._storage={}}incrby(e,r,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+r,new gl(0,i,this._storage[e].value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new bb(r,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new gl(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let r=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new gl(0,r,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var wl=R((J3,oy)=>{var _b=ls(),Sb=iy(),sy=dt(),xl=class extends _b{constructor(e={}){super(e),this._memoryStorage=new Sb}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(o,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(i,u,c)}else i(c)})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,r,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-r,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,r),Promise.resolve(new sy(0,n===0?-1:n,i))}set(e,r,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new sy(0,i===0?-1:i,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};oy.exports=xl});var dy=R((eB,hy)=>{var ay=ey(),Ab=zr(),Ib=ls(),uy=wl(),Rb=dt(),vt="rate_limiter_flexible",pi=null,cy=function(t,e,r,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},t.send({channel:vt,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:r,data:i})},ly=function(t){setTimeout(()=>{this._initiated?process.send(t):typeof this._promises[t.promiseId]<"u"&&ly.call(this,t)},30)},hi=function(t,e,r,n,i){let s={channel:vt,keyPrefix:this.keyPrefix,func:t,promiseId:e,data:{key:r,arg:n,opts:i}};this._initiated?process.send(s):ly.call(this,s)},fy=function(t,e){if(!e||e.channel!==vt||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let r;switch(e.func){case"consume":r=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":r=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":r=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":r=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":r=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":r=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}r&&r.then(n=>{cy(t,e,"resolve",n)}).catch(n=>{cy(t,e,"reject",n)})},Cb=function(t){if(!t||t.channel!==vt||t.keyPrefix!==this.keyPrefix)return!1;if(this._promises[t.promiseId]){clearTimeout(this._promises[t.promiseId].timeoutId);let e;switch(t.data===null||t.data===!0||t.data===!1?e=t.data:e=new Rb(t.data.remainingPoints,t.data.msBeforeNext,t.data.consumedPoints,t.data.isFirstInDuration),t.type){case"resolve":this._promises[t.promiseId].resolve(e);break;case"reject":this._promises[t.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${t.type}'`)}delete this._promises[t.promiseId]}},Tb=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},di=function(t,e){let r=process.hrtime(),n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=Ab.randomBytes(12).toString("base64")),this._promises[n]={resolve:t,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},vl=class{constructor(){if(pi)return pi;this._rateLimiters={},ay.setMaxListeners(0),ay.on("message",(e,r)=>{r&&r.channel===vt&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new uy(r.opts)),e.send({channel:vt,type:"init",keyPrefix:r.opts.keyPrefix})):fy.call(this,e,r)}),pi=this}},El=class{constructor(e){if(pi)return pi;this._rateLimiters={},e.launchBus((r,n)=>{n.on("process:msg",i=>{let s=i.raw;if(s&&s.channel===vt&&s.type==="init")typeof this._rateLimiters[s.opts.keyPrefix]>"u"&&(this._rateLimiters[s.opts.keyPrefix]=new uy(s.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:vt,channel:vt,type:"init",keyPrefix:s.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=vt,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};fy.call(this,o,s)}})}),pi=this}},bl=class extends Ib{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===vt&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:Cb.call(this,r)}),process.send({channel:vt,type:"init",opts:Tb.call(this)}),this._promises={}}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"consume",o,e,r,n)})}penalty(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"penalty",o,e,r,n)})}reward(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"reward",o,e,r,n)})}block(e,r,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"block",o,e,r,n)})}get(e,r={}){return new Promise((n,i)=>{let s=di.call(this,n,i);hi.call(this,"get",s,e,r)})}delete(e,r={}){return new Promise((n,i)=>{let s=di.call(this,n,i);hi.call(this,"delete",s,e,r)})}};hy.exports={RateLimiterClusterMaster:vl,RateLimiterClusterMasterPM2:El,RateLimiterCluster:bl}});var my=R((tB,py)=>{var Bb=fi(),Lb=dt(),_l=class extends Bb{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,r,n){let i=new Lb;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===r,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,r,n,i=!1,s={}){return new Promise((o,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,r,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};o(f)})}):this.client.incr(e,r,(l,f)=>{l||f===!1?this.client.add(e,r,u,(h,d)=>{if(h||!d)if(typeof s.attemptNumber>"u"||s.attemptNumber<3){let p=Object.assign({},s);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,r,n,i,p).then(m=>o(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};o(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,m={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};o(m)}})})})}_get(e){return new Promise((r,n)=>{let i=Date.now();this.client.get(e,(s,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:o,msBeforeNext:u>=0?Math.max(u-i,0):-1};r(l)}}):r(null)})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,s)=>{i?n(i):s===!1?r(s):this.client.del(`${e}_expire`,o=>{o?n(o):r(s)})})})}};py.exports=_l});var xy=R((nB,gy)=>{var yy=dt();gy.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new yy(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new yy(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(e,r=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,r):(this.runActionAnyway&&this.limiter.consume(e,r).catch(()=>{}),n)}block(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,r):(this.runActionAnyway&&this.limiter.block(e,r).catch(()=>{}),n)}penalty(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,r):(this.runActionAnyway&&this.limiter.penalty(e,r).catch(()=>{}),n)}reward(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,r):(this.runActionAnyway&&this.limiter.reward(e,r).catch(()=>{}),n)}get(e){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(e):r}delete(e){return this.limiter.delete(e)}}});var vy=R((sB,wy)=>{var Pb=ls();wy.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(r=>{if(!(r instanceof Pb))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,r=1){return new Promise((n,i)=>{let s=[];this._limiters.forEach(o=>{s.push(o.consume(e,r).catch(a=>({rejected:!0,rej:a})))}),Promise.all(s).then(o=>{let a={},c=!1;o.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u<o.length;u++)c&&o[u].rejected===!0?a[this._limiters[u].keyPrefix]=o[u].rej:c||(a[this._limiters[u].keyPrefix]=o[u]);c?i(a):n(a)})})}}});var by=R((aB,Ey)=>{Ey.exports=class extends Error{constructor(e,r){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,r&&(this.extra=r)}}});var Iy=R((uB,Ay)=>{var _y=by(),Sy=4294967295,Sl="limiter";Ay.exports=class{constructor(e,r={maxQueueSize:Sy}){this._queueLimiters={KEY_DEFAULT:new Jo(e,r)},this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(e=Sl){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,r=Sl){return this._queueLimiters[r]||(this._queueLimiters[r]=new Jo(this._limiterFlexible,{key:r,maxQueueSize:this._maxQueueSize})),this._queueLimiters[r].removeTokens(e)}};var Jo=class{constructor(e,r={maxQueueSize:Sy,key:Sl}){this._key=r.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let r=this;return new Promise((n,i)=>{if(e>r._limiterFlexible.points){i(new _y(`Requested tokens ${e} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,i,e):r._limiterFlexible.consume(r._key,e).then(s=>{n(s.remainingPoints)}).catch(s=>{s instanceof Error?i(s):(r._queueRequest.call(r,n,i,e),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),s.msBeforeNext)))})})}_queueRequest(e,r,n){let i=this;i._queue.length<i._maxQueueSize?i._queue.push({resolve:e,reject:r,tokens:n}):r(new _y(`Number of requests reached it's maximum ${i._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let r=e._queue.shift();e._limiterFlexible.consume(e._key,r.tokens).then(n=>{r.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(r.reject(n),e._processFIFO.call(e)):(e._queue.unshift(r),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var Cy=R((fB,Ry)=>{var Al=dt();Ry.exports=class{constructor(e,r){this._rateLimiter=e,this._burstLimiter=r}_combineRes(e,r){return new Al(e.remainingPoints,Math.min(e.msBeforeNext,r.msBeforeNext),e.consumedPoints,e.isFirstInDuration)}consume(e,r=1,n={}){return this._rateLimiter.consume(e,r,n).catch(i=>i instanceof Al?this._burstLimiter.consume(e,r,n).then(s=>Promise.resolve(this._combineRes(i,s))).catch(s=>s instanceof Al?Promise.reject(this._combineRes(i,s)):Promise.reject(s)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}}});var By=R((hB,Ty)=>{var Db=Gm(),Nb=Qm(),kb=Zm(),Ob=Jm(),{RateLimiterClusterMaster:Mb,RateLimiterClusterMasterPM2:Fb,RateLimiterCluster:Ub}=dy(),Kb=wl(),Vb=my(),qb=xy(),$b=vy(),zb=Iy(),Hb=Cy(),Gb=dt();Ty.exports={RateLimiterRedis:Db,RateLimiterMongo:Nb,RateLimiterMySQL:kb,RateLimiterPostgres:Ob,RateLimiterMemory:Kb,RateLimiterMemcache:Vb,RateLimiterClusterMaster:Mb,RateLimiterClusterMasterPM2:Fb,RateLimiterCluster:Ub,RLWrapperBlackAndWhite:qb,RateLimiterUnion:$b,RateLimiterQueue:zb,BurstyRateLimiter:Hb,RateLimiterRes:Gb}});var A_={};Ke(A_,{createLibp2p:()=>S_});var Qy=V(bi(),1);var YI=V(Ii(),1),WI=V(w0(),1);var $s=class extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=$s.code,this.type=$s.type}},xr=$s;Ia(xr,"code","ABORT_ERR"),Ia(xr,"type","aborted");var E=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var fo=V(se(),1);var ec={};Ke(ec,{identity:()=>Ux});function Nx(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,g=0,w=p.length;g!==w&&p[g]===0;)g++,m++;for(var _=(w-g)*l+1>>>0,N=new Uint8Array(_);g!==w;){for(var C=p[g],T=0,H=_-1;(C!==0||T<y)&&H!==-1;H--,T++)C+=256*N[H]>>>0,N[H]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");y=T,g++}for(var W=_-y;W!==_&&N[W]===0;)W++;for(var De=c.repeat(m);W<_;++W)De+=t.charAt(N[W]);return De}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,g=0;p[m]===c;)y++,m++;for(var w=(p.length-m)*u+1>>>0,_=new Uint8Array(w);p[m];){var N=r[p.charCodeAt(m)];if(N===255)return;for(var C=0,T=w-1;(N!==0||C<g)&&T!==-1;T--,C++)N+=a*_[T]>>>0,_[T]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");g=C,m++}if(p[m]!==" "){for(var H=w-g;H!==w&&_[H]===0;)H++;for(var W=new Uint8Array(y+(w-H)),De=y;H!==w;)W[De++]=_[H++];return W}}}function d(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var kx=Nx,Ox=kx,v0=Ox;var rS=new Uint8Array(0);var E0=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},rr=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var b0=t=>new TextEncoder().encode(t),_0=t=>new TextDecoder().decode(t);var Xa=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Za=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return A0(this,e)}},ja=class{constructor(e){this.decoders=e}or(e){return A0(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},A0=(t,e)=>new ja({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Ja=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Xa(e,r,n),this.decoder=new Za(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Tn=({name:t,prefix:e,encode:r,decode:n})=>new Ja(t,e,r,n),wr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=v0(r,e);return Tn({prefix:t,name:e,encode:n,decode:s=>rr(i(s))})},Mx=(t,e,r,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Fx=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},be=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Tn({prefix:e,name:t,encode(i){return Fx(i,n,r)},decode(i){return Mx(i,n,r,t)}});var Ux=Tn({prefix:"\0",name:"identity",encode:t=>_0(t),decode:t=>b0(t)});var tc={};Ke(tc,{base2:()=>Kx});var Kx=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rc={};Ke(rc,{base8:()=>Vx});var Vx=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nc={};Ke(nc,{base10:()=>qx});var qx=wr({prefix:"9",name:"base10",alphabet:"0123456789"});var ic={};Ke(ic,{base16:()=>$x,base16upper:()=>zx});var $x=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zx=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sc={};Ke(sc,{base32:()=>st,base32hex:()=>Wx,base32hexpad:()=>Xx,base32hexpadupper:()=>Zx,base32hexupper:()=>Qx,base32pad:()=>Gx,base32padupper:()=>Yx,base32upper:()=>Hx,base32z:()=>jx});var st=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hx=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gx=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yx=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wx=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qx=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xx=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zx=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jx=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var oc={};Ke(oc,{base36:()=>Jx,base36upper:()=>ew});var Jx=wr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ew=wr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ac={};Ke(ac,{base58btc:()=>Re,base58flickr:()=>tw});var Re=wr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tw=wr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cc={};Ke(cc,{base64:()=>Wr,base64pad:()=>rw,base64url:()=>nw,base64urlpad:()=>iw});var Wr=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rw=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nw=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iw=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uc={};Ke(uc,{base256emoji:()=>uw});var I0=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}"),sw=I0.reduce((t,e,r)=>(t[r]=e,t),[]),ow=I0.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aw(t){return t.reduce((e,r)=>(e+=sw[r],e),"")}function cw(t){let e=[];for(let r of t){let n=ow[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var uw=Tn({prefix:"\u{1F680}",name:"base256emoji",encode:aw,decode:cw});var dc={};Ke(dc,{sha256:()=>Ve,sha512:()=>Cw});var lw=T0,R0=128,fw=127,hw=~fw,dw=Math.pow(2,31);function T0(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dw;)e[r++]=t&255|R0,t/=128;for(;t&hw;)e[r++]=t&255|R0,t>>>=7;return e[r]=t|0,T0.bytes=r-n+1,e}var pw=lc,mw=128,C0=127;function lc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw lc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&C0)<<i:(o&C0)*Math.pow(2,i),i+=7}while(o>=mw);return lc.bytes=s-n,r}var yw=Math.pow(2,7),gw=Math.pow(2,14),xw=Math.pow(2,21),ww=Math.pow(2,28),vw=Math.pow(2,35),Ew=Math.pow(2,42),bw=Math.pow(2,49),_w=Math.pow(2,56),Sw=Math.pow(2,63),Aw=function(t){return t<yw?1:t<gw?2:t<xw?3:t<ww?4:t<vw?5:t<Ew?6:t<bw?7:t<_w?8:t<Sw?9:10},Iw={encode:lw,decode:pw,encodingLength:Aw},Rw=Iw,Ti=Rw;var Bi=(t,e=0)=>[Ti.decode(t,e),Ti.decode.bytes],Bn=(t,e,r=0)=>(Ti.encode(t,e,r),e),Ln=t=>Ti.encodingLength(t);var qt=(t,e)=>{let r=e.byteLength,n=Ln(t),i=n+Ln(r),s=new Uint8Array(i+r);return Bn(t,s,0),Bn(r,s,n),s.set(e,i),new Pn(t,r,e,s)},Qr=t=>{let e=rr(t),[r,n]=Bi(e),[i,s]=Bi(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Pn(r,i,o,e)},B0=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&E0(t.bytes,r.bytes)}},Pn=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var hc=({name:t,code:e,encode:r})=>new fc(t,e,r),fc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?qt(this.code,r):r.then(n=>qt(this.code,n))}else throw Error("Unknown type, must be binary type")}};var P0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Ve=hc({name:"sha2-256",code:18,encode:P0("SHA-256")}),Cw=hc({name:"sha2-512",code:19,encode:P0("SHA-512")});var pc={};Ke(pc,{identity:()=>vr});var D0=0,Tw="identity",N0=rr,Bw=t=>qt(D0,N0(t)),vr={code:D0,name:Tw,encode:N0,digest:Bw};var _S=new TextEncoder,SS=new TextDecoder;var k0=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Nw(r,mc(t),e||Re.encoder);default:return kw(r,mc(t),e||st.encoder)}};var O0=new WeakMap,mc=t=>{let e=O0.get(t);if(e==null){let r=new Map;return O0.set(t,r),r}return e},ue=class{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:r}=this;if(e!==Li)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Ow)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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:{let{code:e,digest:r}=this.multihash,n=qt(e,r);return ue.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(e){return ue.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&B0(e.multihash,n.multihash)}toString(e){return k0(this,e)}toJSON(){return{"/":k0(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof ue)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:s,bytes:o}=r;return new ue(n,i,s,o||M0(n,i,s.bytes))}else if(r[Mw]===!0){let{version:n,multihash:i,code:s}=r,o=Qr(i);return ue.create(n,s,o)}else return null}static create(e,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(e){case 0:{if(r!==Li)throw new Error(`Version 0 CID must use dag-pb (code: ${Li}) block encoding`);return new ue(e,r,n,n.bytes)}case 1:{let i=M0(e,r,n.bytes);return new ue(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Li,e)}static createV1(e,r){return ue.create(1,e,r)}static decode(e){let[r,n]=ue.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=ue.inspectBytes(e),n=r.size-r.multihashSize,i=rr(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new Pn(r.multihashCode,r.digestSize,s,i);return[r.version===0?ue.createV0(o):ue.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=Bi(e.subarray(r));return r+=h,f},i=n(),s=Li;if(i===18?(i=0,r=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),c=n(),u=r+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,i]=Dw(e,r),s=ue.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return mc(s).set(n,e),s}},Dw=(t,e)=>{switch(t[0]){case"Q":{let r=e||Re;return[Re.prefix,r.decode(`${Re.prefix}${t}`)]}case Re.prefix:{let r=e||Re;return[Re.prefix,r.decode(t)]}case st.prefix:{let r=e||st;return[st.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Nw=(t,e,r)=>{let{prefix:n}=r;if(n!==Re.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},kw=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},Li=112,Ow=18,M0=(t,e,r)=>{let n=Ln(t),i=n+Ln(e),s=new Uint8Array(i+r.byteLength);return Bn(t,s,0),Bn(e,s,n),s.set(r,i),s},Mw=Symbol.for("@ipld/js-cid/CID");var Er={...ec,...tc,...rc,...nc,...ic,...sc,...oc,...ac,...cc,...uc},NS={...dc,...pc};function Zr(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function nr(t=0){return globalThis.Buffer?.alloc!=null?Zr(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function St(t=0){return globalThis.Buffer?.allocUnsafe!=null?Zr(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function U0(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var F0=U0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),yc=U0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=St(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Fw={utf8:F0,"utf-8":F0,hex:Er.base16,latin1:yc,ascii:yc,binary:yc,...Er},Hs=Fw;function U(t,e="utf8"){let r=Hs[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zr(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var zc={};Ke(zc,{Ed25519PrivateKey:()=>rn,Ed25519PublicKey:()=>Fi,generateKeyPair:()=>y2,generateKeyPairFromSeed:()=>Hh,unmarshalEd25519PrivateKey:()=>p2,unmarshalEd25519PublicKey:()=>m2});function ve(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var Uw=V(zr(),1);var Fe=BigInt(0),X=BigInt(1),Sr=BigInt(2),Kw=BigInt(8),K0=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),de=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:K0,n:K0,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var H0=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Pi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GS=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),Vw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),qw=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),$w=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),zw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Y=class{constructor(e,r,n,i){this.x=e,this.y=r,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof ge))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(ge.ZERO)?Y.ZERO:new Y(e.x,e.y,X,A(e.x*e.y))}static toAffineBatch(e){let r=Yw(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){q0(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=A(r*a),u=A(s*i),l=A(n*a),f=A(o*i);return c===u&&l===f}negate(){return new Y(A(-this.x),this.y,this.z,A(-this.t))}double(){let{x:e,y:r,z:n}=this,{a:i}=de,s=A(e*e),o=A(r*r),a=A(Sr*A(n*n)),c=A(i*s),u=e+r,l=A(A(u*u)-s-o),f=c+o,h=f-a,d=c-o,p=A(l*h),m=A(f*d),y=A(l*d),g=A(h*f);return new Y(p,m,g,y)}add(e){q0(e);let{x:r,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=A((n-r)*(a+o)),f=A((n+r)*(a-o)),h=A(f-l);if(h===Fe)return this.double();let d=A(i*Sr*u),p=A(s*Sr*c),m=p+d,y=f+l,g=p-d,w=A(m*h),_=A(y*g),N=A(m*g),C=A(h*y);return new Y(w,_,C,N)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let r=1+256/e,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(Y.BASE)&&(r=ge.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&Ec.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=Y.normalizeZ(i),Ec.set(r,i)));let s=Y.ZERO,o=Y.BASE,a=1+256/n,c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);e>>=f,p>c&&(p-=l,e+=X);let m=d,y=d+Math.abs(p)-1,g=h%2!==0,w=p<0;p===0?o=o.add(V0(g,i[m])):s=s.add(V0(w,i[y]))}return Y.normalizeZ([s,o])[0]}multiply(e,r){return this.wNAF(Ys(e,de.l),r)}multiplyUnsafe(e){let r=Ys(e,de.l,!1),n=Y.BASE,i=Y.ZERO;if(r===Fe)return i;if(this.equals(i)||r===X)return this;if(this.equals(n))return this.wNAF(r);let s=i,o=this;for(;r>Fe;)r&X&&(s=s.add(o)),o=o.double(),r>>=X;return s}isSmallOrder(){return this.multiplyUnsafe(de.h).equals(Y.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(de.l/Sr).double();return de.l%Sr&&(e=e.add(this)),e.equals(Y.ZERO)}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(Y.ZERO);e==null&&(e=s?Kw:Ws(i));let o=A(r*e),a=A(n*e),c=A(i*e);if(s)return ge.ZERO;if(c!==X)throw new Error("invZ was invalid");return new ge(o,a)}fromRistrettoBytes(){xc()}toRistrettoBytes(){xc()}fromRistrettoHash(){xc()}};Y.BASE=new Y(de.Gx,de.Gy,X,A(de.Gx*de.Gy));Y.ZERO=new Y(Fe,X,X,Fe);function V0(t,e){let r=e.negate();return t?r:e}function q0(t){if(!(t instanceof Y))throw new TypeError("ExtendedPoint expected")}function gc(t){if(!(t instanceof tt))throw new TypeError("RistrettoPoint expected")}function xc(){throw new Error("Legacy method: switch to RistrettoPoint")}var tt=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:r}=de,n=A(Pi*e*e),i=A((n+X)*$w),s=BigInt(-1),o=A((s-r*n)*A(n+r)),{isValid:a,value:c}=_c(i,o),u=A(c*e);_r(u)||(u=A(-u)),a||(c=u),a||(s=n);let l=A(s*(n-X)*zw-o),f=c*c,h=A((c+c)*o),d=A(l*Vw),p=A(X-f),m=A(X+f);return new Y(A(h*m),A(p*d),A(d*m),A(h*p))}static hashToCurve(e){e=Ar(e,64);let r=wc(e.slice(0,32)),n=this.calcElligatorRistrettoMap(r),i=wc(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new tt(n.add(s))}static fromHex(e){e=Ar(e,32);let{a:r,d:n}=de,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=wc(e);if(!Qw(Di(s),e)||_r(s))throw new Error(i);let o=A(s*s),a=A(X+r*o),c=A(X-r*o),u=A(a*a),l=A(c*c),f=A(r*n*u-l),{isValid:h,value:d}=z0(A(f*l)),p=A(d*c),m=A(d*p*f),y=A((s+s)*p);_r(y)&&(y=A(-y));let g=A(a*m),w=A(y*g);if(!h||_r(w)||g===Fe)throw new Error(i);return new tt(new Y(y,g,X,w))}toRawBytes(){let{x:e,y:r,z:n,t:i}=this.ep,s=A(A(n+r)*A(n-r)),o=A(e*r),a=A(o*o),{value:c}=z0(A(s*a)),u=A(c*s),l=A(c*o),f=A(u*l*i),h;if(_r(i*f)){let p=A(r*Pi),m=A(e*Pi);e=p,r=m,h=A(u*qw)}else h=l;_r(e*f)&&(r=A(-r));let d=A((n-r)*h);return _r(d)&&(d=A(-d)),Di(d)}toHex(){return Ni(this.toRawBytes())}toString(){return this.toHex()}equals(e){gc(e);let r=this.ep,n=e.ep,i=A(r.x*n.y)===A(r.y*n.x),s=A(r.y*n.y)===A(r.x*n.x);return i||s}add(e){return gc(e),new tt(this.ep.add(e.ep))}subtract(e){return gc(e),new tt(this.ep.subtract(e.ep))}multiply(e){return new tt(this.ep.multiply(e))}multiplyUnsafe(e){return new tt(this.ep.multiplyUnsafe(e))}};tt.BASE=new tt(Y.BASE);tt.ZERO=new tt(Y.ZERO);var Ec=new WeakMap,ge=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Ec.delete(this)}static fromHex(e,r=!0){let{d:n,P:i}=de;e=Ar(e,32);let s=e.slice();s[31]=e[31]&-129;let o=ki(s);if(r&&o>=i)throw new Error("Expected 0 < hex < P");if(!r&&o>=H0)throw new Error("Expected 0 < hex < 2**256");let a=A(o*o),c=A(a-X),u=A(n*a+X),{isValid:l,value:f}=_c(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&X)===X;return(e[31]&128)!==0!==h&&(f=A(-f)),new ge(f,o)}static async fromPrivateKey(e){return(await Qs(e)).point}toRawBytes(){let e=Di(this.y);return e[31]|=this.x&X?128:0,e}toHex(){return Ni(this.toRawBytes())}toX25519(){let{y:e}=this,r=A((X+e)*Ws(X-e));return Di(r)}isTorsionFree(){return Y.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new ge(A(-this.x),this.y)}add(e){return Y.fromAffine(this).add(Y.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Y.fromAffine(this).multiply(e,this).toAffine()}};ge.BASE=new ge(de.Gx,de.Gy);ge.ZERO=new ge(Fe,X);var jr=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=Ar(e,64),n=ge.fromHex(r.slice(0,32),!1),i=ki(r.slice(32,64));return new jr(n,i)}assertValidity(){let{r:e,s:r}=this;if(!(e instanceof ge))throw new Error("Expected Point instance");return Ys(r,de.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Di(this.s),32),e}toHex(){return Ni(this.toRawBytes())}};function $0(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var Hw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ni(t){if(!(t instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Hw[t[r]];return e}function bc(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function G0(t){let r=t.toString(16).padStart(64,"0");return bc(r)}function Di(t){return G0(t).reverse()}function _r(t){return(A(t)&X)===X}function ki(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+Ni(Uint8Array.from(t).reverse()))}var Gw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function wc(t){return A(ki(t)&Gw)}function A(t,e=de.P){let r=t%e;return r>=Fe?r:e+r}function Ws(t,e=de.P){if(t===Fe||e<=Fe)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=A(t,e),n=e,i=Fe,s=X,o=X,a=Fe;for(;r!==Fe;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==X)throw new Error("invert: does not exist");return A(i,e)}function Yw(t,e=de.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===Fe?s:(r[a]=s,A(s*o,e)),X),i=Ws(n,e);return t.reduceRight((s,o,a)=>o===Fe?s:(r[a]=A(s*r[a],e),A(s*o,e)),i),r}function $t(t,e){let{P:r}=de,n=t;for(;e-- >Fe;)n*=n,n%=r;return n}function Ww(t){let{P:e}=de,r=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=t*t%e*t%e,u=$t(c,Sr)*c%e,l=$t(u,X)*t%e,f=$t(l,r)*l%e,h=$t(f,n)*f%e,d=$t(h,i)*h%e,p=$t(d,s)*d%e,m=$t(p,o)*p%e,y=$t(m,o)*p%e,g=$t(y,n)*f%e;return{pow_p_5_8:$t(g,Sr)*t%e,b2:c}}function _c(t,e){let r=A(e*e*e),n=A(r*r*e),i=Ww(t*n).pow_p_5_8,s=A(t*r*i),o=A(e*s*s),a=s,c=A(s*Pi),u=o===t,l=o===A(-t),f=o===A(-t*Pi);return u&&(s=a),(l||f)&&(s=c),_r(s)&&(s=A(-s)),{isValid:u||l,value:s}}function z0(t){return _c(X,t)}function Gs(t){return A(ki(t),de.l)}function Qw(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Ar(t,e){let r=t instanceof Uint8Array?Uint8Array.from(t):bc(t);if(typeof e=="number"&&r.length!==e)throw new Error(`Expected ${e} bytes`);return r}function Ys(t,e,r=!0){if(!e)throw new TypeError("Specify max value");if(typeof t=="number"&&Number.isSafeInteger(t)&&(t=BigInt(t)),typeof t=="bigint"&&t<e){if(r){if(Fe<t)return t}else if(Fe<=t)return t}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function Xw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Zw(t){if(t=typeof t=="bigint"||typeof t=="number"?G0(Ys(t,H0)):Ar(t),t.length!==32)throw new Error("Expected 32 bytes");return t}function jw(t){let e=Xw(t.slice(0,32)),r=t.slice(32,64),n=Gs(e),i=ge.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:r,scalar:n,point:i,pointBytes:s}}var vc;async function Qs(t){return jw(await Ir.sha512(Zw(t)))}async function Sc(t){return(await Qs(t)).pointBytes}async function Y0(t,e){t=Ar(t);let{prefix:r,scalar:n,pointBytes:i}=await Qs(e),s=Gs(await Ir.sha512(r,t)),o=ge.BASE.multiply(s),a=Gs(await Ir.sha512(o.toRawBytes(),i,t)),c=A(s+a*n,de.l);return new jr(o,c).toRawBytes()}function Jw(t,e,r){e=Ar(e),r instanceof ge||(r=ge.fromHex(r,!1));let{r:n,s:i}=t instanceof jr?t.assertValidity():jr.fromHex(t),s=Y.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:r,msg:e}}function e2(t,e,r,n){let i=Gs(n),s=Y.fromAffine(t).multiplyUnsafe(i);return Y.fromAffine(e).add(s).subtract(r).multiplyUnsafe(de.h).equals(Y.ZERO)}async function W0(t,e,r){let{r:n,SB:i,msg:s,pub:o}=Jw(t,e,r),a=await Ir.sha512(n.toRawBytes(),o.toRawBytes(),s);return e2(o,n,i,a)}ge.BASE._setWindowSize(8);var br={node:Uw,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Ir={bytesToHex:Ni,hexToBytes:bc,concatBytes:$0,getExtendedPublicKey:Qs,mod:A,invert:Ws,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:t=>{if(t=Ar(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return A(ki(t),de.l-X)+X},randomBytes:(t=32)=>{if(br.web)return br.web.getRandomValues(new Uint8Array(t));if(br.node){let{randomBytes:e}=br.node;return new Uint8Array(e(t).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ir.randomBytes(32),sha512:async(...t)=>{let e=$0(...t);if(br.web){let r=await br.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(r)}else{if(br.node)return Uint8Array.from(br.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(t=8,e=ge.BASE){let r=e.equals(ge.BASE)?e:new ge(e.x,e.y);return r._setWindowSize(t),r.multiply(Sr),r},sha512Sync:void 0};Object.defineProperties(Ir,{sha512Sync:{configurable:!1,get(){return vc},set(t){vc||(vc=t)}}});var Dn=32,ir=64,Xs=32;async function Q0(){let t=Ir.randomPrivateKey(),e=await Sc(t);return{privateKey:J0(t,e),publicKey:e}}async function X0(t){if(t.length!==Xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=await Sc(e);return{privateKey:J0(e,r),publicKey:r}}async function Z0(t,e){let r=t.subarray(0,Xs);return Y0(e,r)}async function j0(t,e,r){return W0(e,r,t)}function J0(t,e){let r=new Uint8Array(ir);for(let n=0;n<Xs;n++)r[n]=t[n],r[Xs+n]=e[n];return r}function Ce(t,e){e==null&&(e=t.reduce((i,s)=>i+s.length,0));let r=St(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Zr(r)}var rt={get(t=globalThis){let e=t.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Ac={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Zs(t){let e=t?.algorithm??"AES-GCM",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"SHA-256",s=t?.saltLength??16,o=t?.iterations??32767,a=rt.get();r*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof h=="string"&&(h=U(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,_,{name:e,length:r},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,_,{name:e,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,f);return Ce([d,m.iv,new Uint8Array(g)])}async function u(f,h){let d=f.subarray(0,s),p=f.subarray(s,s+n),m=f.subarray(s+n),y={name:e,iv:p};typeof h=="string"&&(h=U(h));let g;if(h.length===0)try{let _={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},N=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(_,N,{name:e,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["decrypt"])}else{let _={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},N=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(_,N,{name:e,length:r},!0,["decrypt"])}let w=await a.subtle.decrypt(y,g,m);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function Nn(t,e){let n=await Zs().encrypt(t,e);return Wr.encode(n)}var Fc=V(Bc(),1),Vh=V(Dh(),1),qh=V(en(),1),Uc=V(Mc(),1),$h=V(Kh(),1);function f2(){qh.default._configure(),Fc.default._configure(Vh.default),Uc.default._configure($h.default)}f2();var zh=["uint64","int64","sint64","fixed64","sfixed64"];function h2(t){for(let e of zh){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function Kc(t){return h2(new Fc.default(t))}function d2(t){for(let e of zh){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function Vc(){return d2(Uc.default.create())}function qe(t,e){let r=Kc(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function $e(t,e){let r=Vc();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var On;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(On||(On={}));function ro(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function qc(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return ro("enum",On.VARINT,r,n)}function ze(t,e){return ro("message",On.LENGTH_DELIMITED,t,e)}var xe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(xe||(xe={}));var $c;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})($c||($c={}));(function(t){t.codec=()=>qc($c)})(xe||(xe={}));var Gt;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),xe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=xe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Gt||(Gt={}));var Yt;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),xe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=xe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Yt||(Yt={}));var Fi=class{_key;constructor(e){this._key=Mn(e,Dn)}async verify(e,r){return j0(this._key,r,e)}marshal(){return this._key}get bytes(){return Gt.encode({Type:xe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},rn=class{_key;_publicKey;constructor(e,r){this._key=Mn(e,ir),this._publicKey=Mn(r,Dn)}async sign(e){return Z0(this._key,e)}get public(){return new Fi(this._publicKey)}marshal(){return this._key}get bytes(){return Yt.encode({Type:xe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=vr.digest(this.public.bytes);return Re.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function p2(t){if(t.length>ir){t=Mn(t,ir+Dn);let n=t.subarray(0,ir),i=t.subarray(ir,t.length);return new rn(n,i)}t=Mn(t,ir);let e=t.subarray(0,ir),r=t.subarray(Dn);return new rn(e,r)}function m2(t){return t=Mn(t,Dn),new Fi(t)}async function y2(){let{privateKey:t,publicKey:e}=await Q0();return new rn(t,e)}async function Hh(t){let{privateKey:e,publicKey:r}=await X0(t);return new rn(e,r)}function Mn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}function $(t,e="utf8"){let r=Hs[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var UA=V(Ie(),1),KA=V(Us(),1),Gh=V(se(),1);function Rt(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Ce([new Uint8Array(e-r.length),r])}return $(r,"base64url")}function ot(t){let e=Yh(t);return new Gh.default.jsbn.BigInteger($(e,"base16"),16)}function Yh(t,e){let r=U(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Ce([new Uint8Array(e-r.length),r])}return r}var g2={"P-256":256,"P-384":384,"P-521":521},x2=Object.keys(g2),ZA=x2.join(" / ");async function Wh(t,e){let r=Wr.decode(t);return Zs().decrypt(r,e)}var tu={};Ke(tu,{RsaPrivateKey:()=>zn,RsaPublicKey:()=>Hi,fromJwk:()=>$2,generateKeyPair:()=>z2,unmarshalRsaPrivateKey:()=>V2,unmarshalRsaPublicKey:()=>q2});var zi=V(se(),1);var kI=V(ed(),1);var v2=V(zr(),1);var Z=BigInt(0),me=BigInt(1),Br=BigInt(2),Vi=BigInt(3),td=BigInt(8),_e=Object.freeze({a:Z,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:me,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),rd=(t,e)=>(t+e/Br)/e,io={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){let{n:e}=_e,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-me*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=rd(s*t,e),c=rd(-n*t,e),u=P(t-a*r-c*i,e),l=P(-a*n-c*s,e),f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}},Ct=32,Kn=32,E2=32,nd=Ct+1,id=2*Ct+1;function sd(t){let{a:e,b:r}=_e,n=P(t*t),i=P(n*t);return P(i+e*t+r)}var so=_e.a===Z,co=class extends Error{constructor(e){super(e)}};function od(t){if(!(t instanceof te))throw new TypeError("JacobianPoint expected")}var te=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof re))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(re.ZERO)?te.ZERO:new te(e.x,e.y,me)}static toAffineBatch(e){let r=I2(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return te.toAffineBatch(e).map(te.fromAffine)}equals(e){od(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=P(i*i),u=P(a*a),l=P(r*u),f=P(s*c),h=P(P(n*a)*u),d=P(P(o*i)*c);return l===f&&h===d}negate(){return new te(this.x,P(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=P(e*e),s=P(r*r),o=P(s*s),a=e+s,c=P(Br*(P(a*a)-i-o)),u=P(Vi*i),l=P(u*u),f=P(l-Br*c),h=P(u*(c-f)-td*o),d=P(Br*r*n);return new te(f,h,d)}add(e){od(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Z||o===Z)return this;if(r===Z||n===Z)return e;let c=P(i*i),u=P(a*a),l=P(r*u),f=P(s*c),h=P(P(n*a)*u),d=P(P(o*i)*c),p=P(f-l),m=P(d-h);if(p===Z)return m===Z?this.double():te.ZERO;let y=P(p*p),g=P(p*y),w=P(l*y),_=P(m*m-g-Br*w),N=P(m*(w-_)-h*g),C=P(i*a*p);return new te(_,N,C)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=te.ZERO;if(typeof e=="bigint"&&e===Z)return r;let n=ud(e);if(n===me)return this;if(!so){let f=r,h=this;for(;n>Z;)n&me&&(f=f.add(h)),h=h.double(),n>>=me;return f}let{k1neg:i,k1:s,k2neg:o,k2:a}=io.splitScalar(n),c=r,u=r,l=this;for(;s>Z||a>Z;)s&me&&(c=c.add(l)),a&me&&(u=u.add(l)),l=l.double(),s>>=me,a>>=me;return i&&(c=c.negate()),o&&(u=u.negate()),u=new te(P(u.x*io.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let r=so?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(te.BASE)&&(r=re.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&Wc.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=te.normalizeZ(i),Wc.set(r,i)));let s=te.ZERO,o=te.BASE,a=1+(so?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);e>>=f,p>c&&(p-=l,e+=me);let m=d,y=d+Math.abs(p)-1,g=h%2!==0,w=p<0;p===0?o=o.add(oo(g,i[m])):s=s.add(oo(w,i[y]))}return{p:s,f:o}}multiply(e,r){let n=ud(e),i,s;if(so){let{k1neg:o,k1:a,k2neg:c,k2:u}=io.splitScalar(n),{p:l,f}=this.wNAF(a,r),{p:h,f:d}=this.wNAF(u,r);l=oo(o,l),h=oo(c,h),h=new te(P(h.x*io.beta),h.y,h.z),i=l.add(h),s=f.add(d)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return te.normalizeZ([i,s])[0]}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(te.ZERO);e==null&&(e=s?td:$n(i));let o=e,a=P(o*o),c=P(a*o),u=P(r*a),l=P(n*c),f=P(i*o);if(s)return re.ZERO;if(f!==me)throw new Error("invZ was invalid");return new re(u,l)}};te.BASE=new te(_e.Gx,_e.Gy,me);te.ZERO=new te(Z,me,Z);function oo(t,e){let r=e.negate();return t?r:e}var Wc=new WeakMap,re=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Wc.delete(this)}hasEvenY(){return this.y%Br===Z}static fromCompressedHex(e){let r=e.length===32,n=Lr(r?e:e.subarray(1));if(!Yc(n))throw new Error("Point is not on curve");let i=sd(n),s=A2(i),o=(s&me)===me;r?o&&(s=P(-s)):(e[0]&1)===1!==o&&(s=P(-s));let a=new re(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=Lr(e.subarray(1,Ct+1)),n=Lr(e.subarray(Ct+1,Ct*2+1)),i=new re(r,n);return i.assertValidity(),i}static fromHex(e){let r=qn(e),n=r.length,i=r[0];if(n===Ct)return this.fromCompressedHex(r);if(n===nd&&(i===2||i===3))return this.fromCompressedHex(r);if(n===id&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-${nd} compressed bytes or ${id} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return re.BASE.multiply(lo(e))}static fromSignature(e,r,n){let{r:i,s}=ld(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=Zc(qn(e)),{n:a}=_e,c=n===2||n===3?i+a:i,u=$n(c,a),l=P(-o*u,a),f=P(s*u,a),h=n&1?"03":"02",d=re.fromHex(h+Fn(c)),p=re.BASE.multiplyAndAddUnsafe(d,l,f);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return sn(this.toHex(e))}toHex(e=!1){let r=Fn(this.x);return e?`${this.hasEvenY()?"02":"03"}${r}`:`04${r}${Fn(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!Yc(r)||!Yc(n))throw new Error(e);let i=P(n*n),s=sd(r);if(P(i-s)!==Z)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new re(this.x,P(-this.y))}double(){return te.fromAffine(this).double().toAffine()}add(e){return te.fromAffine(this).add(te.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return te.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let i=te.fromAffine(this),s=r===Z||r===me||this!==re.BASE?i.multiplyUnsafe(r):i.multiply(r),o=te.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(te.ZERO)?void 0:a.toAffine()}};re.BASE=new re(_e.Gx,_e.Gy);re.ZERO=new re(Z,Z);function ad(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function cd(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${Vn(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Lr(r),left:t.subarray(e+2)}}function b2(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${Vn(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=cd(t.subarray(2)),{data:n,left:i}=cd(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${Vn(i)}`);return{r:e,s:n}}var Wt=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?Vn(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Wt(uo(i.slice(0,64)),uo(i.slice(64,128)))}static fromDER(e){let r=e instanceof Uint8Array;if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=b2(r?e:sn(e));return new Wt(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!$i(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!$i(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=_e.n>>me;return this.s>e}normalizeS(){return this.hasHighS()?new Wt(this.r,P(-this.s,_e.n)):this}toDERRawBytes(){return sn(this.toDERHex())}toDERHex(){let e=ad(Ki(this.s)),r=ad(Ki(this.r)),n=e.length/2,i=r.length/2,s=Ki(n),o=Ki(i);return`30${Ki(i+n+4)}02${o}${r}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return sn(this.toCompactHex())}toCompactHex(){return Fn(this.r)+Fn(this.s)}};function Tr(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var _2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Vn(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;r<t.length;r++)e+=_2[t[r]];return e}var S2=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Fn(t){if(typeof t!="bigint")throw new Error("Expected bigint");if(!(Z<=t&&t<S2))throw new Error("Expected number 0 <= n < 2^256");return t.toString(16).padStart(64,"0")}function Qc(t){let e=sn(Fn(t));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function Ki(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function uo(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function sn(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function Lr(t){return uo(Vn(t))}function qn(t){return t instanceof Uint8Array?Uint8Array.from(t):sn(t)}function ud(t){if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if(typeof t=="bigint"&&$i(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function P(t,e=_e.P){let r=t%e;return r>=Z?r:e+r}function xt(t,e){let{P:r}=_e,n=t;for(;e-- >Z;)n*=n,n%=r;return n}function A2(t){let{P:e}=_e,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,l=xt(u,Vi)*u%e,f=xt(l,Vi)*u%e,h=xt(f,Br)*c%e,d=xt(h,n)*h%e,p=xt(d,i)*d%e,m=xt(p,o)*p%e,y=xt(m,a)*m%e,g=xt(y,o)*p%e,w=xt(g,Vi)*u%e,_=xt(w,s)*d%e,N=xt(_,r)*c%e,C=xt(N,Br);if(C*C%e!==t)throw new Error("Cannot find square root");return C}function $n(t,e=_e.P){if(t===Z||e<=Z)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=P(t,e),n=e,i=Z,s=me,o=me,a=Z;for(;r!==Z;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==me)throw new Error("invert: does not exist");return P(i,e)}function I2(t,e=_e.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===Z?s:(r[a]=s,P(s*o,e)),me),i=$n(n,e);return t.reduceRight((s,o,a)=>o===Z?s:(r[a]=P(s*r[a],e),P(s*o,e)),i),r}function R2(t){let e=t.length*8-Kn*8,r=Lr(t);return e>0?r>>BigInt(e):r}function Zc(t,e=!1){let r=R2(t);if(e)return r;let{n}=_e;return r>=n?r-n:r}var Un,qi,Xc=class{constructor(e,r){if(this.hashLen=e,this.qByteLen=r,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof r!="number"||r<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Tt.hmacSha256(this.k,...e)}hmacSync(...e){return qi(this.k,...e)}checkSync(){if(typeof qi!="function")throw new co("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return Tr(...r)}generateSync(){this.checkSync(),this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return Tr(...r)}};function $i(t){return Z<t&&t<_e.n}function Yc(t){return Z<t&&t<_e.P}function C2(t,e,r,n=!0){let{n:i}=_e,s=Zc(t,!0);if(!$i(s))return;let o=$n(s,i),a=re.BASE.multiply(s),c=P(a.x,i);if(c===Z)return;let u=P(o*P(e+r*c,i),i);if(u===Z)return;let l=new Wt(c,u),f=(a.x===l.r?0:2)|Number(a.y&me);return n&&l.hasHighS()&&(l=l.normalizeS(),f^=1),{sig:l,recovery:f}}function lo(t){let e;if(typeof t=="bigint")e=t;else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==2*Kn)throw new Error("Expected 32 bytes of private key");e=uo(t)}else if(t instanceof Uint8Array){if(t.length!==Kn)throw new Error("Expected 32 bytes of private key");e=Lr(t)}else throw new TypeError("Expected valid private key");if(!$i(e))throw new Error("Expected private key: 0 < key < n");return e}function T2(t){return t instanceof re?(t.assertValidity(),t):re.fromHex(t)}function ld(t){if(t instanceof Wt)return t.assertValidity(),t;try{return Wt.fromDER(t)}catch{return Wt.fromCompact(t)}}function jc(t,e=!1){return re.fromPrivateKey(t).toRawBytes(e)}function fd(t){let e=t.length>Ct?t.slice(0,Ct):t;return Lr(e)}function B2(t){let e=fd(t),r=P(e,_e.n);return hd(r<Z?e:r)}function hd(t){return Qc(t)}function L2(t,e,r){if(t==null)throw new Error(`sign: expected valid message hash, not "${t}"`);let n=qn(t),i=lo(e),s=[hd(i),B2(n)];if(r!=null){r===!0&&(r=Tt.randomBytes(Ct));let c=qn(r);if(c.length!==Ct)throw new Error(`sign: Expected ${Ct} bytes of extra data`);s.push(c)}let o=Tr(...s),a=fd(n);return{seed:o,m:a,d:i}}function P2(t,e){let{sig:r,recovery:n}=t,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}async function dd(t,e,r={}){let{seed:n,m:i,d:s}=L2(t,e,r.extraEntropy),o=new Xc(E2,Kn);await o.reseed(n);let a;for(;!(a=C2(await o.generate(),i,s,r.canonical));)await o.reseed();return P2(a,r)}var D2={strict:!0};function pd(t,e,r,n=D2){let i;try{i=ld(t),e=qn(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=Zc(e),c;try{c=T2(r)}catch{return!1}let{n:u}=_e,l=$n(o,u),f=P(a*l,u),h=P(s*l,u),d=re.BASE.multiplyAndAddUnsafe(c,f,h);return d?P(d.x,u)===s:!1}re.BASE._setWindowSize(8);var at={node:v2,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var ao={},Tt={bytesToHex:Vn,hexToBytes:sn,concatBytes:Tr,mod:P,invert:$n,isValidPrivateKey(t){try{return lo(t),!0}catch{return!1}},_bigintTo32Bytes:Qc,_normalizePrivateKey:lo,hashToPrivateKey:t=>{t=qn(t);let e=Kn+8;if(t.length<e||t.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let r=P(Lr(t),_e.n-me)+me;return Qc(r)},randomBytes:(t=32)=>{if(at.web)return at.web.getRandomValues(new Uint8Array(t));if(at.node){let{randomBytes:e}=at.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Tt.hashToPrivateKey(Tt.randomBytes(Kn+8)),precompute(t=8,e=re.BASE){let r=e===re.BASE?e:new re(e.x,e.y);return r._setWindowSize(t),r.multiply(Vi),r},sha256:async(...t)=>{if(at.web){let e=await at.web.subtle.digest("SHA-256",Tr(...t));return new Uint8Array(e)}else if(at.node){let{createHash:e}=at.node,r=e("sha256");return t.forEach(n=>r.update(n)),Uint8Array.from(r.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(at.web){let r=await at.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Tr(...e),i=await at.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(at.node){let{createHmac:r}=at.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let r=ao[t];if(r===void 0){let n=await Tt.sha256(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Tr(n,n),ao[t]=r}return Tt.sha256(r,...e)},taggedHashSync:(t,...e)=>{if(typeof Un!="function")throw new co("sha256Sync is undefined, you need to set it");let r=ao[t];if(r===void 0){let n=Un(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Tr(n,n),ao[t]=r}return Un(r,...e)},_JacobianPoint:te};Object.defineProperties(Tt,{sha256Sync:{configurable:!1,get(){return Un},set(t){Un||(Un=t)}},hmacSha256Sync:{configurable:!1,get(){return qi},set(t){qi||(qi=t)}}});function on(t){if(isNaN(t)||t<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Tt.randomBytes(t)}var gI=V(qs(),1),Jc=V(se(),1);function md(t,e){return e.map(r=>ot(t[r]))}function yd(t){return Jc.default.pki.setRsaPrivateKey(...md(t,["n","e","d","p","q","dp","dq","qi"]))}function gd(t){return Jc.default.pki.setRsaPublicKey(...md(t,["n","e"]))}var an={};Ke(an,{jwkToPkcs1:()=>O2,jwkToPkix:()=>F2,pkcs1ToJwk:()=>k2,pkixToJwk:()=>M2});var vI=V(Ii(),1),EI=V(qs(),1);var sr=V(se(),1);function k2(t){let e=sr.default.asn1.fromDer($(t,"ascii")),r=sr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Rt(r.n),e:Rt(r.e),d:Rt(r.d),p:Rt(r.p),q:Rt(r.q),dp:Rt(r.dP),dq:Rt(r.dQ),qi:Rt(r.qInv),alg:"RS256"}}function O2(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=sr.default.pki.privateKeyToAsn1({n:ot(t.n),e:ot(t.e),d:ot(t.d),p:ot(t.p),q:ot(t.q),dP:ot(t.dp),dQ:ot(t.dq),qInv:ot(t.qi)});return U(sr.default.asn1.toDer(e).getBytes(),"ascii")}function M2(t){let e=sr.default.asn1.fromDer($(t,"ascii")),r=sr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Rt(r.n),e:Rt(r.e)}}function F2(t){if(t.n==null||t.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=sr.default.pki.publicKeyToAsn1({n:ot(t.n),e:ot(t.e)});return U(sr.default.asn1.toDer(e).getBytes(),"ascii")}async function xd(t){let e=await rt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Ed(e);return{privateKey:r[0],publicKey:r[1]}}async function eu(t){let r=[await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await U2(t)],n=await Ed({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function wd(t,e){let r=await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function vd(t,e,r){let n=await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)}async function Ed(t){if(t.privateKey==null||t.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([rt.get().subtle.exportKey("jwk",t.privateKey),rt.get().subtle.exportKey("jwk",t.publicKey)])}async function U2(t){return rt.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function bd(t,e,r,n){let i=e?gd(t):yd(t),s=$(Uint8Array.from(r),"ascii"),o=n(s,i);return U(o,"ascii")}function _d(t,e){return bd(t,!0,e,(r,n)=>n.encrypt(r))}function Sd(t,e){return bd(t,!1,e,(r,n)=>n.decrypt(r))}var Hi=class{_key;constructor(e){this._key=e}async verify(e,r){return vd(this._key,r,e)}marshal(){return an.jwkToPkix(this._key)}get bytes(){return Gt.encode({Type:xe.RSA,Data:this.marshal()}).subarray()}encrypt(e){return _d(this._key,e)}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},zn=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return on(16)}async sign(e){return wd(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Hi(this._publicKey)}decrypt(e){return Sd(this._key,e)}marshal(){return an.jwkToPkcs1(this._key)}get bytes(){return Yt.encode({Type:xe.RSA,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new zi.default.util.ByteBuffer(this.marshal()),i=zi.default.asn1.fromDer(n),s=zi.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return zi.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function V2(t){let e=an.pkcs1ToJwk(t),r=await eu(e);return new zn(r.privateKey,r.publicKey)}function q2(t){let e=an.pkixToJwk(t);return new Hi(e)}async function $2(t){let e=await eu(t);return new zn(e.privateKey,e.publicKey)}async function z2(t){let e=await xd(t);return new zn(e.privateKey,e.publicKey)}var nu={};Ke(nu,{Secp256k1PrivateKey:()=>Yi,Secp256k1PublicKey:()=>Gi,generateKeyPair:()=>W2,unmarshalSecp256k1PrivateKey:()=>G2,unmarshalSecp256k1PublicKey:()=>Y2});function Ad(){return Tt.randomPrivateKey()}async function Id(t,e){let{digest:r}=await Ve.digest(e);try{return await dd(r,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}async function Rd(t,e,r){try{let{digest:n}=await Ve.digest(r);return pd(e,n,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function Cd(t){return re.fromHex(t).toRawBytes(!0)}function Td(t){try{jc(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ru(t){try{re.fromHex(t)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Bd(t){try{return jc(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Gi=class{_key;constructor(e){ru(e),this._key=e}async verify(e,r){return Rd(this._key,r,e)}marshal(){return Cd(this._key)}get bytes(){return Gt.encode({Type:xe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},Yi=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??Bd(e),Td(this._key),ru(this._publicKey)}async sign(e){return Id(this._key,e)}get public(){return new Gi(this._publicKey)}marshal(){return this._key}get bytes(){return Yt.encode({Type:xe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function G2(t){return new Yi(t)}function Y2(t){return new Gi(t)}async function W2(){let t=Ad();return new Yi(t)}var or={rsa:tu,ed25519:zc,secp256k1:nu};function iu(t){let e=Object.keys(or).join(" / ");return new E(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function su(t){if(t=t.toLowerCase(),t==="rsa"||t==="ed25519"||t==="secp256k1")return or[t];throw iu(t)}async function ho(t,e){return su(t).generateKeyPair(e??2048)}function cn(t){let e=Gt.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case xe.RSA:return or.rsa.unmarshalRsaPublicKey(r);case xe.Ed25519:return or.ed25519.unmarshalEd25519PublicKey(r);case xe.Secp256k1:return or.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw iu(e.Type??"RSA")}}function ou(t,e){return e=(e??"rsa").toLowerCase(),su(e),t.bytes}async function Hn(t){let e=Yt.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case xe.RSA:return or.rsa.unmarshalRsaPrivateKey(r);case xe.Ed25519:return or.ed25519.unmarshalEd25519PrivateKey(r);case xe.Secp256k1:return or.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw iu(e.Type??"RSA")}}function Ld(t,e){return e=(e??"rsa").toLowerCase(),su(e),t.bytes}async function Wi(t,e){try{let i=await Wh(t,e);return await Hn(i)}catch{}let r=fo.default.pki.decryptRsaPrivateKey(t,e);if(r===null)throw new E("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=fo.default.asn1.toDer(fo.default.pki.privateKeyToAsn1(r));return n=U(n.getBytes(),"ascii"),or.rsa.unmarshalRsaPrivateKey(n)}var au=Symbol.for("@libp2p/content-routing");var cu=Symbol.for("@libp2p/peer-discovery");var uu=Symbol.for("@libp2p/peer-routing");var Qi=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new fu(e,r))}},lu=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},fu=globalThis.CustomEvent??lu;var wt=V(du(),1);wt.default.formatters.b=t=>t==null?"undefined":Re.baseEncode(t);wt.default.formatters.t=t=>t==null?"undefined":st.baseEncode(t);wt.default.formatters.m=t=>t==null?"undefined":Wr.baseEncode(t);wt.default.formatters.p=t=>t==null?"undefined":t.toString();wt.default.formatters.c=t=>t==null?"undefined":t.toString();wt.default.formatters.k=t=>t==null?"undefined":t.toString();function cv(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function G(t){let e=cv(`${t}:trace`);return wt.default.enabled(`${t}:trace`)&&wt.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,wt.default)(`${t}:trace`)),Object.assign((0,wt.default)(t),{error:(0,wt.default)(`${t}:error`),trace:e})}var sp=V($d(),1);var jd=V(Zd(),1),Pr=jd.default;var xo=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var ar="/",Jd=new TextEncoder().encode(ar),wo=Jd[0],Se=class{constructor(e,r){if(typeof e=="string")this._buf=U(e);else if(e instanceof Uint8Array)this._buf=e;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]!==wo)throw new Error("Invalid key")}toString(e="utf8"){return $(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Se(e.join(ar))}static random(){return new Se(xo().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new Se(e):typeof e.uint8Array=="function"?new Se(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Jd),this._buf[0]!==wo){let e=new Uint8Array(this._buf.byteLength+1);e.fill(wo,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===wo;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let s=r[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return r.length<n.length}reverse(){return Se.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ar).slice(1)}type(){return Iv(this.baseNamespace())}name(){return Rv(this.baseNamespace())}instance(e){return new Se(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ar)||(e+=ar),e+=this.type(),new Se(e)}parent(){let e=this.list();return e.length===1?new Se(ar):new Se(e.slice(0,-1).join(ar))}child(e){return this.toString()===ar?e:e.toString()===ar?this:new Se(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return Se.withNamespaces([...this.namespaces(),...Cv(e.map(r=>r.namespaces()))])}};function Iv(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Rv(t){let e=t.split(":");return e[e.length-1]}function Cv(t){return[].concat(...t)}var j;(function(t){t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(j||(j={}));var SR=V(Ls(),1),Tv=V(se(),1);var tp=V(Ka(),1),rp=V(Ie(),1),ep={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function Xi(t,e,r,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(ep).join(" / ");throw new E(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=ep[i],o=(0,tp.default)(t,e,r,n,s);return rp.default.encode64(o,null)}var mu=Symbol.for("@libp2p/peer-id");function vo(t){return t!=null&&!!t[mu]}var Pv=Symbol.for("nodejs.util.inspect.custom"),np=Object.values(Er).map(t=>t.decoder).reduce((t,e)=>t.or(e),Er.identity.decoder),ip=114,yu=36,gu=37,Zi=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[mu](){return!0}toString(){return this.string==null&&(this.string=Re.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ue.createV1(ip,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return ve(this.multihash.bytes,e);if(typeof e=="string")return ie(e).equals(this);if(e?.multihash?.bytes!=null)return ve(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Pv](){return`PeerId(${this.toString()})`}},Zn=class extends Zi{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},jn=class extends Zi{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Jn=class extends Zi{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function ie(t,e){if(e=e??np,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=Qr(Re.decode(`z${t}`));return t.startsWith("12D")?new jn({multihash:r}):t.startsWith("16U")?new Jn({multihash:r}):new Zn({multihash:r})}return ei(np.decode(t))}function ei(t){try{let e=Qr(t);if(e.code===vr.code){if(e.digest.length===yu)return new jn({multihash:e});if(e.digest.length===gu)return new Jn({multihash:e})}if(e.code===Ve.code)return new Zn({multihash:e})}catch{return Dv(ue.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function Dv(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==ip)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===Ve.code)return new Zn({multihash:t.multihash});if(e.code===vr.code){if(e.digest.length===yu)return new jn({multihash:t.multihash});if(e.digest.length===gu)return new Jn({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ln(t,e){return t.length===yu?new jn({multihash:qt(vr.code,t),privateKey:e}):t.length===gu?new Jn({multihash:qt(vr.code,t),privateKey:e}):new Zn({multihash:await Ve.digest(t),publicKey:t,privateKey:e})}var Eo=G("libp2p:keychain"),Nv="/pkcs8/",op="/info/",fn=new WeakMap,hn={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},xu={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function cr(t){return t==null||typeof t!="string"?!1:t===(0,sp.default)(t.trim())&&t.length>0}async function ae(){let r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function Qt(t){return new Se(Nv+t)}function Dr(t){return new Se(op+t)}var dn=class{constructor(e,r){if(this.components=e,this.init=Pr(xu,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.keyLength<hn.minKeyLength)throw new Error(`dek.keyLength must be least ${hn.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<hn.minSaltLength)throw new Error(`dek.saltLength must be least ${hn.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<hn.minIterationCount)throw new Error(`dek.iterationCount must be least ${hn.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?Xi(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";fn.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},xu),r=Math.ceil(hn.minSaltLength/3)*3;return e.dek.salt=$(on(r),"base64"),e}static get options(){return xu}async createKey(e,r,n=2048){if(!cr(e)||e==="self")throw await ae(),new E("Invalid key name",j.ERR_INVALID_KEY_NAME);if(typeof r!="string")throw await ae(),new E("Invalid key type",j.ERR_INVALID_KEY_TYPE);let i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E("Key name already exists",j.ERR_KEY_ALREADY_EXISTS);switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await ae(),new E("Invalid RSA key size",j.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await ho(r,n),c=await a.id(),u=fn.get(this);if(u==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let l=u.dek,f=await a.export(l);o={name:e,id:c};let h=this.components.datastore.batch();h.put(i,U(f)),h.put(Dr(e),U(JSON.stringify(o))),await h.commit()}catch(a){throw await ae(),a}return o}async listKeys(){let e={prefix:op},r=[];for await(let n of this.components.datastore.query(e))r.push(JSON.parse($(n.value)));return r}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new E(`Key with id '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND);return n}catch(r){throw await ae(),r}}async findKeyByName(e){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);let r=Dr(e);try{let n=await this.components.datastore.get(r);return JSON.parse($(n))}catch(n){throw await ae(),Eo.error(n),new E(`Key '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);let r=Qt(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(r),i.delete(Dr(e)),await i.commit(),n}async renameKey(e,r){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid old key name '${e}'`,j.ERR_OLD_KEY_NAME_INVALID);if(!cr(r)||r==="self")throw await ae(),new E(`Invalid new key name '${r}'`,j.ERR_NEW_KEY_NAME_INVALID);let n=Qt(e),i=Qt(r),s=Dr(e),o=Dr(r);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${r}' already exists`,j.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse($(u));l.name=r;let f=this.components.datastore.batch();return f.put(i,c),f.put(o,U(JSON.stringify(l))),f.delete(n),f.delete(s),await f.commit(),l}catch(c){throw await ae(),c}}async exportKey(e,r){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw await ae(),new E("Password is required",j.ERR_PASSWORD_REQUIRED);let n=Qt(e);try{let i=await this.components.datastore.get(n),s=$(i),o=fn.get(this);if(o==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Wi(s,a)).export(r)}catch(i){throw await ae(),i}}async exportPeerId(e){let r="temporary-password",n=await this.exportKey(e,r),i=await Wi(n,r);return await ln(i.public.bytes,i.bytes)}async importKey(e,r,n){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw await ae(),new E("PEM encoded key is required",j.ERR_PEM_REQUIRED);let i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${e}' already exists`,j.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Wi(r,n)}catch{throw await ae(),new E("Cannot read the key, most likely the password is wrong",j.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=fn.get(this);if(l==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let f=l.dek;r=await o.export(f)}catch(l){throw await ae(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,U(r)),u.put(Dr(e),U(JSON.stringify(c))),await u.commit(),c}async importPeer(e,r){try{if(!cr(e))throw new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw new E("PeerId is required",j.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new E("PeerId.privKey is required",j.ERR_MISSING_PRIVATE_KEY);let n=await Hn(r.privateKey),i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${e}' already exists`,j.ERR_KEY_ALREADY_EXISTS);let o=fn.get(this);if(o==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:r.toString()},l=this.components.datastore.batch();return l.put(i,U(c)),l.put(Dr(e),U(JSON.stringify(u))),await l.commit(),u}catch(n){throw await ae(),n}}async getPrivateKey(e){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);try{let r=Qt(e),n=await this.components.datastore.get(r);return $(n)}catch(r){throw await ae(),Eo.error(r),new E(`Key '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,r){if(typeof e!="string")throw await ae(),new E(`Invalid old pass type '${typeof e}'`,j.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await ae(),new E(`Invalid new pass type '${typeof r}'`,j.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await ae(),new E(`Invalid pass length ${r.length}`,j.ERR_INVALID_PASS_LENGTH);Eo("recreating keychain");let n=fn.get(this);if(n==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=r;let s=r!=null&&this.init.dek?.salt!=null?Xi(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";fn.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Qt(a.name)),u=$(c),l=await Wi(u,i),f=s.toString(),h=await l.export(f),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Qt(a.name),U(h)),d.put(Dr(a.name),U(JSON.stringify(p))),await d.commit()}Eo("keychain reconstructed")}};function ur(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return r}var lr=class{constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return ur(this.map.entries(),e=>[ie(e[0]),e[1]])}forEach(e){this.map.forEach((r,n)=>{e(r,ie(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),r)}keys(){return ur(this.map.keys(),e=>ie(e))}values(){return this.map.values()}get size(){return this.map.size}};var Bt=class{constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return ur(this.set.entries(),e=>{let r=ie(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=ie(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ur(this.set.values(),e=>ie(e))}intersection(e){let r=new Bt;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new Bt;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new Bt;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var ti=class{constructor(e){if(this.list=[],e!=null)for(let r of e)this.list.push(r.toString())}[Symbol.iterator](){return ur(this.list.entries(),e=>ie(e[1]))}concat(e){let r=new ti(this);for(let n of e)r.push(n);return r}entries(){return ur(this.list.entries(),e=>[e[0],ie(e[1])])}every(e){return this.list.every((r,n)=>e(ie(r),n,this))}filter(e){let r=new ti;return this.list.forEach((n,i)=>{let s=ie(n);e(s,i,this)&&r.push(s)}),r}find(e){let r=this.list.find((n,i)=>e(ie(n),i,this));if(r!=null)return ie(r)}findIndex(e){return this.list.findIndex((r,n)=>e(ie(r),n,this))}forEach(e){this.list.forEach((r,n)=>{e(ie(r),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return ie(e)}push(...e){for(let r of e)this.list.push(r.toString())}shift(){let e=this.list.shift();if(e!=null)return ie(e)}unshift(...e){let r=this.list.length;for(let n=e.length-1;n>-1;n--)r=this.list.unshift(e[n].toString());return r}get length(){return this.list.length}};var wu;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(wu||(wu={}));var ap=async()=>{let t=await ho("Ed25519"),e=await kv(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function cp(t){return await ln(ou(t))}async function kv(t){return await ln(ou(t.public),Ld(t))}var up={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var ji;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(ji||(ji={}));var fp=Symbol.for("@achingbrain/uint8arraylist");function lp(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function bo(t){return!!t?.[fp]}var Ae=class{constructor(...e){Object.defineProperty(this,fp,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(bo(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(bo(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(e){let r=lp(this.bufs,e);return r.buf[r.index]}set(e,r){let n=lp(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(bo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return Ce(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Ce(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),s=new Ae;return s.length=i,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(o);break}let f=e-a;n.push(o.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(r===c){n.push(o);break}n.push(o.subarray(0,r-a));break}n.push(o)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!bo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let f=0;f<s;f++)o[f]=-1;for(let f=0;f<i;f++)o[n[f]]=f;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=nr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=nr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof Ae)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!ve(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new Ae;return n.bufs=e,r==null&&(r=e.reduce((i,s)=>i+s.byteLength,0)),n.length=r,n}};function _o(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var hp=4294967296,ut=class{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new ut(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new ut(r,n)}toBytes(e,r=0){let n=_o(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new ut;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>hp&&(i=0,++n>hp&&(n=0))),new ut(n,i)}static fromNumber(e){if(e===0)return new ut;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new ut(i,n)}static fromBytes(e,r=0){let n=_o(e),i=new ut,s=0;if(e.length-r>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;s=0}else for(;s<4;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;s<5;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var Ov=Math.pow(2,7),Mv=Math.pow(2,14),Fv=Math.pow(2,21),Uv=Math.pow(2,28),Kv=Math.pow(2,35),Vv=Math.pow(2,42),qv=Math.pow(2,49),$v=Math.pow(2,56),zv=Math.pow(2,63),Lt={encodingLength(t){return t<Ov?1:t<Mv?2:t<Fv?3:t<Uv?4:t<Kv?5:t<Vv?6:t<qv?7:t<$v?8:t<zv?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=St(Lt.encodingLength(t))),ut.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return ut.fromBytes(t,e).toNumber(!0)}};var Hv,lt=class{constructor(e){let{peerId:r,payloadType:n,payload:i,signature:s}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=ji.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ve(this.marshal(),e.marshal())}async validate(e){let r=dp(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await cn(this.peerId.publicKey).verify(r.subarray(),this.signature)}};Hv=lt;lt.createFromProtobuf=async t=>{let e=ji.decode(t),r=await ln(e.publicKey);return new lt({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};lt.seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let r=t.domain,n=t.codec,i=t.marshal(),s=dp(r,n,i),a=await(await Hn(e.privateKey)).sign(s.subarray());return new lt({peerId:e,payloadType:n,payload:i,signature:a})};lt.openAndCertify=async(t,e)=>{let r=await lt.createFromProtobuf(t);if(!await r.validate(e))throw new E("envelope signature is not valid for the given domain",up.ERR_SIGNATURE_NOT_VALID);return r};var dp=(t,e,r)=>{let n=U(t),i=Lt.encode(n.byteLength),s=Lt.encode(e.length),o=Lt.encode(r.length);return new Ae(i,n,s,e,o,r)};var Du=V(So(),1);var ii=V(So(),1);var Ao=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(s*=e,s+=l,s>u||(o+=1,r!==void 0&&o>r))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return r[i]=o[0],r[i+1]=o[1],r[i+2]=o[2],r[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];r[i]=s>>8,r[i+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var _p=45,sE=15,ri=new Ao;function bu(t){if(!(t.length>sE))return ri.new(t).parseWith(()=>ri.readIPv4Addr())}function _u(t){if(!(t.length>_p))return ri.new(t).parseWith(()=>ri.readIPv6Addr())}function Io(t){if(!(t.length>_p))return ri.new(t).parseWith(()=>ri.readIPAddr())}var oC=parseInt("0xFFFF",16),aC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Xt=V(So(),1);function Ip(t){return!!bu(t)}function Rp(t){return!!_u(t)}function ni(t){return!!Io(t)}var Cp=Ip,lE=Rp,Su=function(t){let e=0;if(t=t.toString().trim(),Cp(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(lE(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Cp(r[n]),o;s&&(o=Su(r[n]),r[n]=$(o.slice(0,2),"base16")),o!=null&&++n<8&&r.splice(n,0,$(o.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},Tp=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let s=0;s<r;s++)i.push(t[e+s]);return i.join(".")}if(r===16){let i=[];for(let s=0;s<r;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ji={},Au={},hE=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];hE.forEach(t=>{let e=dE(...t);Au[e.code]=e,Ji[e.name]=e});function dE(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function ce(t){if(typeof t=="number"){if(Au[t]!=null)return Au[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(Ji[t]!=null)return Ji[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var zC=ce("ip4"),HC=ce("ip6"),GC=ce("ipcidr");function Np(t,e){switch(ce(t).code){case 4:case 41:return mE(e);case 42:return Pp(e);case 6:case 273:case 33:case 132:return Op(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Pp(e);case 421:return wE(e);case 444:return Dp(e);case 445:return Dp(e);case 466:return xE(e);default:return $(e,"base16")}}function kp(t,e){switch(ce(t).code){case 4:return Bp(e);case 41:return Bp(e);case 42:return Lp(e);case 6:case 273:case 33:case 132:return Ru(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Lp(e);case 421:return yE(e);case 444:return vE(e);case 445:return EE(e);case 466:return gE(e);default:return U(e,"base16")}}var Iu=Object.values(Er).map(t=>t.decoder),pE=function(){let t=Iu[0].or(Iu[1]);return Iu.slice(2).forEach(e=>t=t.or(e)),t}();function Bp(t){if(!ni(t))throw new Error("invalid ip address");return Su(t)}function mE(t){let e=Tp(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!ni(e))throw new Error("invalid ip address");return e}function Ru(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Op(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function Lp(t){let e=U(t),r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function Pp(t){let e=Xt.default.decode(t);if(t=t.slice(Xt.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return $(t)}function yE(t){let e;t[0]==="Q"||t[0]==="1"?e=Qr(Re.decode(`z${t}`)).bytes:e=ue.parse(t).multihash.bytes;let r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function gE(t){let e=pE.decode(t),r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function xE(t){let e=Xt.default.decode(t),r=t.slice(Xt.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+$(r,"base64url")}function wE(t){let e=Xt.default.decode(t),r=t.slice(Xt.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return $(r,"base58btc")}function vE(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=st.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ru(n);return Ce([r,i],r.length+i.length)}function EE(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=st.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ru(n);return Ce([r,i],r.length+i.length)}function Dp(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=$(e,"base32"),i=Op(r);return`${n}:${i}`}function bE(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=ce(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw Fp("invalid address: "+t);if(s.path===!0){e.push([i,Pu(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function _E(t){let e=[];return t.map(r=>{let n=To(r);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Pu(e.join("/"))}function SE(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=To(e);return e.length>1?[r.code,kp(r.code,e[1])]:[r.code]})}function Cu(t){return t.map(e=>{let r=To(e);return e[1]!=null?[r.code,Np(r.code,e[1])]:[r.code]})}function Tu(t){return Co(Ce(t.map(e=>{let r=To(e),n=Uint8Array.from(ii.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=Ce([n,e[1]])),n})))}function Bu(t,e){return t.size>0?t.size/8:t.size===0?0:ii.default.decode(e)+(ii.default.decode.bytes??0)}function Ro(t){let e=[],r=0;for(;r<t.length;){let n=ii.default.decode(t,r),i=ii.default.decode.bytes??0,s=ce(n),o=Bu(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw Fp("Invalid address Uint8Array: "+$(t,"base16"));e.push([n,a])}return e}function Lu(t){let e=Ro(t),r=Cu(e);return _E(r)}function AE(t){t=Pu(t);let e=bE(t),r=SE(e);return Tu(r)}function Mp(t){return AE(t)}function Co(t){let e=IE(t);if(e!=null)throw e;return Uint8Array.from(t)}function IE(t){try{Ro(t)}catch(e){return e}}function Pu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function Fp(t){return new Error("Error parsing address: "+t)}function To(t){return ce(t[0])}var CE=Symbol.for("nodejs.util.inspect.custom"),TE=[ce("dns").code,ce("dns4").code,ce("dns6").code,ce("dnsaddr").code],Nu=new Map,Up=Symbol.for("@multiformats/js-multiaddr/multiaddr");function pn(t){return!!t?.[Up]}var fr=class{bytes;#e;#t;#n;#r;[Up]=!0;constructor(e){if(e==null&&(e=""),e instanceof Uint8Array)this.bytes=Co(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=Mp(e)}else if(pn(e))this.bytes=Co(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return this.#e==null&&(this.#e=Lu(this.bytes)),this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,i,s="",o=ce("tcp"),a=ce("udp"),c=ce("ip4"),u=ce("ip6"),l=ce("dns6"),f=ce("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(s=`%${p??""}`),TE.includes(d)&&(r=o.name,i=443,n=`${p??""}${s}`,e=d===l.code?6:4),(d===o.code||d===a.code)&&(r=ce(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(r=ce(d).name,n=`${p??""}${s}`,e=d===u.code?6:4);if(e==null||r==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:r,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},ce(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=Du.default.decode(r,n),s=Du.default.decode.bytes??0,o=ce(i),a=Bu(o,r.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return this.#t==null&&(this.#t=Ro(this.bytes)),this.#t}stringTuples(){return this.#n==null&&(this.#n=Cu(this.tuples())),this.#n}encapsulate(e){return e=new fr(e),new fr(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new fr(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new fr(Tu(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Ji.ipfs.code).pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?$(Re.decode(`z${n}`),"base58btc"):$(ue.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(this.#r===void 0)try{this.#r=this.stringTuples().filter(e=>ce(e[0]).path===!0)[0][1],this.#r==null&&(this.#r=null)}catch{this.#r=null}return this.#r}equals(e){return ve(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=Nu.get(r.name);if(n==null)throw new E(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new fr(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[CE](){return`Multiaddr(${Lu(this.bytes)})`}};function Ne(t){return new fr(t)}function Kp(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var es;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=ze((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>$e(s,n.codec()),n.decode=s=>qe(s,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=ze((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),r),t.encode=n=>$e(n,t.codec()),t.decode=n=>qe(n,t.codec())})(es||(es={}));var Vp="libp2p-peer-record",qp=Uint8Array.from([3,1]);var Ze=class{constructor(e){this.domain=Ze.DOMAIN,this.codec=Ze.CODEC;let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=es.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Ze)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Kp(this.multiaddrs,e.multiaddrs))}};Ze.createFromProtobuf=t=>{let e=es.decode(t),r=ei(e.peerId),n=(e.addresses??[]).map(s=>Ne(s.multiaddr)),i=e.seq;return new Ze({peerId:r,multiaddrs:n,seqNumber:i})};Ze.DOMAIN=Vp;Ze.CODEC=qp;var Jp=V(zp(),1);var rs=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ou=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Hp=t=>globalThis.DOMException===void 0?new Ou(t):new DOMException(t),Gp=t=>{let e=t.reason===void 0?Hp("This operation was aborted."):t.reason;return e instanceof Error?e:Hp(e)};function Mu(t,e,r,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(Gp(c)),c.addEventListener("abort",()=>{a(Gp(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new rs(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{o(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function Fu(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var mn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},hr,ns=class{constructor(){hr.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&mn(this,hr,"f")[this.size-1].priority>=r.priority){mn(this,hr,"f").push(n);return}let i=Fu(mn(this,hr,"f"),n,(s,o)=>o.priority-s.priority);mn(this,hr,"f").splice(i,0,n)}dequeue(){let e=mn(this,hr,"f").shift();return e?.run}filter(e){return mn(this,hr,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return mn(this,hr,"f").length}};hr=new WeakMap;var Ee=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},k=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Be,ss,os,kr,Oo,as,Lo,Pt,is,ft,Po,ht,cs,Nr,Do,Yp,Wp,Zp,Qp,Xp,No,Uu,Ku,Mo,jp,ko,Fo=class extends Error{},Dt=class extends Jp.default{constructor(e){var r,n,i,s;if(super(),Be.add(this),ss.set(this,void 0),os.set(this,void 0),kr.set(this,0),Oo.set(this,void 0),as.set(this,void 0),Lo.set(this,0),Pt.set(this,void 0),is.set(this,void 0),ft.set(this,void 0),Po.set(this,void 0),ht.set(this,0),cs.set(this,void 0),Nr.set(this,void 0),Do.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ns,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);Ee(this,ss,e.carryoverConcurrencyCount,"f"),Ee(this,os,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Ee(this,Oo,e.intervalCap,"f"),Ee(this,as,e.interval,"f"),Ee(this,ft,new e.queueClass,"f"),Ee(this,Po,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Ee(this,Do,e.throwOnTimeout===!0,"f"),Ee(this,Nr,e.autoStart===!1,"f")}get concurrency(){return k(this,cs,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Ee(this,cs,e,"f"),k(this,Be,"m",Mo).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:k(this,Do,"f"),...r},new Promise((n,i)=>{k(this,ft,"f").enqueue(async()=>{var s,o,a;Ee(this,ht,(o=k(this,ht,"f"),o++,o),"f"),Ee(this,kr,(a=k(this,kr,"f"),a++,a),"f");try{if(!((s=r.signal)===null||s===void 0)&&s.aborted)throw new Fo("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=Mu(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,k(this,Be,"m",jp).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof rs&&!r.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{k(this,Be,"m",Zp).call(this)}},r),this.emit("add"),k(this,Be,"m",No).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return k(this,Nr,"f")?(Ee(this,Nr,!1,"f"),k(this,Be,"m",Mo).call(this),this):this}pause(){Ee(this,Nr,!0,"f")}clear(){Ee(this,ft,new(k(this,Po,"f")),"f")}async onEmpty(){k(this,ft,"f").size!==0&&await k(this,Be,"m",ko).call(this,"empty")}async onSizeLessThan(e){k(this,ft,"f").size<e||await k(this,Be,"m",ko).call(this,"next",()=>k(this,ft,"f").size<e)}async onIdle(){k(this,ht,"f")===0&&k(this,ft,"f").size===0||await k(this,Be,"m",ko).call(this,"idle")}get size(){return k(this,ft,"f").size}sizeBy(e){return k(this,ft,"f").filter(e).length}get pending(){return k(this,ht,"f")}get isPaused(){return k(this,Nr,"f")}};ss=new WeakMap,os=new WeakMap,kr=new WeakMap,Oo=new WeakMap,as=new WeakMap,Lo=new WeakMap,Pt=new WeakMap,is=new WeakMap,ft=new WeakMap,Po=new WeakMap,ht=new WeakMap,cs=new WeakMap,Nr=new WeakMap,Do=new WeakMap,Be=new WeakSet,Yp=function(){return k(this,os,"f")||k(this,kr,"f")<k(this,Oo,"f")},Wp=function(){return k(this,ht,"f")<k(this,cs,"f")},Zp=function(){var e;Ee(this,ht,(e=k(this,ht,"f"),e--,e),"f"),k(this,Be,"m",No).call(this),this.emit("next")},Qp=function(){k(this,Be,"m",Ku).call(this),k(this,Be,"m",Uu).call(this),Ee(this,is,void 0,"f")},Xp=function(){let e=Date.now();if(k(this,Pt,"f")===void 0){let r=k(this,Lo,"f")-e;if(r<0)Ee(this,kr,k(this,ss,"f")?k(this,ht,"f"):0,"f");else return k(this,is,"f")===void 0&&Ee(this,is,setTimeout(()=>{k(this,Be,"m",Qp).call(this)},r),"f"),!0}return!1},No=function(){if(k(this,ft,"f").size===0)return k(this,Pt,"f")&&clearInterval(k(this,Pt,"f")),Ee(this,Pt,void 0,"f"),this.emit("empty"),k(this,ht,"f")===0&&this.emit("idle"),!1;if(!k(this,Nr,"f")){let e=!k(this,Be,"a",Xp);if(k(this,Be,"a",Yp)&&k(this,Be,"a",Wp)){let r=k(this,ft,"f").dequeue();return r?(this.emit("active"),r(),e&&k(this,Be,"m",Uu).call(this),!0):!1}}return!1},Uu=function(){k(this,os,"f")||k(this,Pt,"f")!==void 0||(Ee(this,Pt,setInterval(()=>{k(this,Be,"m",Ku).call(this)},k(this,as,"f")),"f"),Ee(this,Lo,Date.now()+k(this,as,"f"),"f"))},Ku=function(){k(this,kr,"f")===0&&k(this,ht,"f")===0&&k(this,Pt,"f")&&(clearInterval(k(this,Pt,"f")),Ee(this,Pt,void 0,"f")),Ee(this,kr,k(this,ss,"f")?k(this,ht,"f"):0,"f"),k(this,Be,"m",Mo).call(this)},Mo=function(){for(;k(this,Be,"m",No).call(this););},jp=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Fo("The task was aborted."))},{once:!0})})},ko=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var Vu=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},qu=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},em=t=>globalThis.DOMException===void 0?new qu(t):new DOMException(t),tm=t=>{let e=t.reason===void 0?em("This operation was aborted."):t.reason;return e instanceof Error?e:em(e)};function $u(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,u)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(r===Number.POSITIVE_INFINITY){c(t);return}if(e.signal){let{signal:f}=e;f.aborted&&u(tm(f)),f.addEventListener("abort",()=>{u(tm(f))})}let l=new Vu;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(f){u(f)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${r} milliseconds`,u(l))},r),(async()=>{try{c(await t)}catch(f){u(f)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var zu="lock:worker:request-read",Hu="lock:worker:release-read",Gu="lock:master:grant-read",Yu="lock:worker:request-write",Wu="lock:worker:release-write",Qu="lock:master:grant-write";var Or={},si=t=>{t.addEventListener("message",e=>{si.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{si.dispatchEvent("message",t,e)})};si.addEventListener=(t,e)=>{Or[t]==null&&(Or[t]=[]),Or[t].push(e)};si.removeEventListener=(t,e)=>{Or[t]!=null&&(Or[t]=Or[t].filter(r=>r===e))};si.dispatchEvent=function(t,e,r){Or[t]!=null&&Or[t].forEach(n=>n(e,r))};var Xu=si;var rm=(t,e,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},nm=(t,e,r,n)=>async()=>{let i=xo();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},PE={singleProcess:!1},im=t=>{if(t=Object.assign({},PE,t),!!globalThis.document||t.singleProcess){let r=new EventTarget;return Xu.addEventListener("message",rm(r,"requestReadLock",zu,Hu,Gu)),Xu.addEventListener("message",rm(r,"requestWriteLock",Yu,Wu,Qu)),r}return{isWorker:!0,readLock:r=>nm(r,zu,Gu,Hu),writeLock:r=>nm(r,Yu,Qu,Wu)}};var yn={},Mr;async function Zu(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await $u((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var DE=(t,e)=>{if(Mr.isWorker===!0)return{readLock:Mr.readLock(t,e),writeLock:Mr.writeLock(t,e)};let r=new Dt({concurrency:1}),n;return{async readLock(){if(n!=null)return await Zu(n,e);n=new Dt({concurrency:e.concurrency,autoStart:!1});let i=n,s=Zu(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await Zu(r,e)}}},NE={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ju(t){let e=Object.assign({},NE,t);return Mr==null&&(Mr=im(e),Mr.isWorker!==!0&&(Mr.addEventListener("requestReadLock",r=>{yn[r.data.name]!=null&&yn[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Mr.addEventListener("requestWriteLock",async r=>{yn[r.data.name]!=null&&yn[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),yn[e.name]==null&&(yn[e.name]=DE(e.name,e)),yn[e.name]}var He={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var oi;(function(t){let e;(function(i){let s;i.codec=()=>(s==null&&(s=ze((o,a,c={})=>{c.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)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>$e(o,i.codec()),i.decode=o=>qe(o,i.codec())})(e=t.Peer$metadataEntry||(t.Peer$metadataEntry={}));let r;(function(i){let s;i.codec=()=>(s==null&&(s=ze((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),Ko.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=Ko.codec().decode(o,o.uint32());break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>$e(o,i.codec()),i.decode=o=>qe(o,i.codec())})(r=t.Peer$tagsEntry||(t.Peer$tagsEntry={}));let n;t.codec=()=>(n==null&&(n=ze((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),Uo.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),t.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),t.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(Uo.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let u=t.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(u.key,u.value);break}case 7:{let u=t.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return o})),n),t.encode=i=>$e(i,t.codec()),t.decode=i=>qe(i,t.codec())})(oi||(oi={}));var Uo;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Uo||(Uo={}));var Ko;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={value:0},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.value=r.uint32();break;case 2:i.expiry=r.uint64();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Ko||(Ko={}));async function ai(t,e){let r=oi.decode(e);r.publicKey!=null&&t.publicKey==null&&(t=await cp(cn(r.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of r.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...r,id:t,addresses:r.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:Ne(s),isCertified:o??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}var Ju="/peers/";function ci(t){if(!vo(t)||t.type==null)throw new E("Invalid PeerId",He.ERR_INVALID_PARAMETERS);let e=t.toCID().toString();return new Se(`${Ju}${e}`)}async function sm(t,e,r){let n=new Map;for(let i of r){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=Ne(i.multiaddr)),!pn(i.multiaddr))throw new E("Multiaddr was invalid",He.ERR_INVALID_PARAMETERS);if(!await e(t,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function qo(t,e,r,n){if(e==null)throw new E("Invalid PeerData",He.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&t.publicKey!=null&&!ve(e.publicKey,t.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",He.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!t.equals(i.id))throw new E("peer id did not match existing peer id",He.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(r==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Vo(f,{validate:om})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Vo(f,{validate:am,map:cm})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(r==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,d]of f)d==null?a.delete(h):a.set(h,d);a=Vo([...a.entries()],{validate:om})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[d,p]of f)p==null?h.delete(d):h.set(d,p);c=Vo([...h.entries()],{validate:am,map:cm})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await sm(t,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??t.publicKey,peerRecordEnvelope:u};return t.type!=="RSA"&&delete l.publicKey,l}function Vo(t,e){let r=new Map;for(let[n,i]of t)i!=null&&e.validate(n,i);for(let[n,i]of t.sort(([s],[o])=>s.localeCompare(o)))i!=null&&r.set(n,e.map?.(n,i)??i);return r}function om(t,e){if(typeof t!="string")throw new E("Metadata key must be a string",He.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",He.ERR_INVALID_PARAMETERS)}function am(t,e){if(typeof t!="string")throw new E("Tag name must be a string",He.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",He.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",He.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",He.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",He.ERR_INVALID_PARAMETERS)}}function cm(t,e){let r;return e.expiry!=null&&(r=e.expiry),e.ttl!=null&&(r=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:r}}var $o=class{peerId;datastore;lock;addressFilter;constructor(e,r={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=r.addressFilter,this.lock=ju({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ci(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",He.ERR_INVALID_PARAMETERS);await this.datastore.delete(ci(e))}async load(e){let r=await this.datastore.get(ci(e));return ai(e,r)}async save(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:r}of this.datastore.query({prefix:Ju})){let n=e.toString().split("/")[2],i=st.decode(n),s=ei(i);s.equals(this.peerId)||(yield ai(s,r))}}async#e(e){try{let r=await this.datastore.get(ci(e)),n=await ai(e,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}}async#t(e,r,n,i){let s=oi.encode(r);return n!=null&&ve(s,n)?{peer:await ai(e,s),previous:i,updated:!1}:(await this.datastore.put(ci(e),s),{peer:await ai(e,s),previous:i,updated:!0})}};var fe=G("libp2p:peer-store"),zo=class{store;events;peerId;constructor(e,r={}){this.events=e.events,this.peerId=e.peerId,this.store=new $o(e,r)}async forEach(e){fe.trace("forEach await read lock");let r=await this.store.lock.readLock();fe.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{fe.trace("forEach release read lock"),r()}}async all(){fe.trace("all await read lock");let e=await this.store.lock.readLock();fe.trace("all got read lock");try{let r=[];for await(let n of this.store.all())r.push(n);return r}finally{fe.trace("all release read lock"),e()}}async delete(e){fe.trace("delete await write lock");let r=await this.store.lock.writeLock();fe.trace("delete got write lock");try{await this.store.delete(e)}finally{fe.trace("delete release write lock"),r()}}async has(e){fe.trace("has await read lock");let r=await this.store.lock.readLock();fe.trace("has got read lock");try{return await this.store.has(e)}finally{fe.trace("has release read lock"),r()}}async get(e){fe.trace("get await read lock");let r=await this.store.lock.readLock();fe.trace("get got read lock");try{return await this.store.load(e)}finally{fe.trace("get release read lock"),r()}}async save(e,r){fe.trace("save await write lock");let n=await this.store.lock.writeLock();fe.trace("save got write lock");try{let i=await this.store.save(e,r);return this.#e(e,i),i.peer}finally{fe.trace("save release write lock"),n()}}async patch(e,r){fe.trace("patch await write lock");let n=await this.store.lock.writeLock();fe.trace("patch got write lock");try{let i=await this.store.patch(e,r);return this.#e(e,i),i.peer}finally{fe.trace("patch release write lock"),n()}}async merge(e,r){fe.trace("merge await write lock");let n=await this.store.lock.writeLock();fe.trace("merge got write lock");try{let i=await this.store.merge(e,r);return this.#e(e,i),i.peer}finally{fe.trace("merge release write lock"),n()}}async consumePeerRecord(e,r){let n=await lt.openAndCertify(e,Ze.DOMAIN);if(r?.equals(n.peerId)===!1)return fe("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;let i=Ze.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await lt.createFromProtobuf(s.peerRecordEnvelope),a=Ze.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return fe("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,r){r.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))}};function kE(t){return t[Symbol.asyncIterator]!=null}function OE(t){if(kE(t))return(async()=>{let r=[];for await(let n of t)r.push(n);return r})();let e=[];for(let r of t)e.push(r);return e}var el=OE;function ME(t){return t[Symbol.asyncIterator]!=null}function FE(t,e){return ME(t)?async function*(){yield*(await el(t)).sort(e)}():function*(){yield*el(t).sort(e)}()}var tl=FE;function UE(t){return t[Symbol.asyncIterator]!=null}function KE(t){if(UE(t))return(async()=>{for await(let e of t);})();for(let e of t);}var rl=KE;function VE(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var Ho=VE;function qE(t){return t[Symbol.asyncIterator]!=null}function $E(t,e){if(qE(t))return async function*(){for await(let a of t)await e(a)&&(yield a)}();let r=Ho(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of r)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of r)o(a)&&(yield a)}()}var Nt=$E;function zE(t){return t[Symbol.asyncIterator]!=null}function HE(t,e){return zE(t)?async function*(){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}}():function*(){let r=0;if(!(e<1)){for(let n of t)if(yield n,r++,r===e)return}}()}var nl=HE;var Go=class{put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield n}async*getMany(e,r={}){for await(let n of e)yield{key:n,value:await this.get(n,r)}}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await rl(this.putMany(e,n)),e=[],await rl(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null){let i=e.prefix;n=Nt(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Nt(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>tl(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Nt(n,()=>i++>=s)}return e.limit!=null&&(n=nl(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null){let i=e.prefix;n=Nt(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Nt(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>tl(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Nt(n,()=>s++>=i)}return e.limit!=null&&(n=nl(n,e.limit)),n}};var fm=V(il(),1);function hm(t){return t=t??new Error("Not Found"),(0,fm.default)(t,"ERR_NOT_FOUND")}var Yo=class extends Go{constructor(){super(),this.data=new Map}put(e,r){return this.data.set(e.toString(),r),e}get(e){let r=this.data.get(e.toString());if(r==null)throw hm();return r}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,r]of this.data.entries())yield{key:new Se(e),value:r}}*_allKeys(){for(let e of this.data.keys())yield new Se(e)}};function dm(t,e){let r;return function(){let n=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(n,e)}}var WE=G("libp2p:address-manager"),QE=t=>t;function sl(t,e){let r=t.getPeerId();return r!=null&&ie(r).equals(e)&&(t=t.decapsulate(Ne(`/p2p/${e.toString()}`))),t}var Wo=class{components;listen;announce;observed;announceFilter;constructor(e,r={}){let{listen:n=[],announce:i=[]}=r;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??QE,this._updatePeerStoreAddresses=dm(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>Ne(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:e}).catch(r=>{WE.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(e=>Ne(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Ne(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Ne(e))}addObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString(),i=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString();this.observed.delete(r)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let r=new Set(e);return this.announceFilter(Array.from(r).map(n=>Ne(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function pm(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}var ol=class{components={};_started=!1;constructor(e={}){this.components={};for(let[r,n]of Object.entries(e))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(r=>pm(r)).map(async r=>{await r[e]?.()}))}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")}},XE=["metrics","connectionProtector"],ZE=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mm(t={}){let e=new ol(t);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!ZE.includes(i)){let o=e.components[i];if(o==null&&!XE.includes(i))throw new E(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}var bm=V(ym(),1);var gm="[a-fA-F\\d:]",Fr=t=>t&&t.includeBoundaries?`(?:(?<=\\s|^)(?=${gm})|(?<=${gm})(?=\\s|$))`:"",kt="(?: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}",Pe="[a-fA-F\\d]{1,4}",Qo=`
37
+ SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),r(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}};jm.exports=yl});var ey=R(()=>{});var ry=R((X3,ty)=>{ty.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var iy=R((j3,ny)=>{var bb=ry(),gl=pt();ny.exports=class{constructor(){this._storage={}}incrby(e,r,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+r,new gl(0,i,this._storage[e].value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new bb(r,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new gl(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let r=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new gl(0,r,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var wl=R((J3,oy)=>{var _b=ls(),Sb=iy(),sy=pt(),xl=class extends _b{constructor(e={}){super(e),this._memoryStorage=new Sb}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(o,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(i,u,c)}else i(c)})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,r,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-r,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,r),Promise.resolve(new sy(0,n===0?-1:n,i))}set(e,r,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new sy(0,i===0?-1:i,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};oy.exports=xl});var dy=R((eB,hy)=>{var ay=ey(),Ab=zr(),Ib=ls(),uy=wl(),Rb=pt(),vt="rate_limiter_flexible",pi=null,cy=function(t,e,r,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},t.send({channel:vt,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:r,data:i})},ly=function(t){setTimeout(()=>{this._initiated?process.send(t):typeof this._promises[t.promiseId]<"u"&&ly.call(this,t)},30)},hi=function(t,e,r,n,i){let s={channel:vt,keyPrefix:this.keyPrefix,func:t,promiseId:e,data:{key:r,arg:n,opts:i}};this._initiated?process.send(s):ly.call(this,s)},fy=function(t,e){if(!e||e.channel!==vt||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let r;switch(e.func){case"consume":r=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":r=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":r=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":r=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":r=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":r=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}r&&r.then(n=>{cy(t,e,"resolve",n)}).catch(n=>{cy(t,e,"reject",n)})},Cb=function(t){if(!t||t.channel!==vt||t.keyPrefix!==this.keyPrefix)return!1;if(this._promises[t.promiseId]){clearTimeout(this._promises[t.promiseId].timeoutId);let e;switch(t.data===null||t.data===!0||t.data===!1?e=t.data:e=new Rb(t.data.remainingPoints,t.data.msBeforeNext,t.data.consumedPoints,t.data.isFirstInDuration),t.type){case"resolve":this._promises[t.promiseId].resolve(e);break;case"reject":this._promises[t.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${t.type}'`)}delete this._promises[t.promiseId]}},Tb=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},di=function(t,e){let r=process.hrtime(),n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=Ab.randomBytes(12).toString("base64")),this._promises[n]={resolve:t,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},vl=class{constructor(){if(pi)return pi;this._rateLimiters={},ay.setMaxListeners(0),ay.on("message",(e,r)=>{r&&r.channel===vt&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new uy(r.opts)),e.send({channel:vt,type:"init",keyPrefix:r.opts.keyPrefix})):fy.call(this,e,r)}),pi=this}},El=class{constructor(e){if(pi)return pi;this._rateLimiters={},e.launchBus((r,n)=>{n.on("process:msg",i=>{let s=i.raw;if(s&&s.channel===vt&&s.type==="init")typeof this._rateLimiters[s.opts.keyPrefix]>"u"&&(this._rateLimiters[s.opts.keyPrefix]=new uy(s.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:vt,channel:vt,type:"init",keyPrefix:s.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=vt,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};fy.call(this,o,s)}})}),pi=this}},bl=class extends Ib{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===vt&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:Cb.call(this,r)}),process.send({channel:vt,type:"init",opts:Tb.call(this)}),this._promises={}}consume(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"consume",o,e,r,n)})}penalty(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"penalty",o,e,r,n)})}reward(e,r=1,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"reward",o,e,r,n)})}block(e,r,n={}){return new Promise((i,s)=>{let o=di.call(this,i,s);hi.call(this,"block",o,e,r,n)})}get(e,r={}){return new Promise((n,i)=>{let s=di.call(this,n,i);hi.call(this,"get",s,e,r)})}delete(e,r={}){return new Promise((n,i)=>{let s=di.call(this,n,i);hi.call(this,"delete",s,e,r)})}};hy.exports={RateLimiterClusterMaster:vl,RateLimiterClusterMasterPM2:El,RateLimiterCluster:bl}});var my=R((tB,py)=>{var Bb=fi(),Lb=pt(),_l=class extends Bb{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,r,n){let i=new Lb;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===r,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,r,n,i=!1,s={}){return new Promise((o,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,r,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};o(f)})}):this.client.incr(e,r,(l,f)=>{l||f===!1?this.client.add(e,r,u,(h,d)=>{if(h||!d)if(typeof s.attemptNumber>"u"||s.attemptNumber<3){let p=Object.assign({},s);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,r,n,i,p).then(m=>o(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};o(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,m={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};o(m)}})})})}_get(e){return new Promise((r,n)=>{let i=Date.now();this.client.get(e,(s,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:o,msBeforeNext:u>=0?Math.max(u-i,0):-1};r(l)}}):r(null)})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,s)=>{i?n(i):s===!1?r(s):this.client.del(`${e}_expire`,o=>{o?n(o):r(s)})})})}};py.exports=_l});var xy=R((nB,gy)=>{var yy=pt();gy.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new yy(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new yy(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(e,r=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,r):(this.runActionAnyway&&this.limiter.consume(e,r).catch(()=>{}),n)}block(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,r):(this.runActionAnyway&&this.limiter.block(e,r).catch(()=>{}),n)}penalty(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,r):(this.runActionAnyway&&this.limiter.penalty(e,r).catch(()=>{}),n)}reward(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,r):(this.runActionAnyway&&this.limiter.reward(e,r).catch(()=>{}),n)}get(e){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(e):r}delete(e){return this.limiter.delete(e)}}});var vy=R((sB,wy)=>{var Pb=ls();wy.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(r=>{if(!(r instanceof Pb))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,r=1){return new Promise((n,i)=>{let s=[];this._limiters.forEach(o=>{s.push(o.consume(e,r).catch(a=>({rejected:!0,rej:a})))}),Promise.all(s).then(o=>{let a={},c=!1;o.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u<o.length;u++)c&&o[u].rejected===!0?a[this._limiters[u].keyPrefix]=o[u].rej:c||(a[this._limiters[u].keyPrefix]=o[u]);c?i(a):n(a)})})}}});var by=R((aB,Ey)=>{Ey.exports=class extends Error{constructor(e,r){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,r&&(this.extra=r)}}});var Iy=R((uB,Ay)=>{var _y=by(),Sy=4294967295,Sl="limiter";Ay.exports=class{constructor(e,r={maxQueueSize:Sy}){this._queueLimiters={KEY_DEFAULT:new Jo(e,r)},this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(e=Sl){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,r=Sl){return this._queueLimiters[r]||(this._queueLimiters[r]=new Jo(this._limiterFlexible,{key:r,maxQueueSize:this._maxQueueSize})),this._queueLimiters[r].removeTokens(e)}};var Jo=class{constructor(e,r={maxQueueSize:Sy,key:Sl}){this._key=r.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let r=this;return new Promise((n,i)=>{if(e>r._limiterFlexible.points){i(new _y(`Requested tokens ${e} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,i,e):r._limiterFlexible.consume(r._key,e).then(s=>{n(s.remainingPoints)}).catch(s=>{s instanceof Error?i(s):(r._queueRequest.call(r,n,i,e),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),s.msBeforeNext)))})})}_queueRequest(e,r,n){let i=this;i._queue.length<i._maxQueueSize?i._queue.push({resolve:e,reject:r,tokens:n}):r(new _y(`Number of requests reached it's maximum ${i._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let r=e._queue.shift();e._limiterFlexible.consume(e._key,r.tokens).then(n=>{r.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(r.reject(n),e._processFIFO.call(e)):(e._queue.unshift(r),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var Cy=R((fB,Ry)=>{var Al=pt();Ry.exports=class{constructor(e,r){this._rateLimiter=e,this._burstLimiter=r}_combineRes(e,r){return new Al(e.remainingPoints,Math.min(e.msBeforeNext,r.msBeforeNext),e.consumedPoints,e.isFirstInDuration)}consume(e,r=1,n={}){return this._rateLimiter.consume(e,r,n).catch(i=>i instanceof Al?this._burstLimiter.consume(e,r,n).then(s=>Promise.resolve(this._combineRes(i,s))).catch(s=>s instanceof Al?Promise.reject(this._combineRes(i,s)):Promise.reject(s)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}}});var By=R((hB,Ty)=>{var Db=Gm(),Nb=Qm(),kb=Zm(),Ob=Jm(),{RateLimiterClusterMaster:Mb,RateLimiterClusterMasterPM2:Fb,RateLimiterCluster:Ub}=dy(),Kb=wl(),Vb=my(),qb=xy(),$b=vy(),zb=Iy(),Hb=Cy(),Gb=pt();Ty.exports={RateLimiterRedis:Db,RateLimiterMongo:Nb,RateLimiterMySQL:kb,RateLimiterPostgres:Ob,RateLimiterMemory:Kb,RateLimiterMemcache:Vb,RateLimiterClusterMaster:Mb,RateLimiterClusterMasterPM2:Fb,RateLimiterCluster:Ub,RLWrapperBlackAndWhite:qb,RateLimiterUnion:$b,RateLimiterQueue:zb,BurstyRateLimiter:Hb,RateLimiterRes:Gb}});var A_={};Ke(A_,{createLibp2p:()=>S_});var Qy=V(bi(),1);var YI=V(Ii(),1),WI=V(w0(),1);var $s=class extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=$s.code,this.type=$s.type}},xr=$s;Ia(xr,"code","ABORT_ERR"),Ia(xr,"type","aborted");var E=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var fo=V(se(),1);var ec={};Ke(ec,{identity:()=>Ux});function Nx(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,g=0,w=p.length;g!==w&&p[g]===0;)g++,m++;for(var _=(w-g)*l+1>>>0,N=new Uint8Array(_);g!==w;){for(var C=p[g],T=0,H=_-1;(C!==0||T<y)&&H!==-1;H--,T++)C+=256*N[H]>>>0,N[H]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");y=T,g++}for(var W=_-y;W!==_&&N[W]===0;)W++;for(var De=c.repeat(m);W<_;++W)De+=t.charAt(N[W]);return De}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,g=0;p[m]===c;)y++,m++;for(var w=(p.length-m)*u+1>>>0,_=new Uint8Array(w);p[m];){var N=r[p.charCodeAt(m)];if(N===255)return;for(var C=0,T=w-1;(N!==0||C<g)&&T!==-1;T--,C++)N+=a*_[T]>>>0,_[T]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");g=C,m++}if(p[m]!==" "){for(var H=w-g;H!==w&&_[H]===0;)H++;for(var W=new Uint8Array(y+(w-H)),De=y;H!==w;)W[De++]=_[H++];return W}}}function d(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var kx=Nx,Ox=kx,v0=Ox;var rS=new Uint8Array(0);var E0=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},rr=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var b0=t=>new TextEncoder().encode(t),_0=t=>new TextDecoder().decode(t);var Xa=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Za=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return A0(this,e)}},ja=class{constructor(e){this.decoders=e}or(e){return A0(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},A0=(t,e)=>new ja({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Ja=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Xa(e,r,n),this.decoder=new Za(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Tn=({name:t,prefix:e,encode:r,decode:n})=>new Ja(t,e,r,n),wr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=v0(r,e);return Tn({prefix:t,name:e,encode:n,decode:s=>rr(i(s))})},Mx=(t,e,r,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Fx=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},be=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Tn({prefix:e,name:t,encode(i){return Fx(i,n,r)},decode(i){return Mx(i,n,r,t)}});var Ux=Tn({prefix:"\0",name:"identity",encode:t=>_0(t),decode:t=>b0(t)});var tc={};Ke(tc,{base2:()=>Kx});var Kx=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rc={};Ke(rc,{base8:()=>Vx});var Vx=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nc={};Ke(nc,{base10:()=>qx});var qx=wr({prefix:"9",name:"base10",alphabet:"0123456789"});var ic={};Ke(ic,{base16:()=>$x,base16upper:()=>zx});var $x=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zx=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sc={};Ke(sc,{base32:()=>st,base32hex:()=>Wx,base32hexpad:()=>Xx,base32hexpadupper:()=>Zx,base32hexupper:()=>Qx,base32pad:()=>Gx,base32padupper:()=>Yx,base32upper:()=>Hx,base32z:()=>jx});var st=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hx=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gx=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yx=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wx=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qx=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xx=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zx=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jx=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var oc={};Ke(oc,{base36:()=>Jx,base36upper:()=>ew});var Jx=wr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ew=wr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ac={};Ke(ac,{base58btc:()=>Re,base58flickr:()=>tw});var Re=wr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tw=wr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cc={};Ke(cc,{base64:()=>Wr,base64pad:()=>rw,base64url:()=>nw,base64urlpad:()=>iw});var Wr=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rw=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nw=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iw=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uc={};Ke(uc,{base256emoji:()=>uw});var I0=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}"),sw=I0.reduce((t,e,r)=>(t[r]=e,t),[]),ow=I0.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aw(t){return t.reduce((e,r)=>(e+=sw[r],e),"")}function cw(t){let e=[];for(let r of t){let n=ow[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var uw=Tn({prefix:"\u{1F680}",name:"base256emoji",encode:aw,decode:cw});var dc={};Ke(dc,{sha256:()=>Ve,sha512:()=>Cw});var lw=T0,R0=128,fw=127,hw=~fw,dw=Math.pow(2,31);function T0(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dw;)e[r++]=t&255|R0,t/=128;for(;t&hw;)e[r++]=t&255|R0,t>>>=7;return e[r]=t|0,T0.bytes=r-n+1,e}var pw=lc,mw=128,C0=127;function lc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw lc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&C0)<<i:(o&C0)*Math.pow(2,i),i+=7}while(o>=mw);return lc.bytes=s-n,r}var yw=Math.pow(2,7),gw=Math.pow(2,14),xw=Math.pow(2,21),ww=Math.pow(2,28),vw=Math.pow(2,35),Ew=Math.pow(2,42),bw=Math.pow(2,49),_w=Math.pow(2,56),Sw=Math.pow(2,63),Aw=function(t){return t<yw?1:t<gw?2:t<xw?3:t<ww?4:t<vw?5:t<Ew?6:t<bw?7:t<_w?8:t<Sw?9:10},Iw={encode:lw,decode:pw,encodingLength:Aw},Rw=Iw,Ti=Rw;var Bi=(t,e=0)=>[Ti.decode(t,e),Ti.decode.bytes],Bn=(t,e,r=0)=>(Ti.encode(t,e,r),e),Ln=t=>Ti.encodingLength(t);var qt=(t,e)=>{let r=e.byteLength,n=Ln(t),i=n+Ln(r),s=new Uint8Array(i+r);return Bn(t,s,0),Bn(r,s,n),s.set(e,i),new Pn(t,r,e,s)},Qr=t=>{let e=rr(t),[r,n]=Bi(e),[i,s]=Bi(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Pn(r,i,o,e)},B0=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&E0(t.bytes,r.bytes)}},Pn=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var hc=({name:t,code:e,encode:r})=>new fc(t,e,r),fc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?qt(this.code,r):r.then(n=>qt(this.code,n))}else throw Error("Unknown type, must be binary type")}};var P0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Ve=hc({name:"sha2-256",code:18,encode:P0("SHA-256")}),Cw=hc({name:"sha2-512",code:19,encode:P0("SHA-512")});var pc={};Ke(pc,{identity:()=>vr});var D0=0,Tw="identity",N0=rr,Bw=t=>qt(D0,N0(t)),vr={code:D0,name:Tw,encode:N0,digest:Bw};var _S=new TextEncoder,SS=new TextDecoder;var k0=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Nw(r,mc(t),e||Re.encoder);default:return kw(r,mc(t),e||st.encoder)}};var O0=new WeakMap,mc=t=>{let e=O0.get(t);if(e==null){let r=new Map;return O0.set(t,r),r}return e},ue=class{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:r}=this;if(e!==Li)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Ow)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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:{let{code:e,digest:r}=this.multihash,n=qt(e,r);return ue.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(e){return ue.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&B0(e.multihash,n.multihash)}toString(e){return k0(this,e)}toJSON(){return{"/":k0(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof ue)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:s,bytes:o}=r;return new ue(n,i,s,o||M0(n,i,s.bytes))}else if(r[Mw]===!0){let{version:n,multihash:i,code:s}=r,o=Qr(i);return ue.create(n,s,o)}else return null}static create(e,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(e){case 0:{if(r!==Li)throw new Error(`Version 0 CID must use dag-pb (code: ${Li}) block encoding`);return new ue(e,r,n,n.bytes)}case 1:{let i=M0(e,r,n.bytes);return new ue(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Li,e)}static createV1(e,r){return ue.create(1,e,r)}static decode(e){let[r,n]=ue.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=ue.inspectBytes(e),n=r.size-r.multihashSize,i=rr(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new Pn(r.multihashCode,r.digestSize,s,i);return[r.version===0?ue.createV0(o):ue.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=Bi(e.subarray(r));return r+=h,f},i=n(),s=Li;if(i===18?(i=0,r=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),c=n(),u=r+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,i]=Dw(e,r),s=ue.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return mc(s).set(n,e),s}},Dw=(t,e)=>{switch(t[0]){case"Q":{let r=e||Re;return[Re.prefix,r.decode(`${Re.prefix}${t}`)]}case Re.prefix:{let r=e||Re;return[Re.prefix,r.decode(t)]}case st.prefix:{let r=e||st;return[st.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Nw=(t,e,r)=>{let{prefix:n}=r;if(n!==Re.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},kw=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},Li=112,Ow=18,M0=(t,e,r)=>{let n=Ln(t),i=n+Ln(e),s=new Uint8Array(i+r.byteLength);return Bn(t,s,0),Bn(e,s,n),s.set(r,i),s},Mw=Symbol.for("@ipld/js-cid/CID");var Er={...ec,...tc,...rc,...nc,...ic,...sc,...oc,...ac,...cc,...uc},NS={...dc,...pc};function Zr(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function nr(t=0){return globalThis.Buffer?.alloc!=null?Zr(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function St(t=0){return globalThis.Buffer?.allocUnsafe!=null?Zr(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function U0(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var F0=U0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),yc=U0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=St(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Fw={utf8:F0,"utf-8":F0,hex:Er.base16,latin1:yc,ascii:yc,binary:yc,...Er},Hs=Fw;function U(t,e="utf8"){let r=Hs[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zr(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var zc={};Ke(zc,{Ed25519PrivateKey:()=>rn,Ed25519PublicKey:()=>Fi,generateKeyPair:()=>y2,generateKeyPairFromSeed:()=>Hh,unmarshalEd25519PrivateKey:()=>p2,unmarshalEd25519PublicKey:()=>m2});function ve(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var Uw=V(zr(),1);var Fe=BigInt(0),X=BigInt(1),Sr=BigInt(2),Kw=BigInt(8),K0=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),de=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:K0,n:K0,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var H0=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Pi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GS=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),Vw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),qw=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),$w=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),zw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Y=class{constructor(e,r,n,i){this.x=e,this.y=r,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof ge))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(ge.ZERO)?Y.ZERO:new Y(e.x,e.y,X,A(e.x*e.y))}static toAffineBatch(e){let r=Yw(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){q0(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=A(r*a),u=A(s*i),l=A(n*a),f=A(o*i);return c===u&&l===f}negate(){return new Y(A(-this.x),this.y,this.z,A(-this.t))}double(){let{x:e,y:r,z:n}=this,{a:i}=de,s=A(e*e),o=A(r*r),a=A(Sr*A(n*n)),c=A(i*s),u=e+r,l=A(A(u*u)-s-o),f=c+o,h=f-a,d=c-o,p=A(l*h),m=A(f*d),y=A(l*d),g=A(h*f);return new Y(p,m,g,y)}add(e){q0(e);let{x:r,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=A((n-r)*(a+o)),f=A((n+r)*(a-o)),h=A(f-l);if(h===Fe)return this.double();let d=A(i*Sr*u),p=A(s*Sr*c),m=p+d,y=f+l,g=p-d,w=A(m*h),_=A(y*g),N=A(m*g),C=A(h*y);return new Y(w,_,C,N)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let r=1+256/e,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(Y.BASE)&&(r=ge.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&Ec.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=Y.normalizeZ(i),Ec.set(r,i)));let s=Y.ZERO,o=Y.BASE,a=1+256/n,c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);e>>=f,p>c&&(p-=l,e+=X);let m=d,y=d+Math.abs(p)-1,g=h%2!==0,w=p<0;p===0?o=o.add(V0(g,i[m])):s=s.add(V0(w,i[y]))}return Y.normalizeZ([s,o])[0]}multiply(e,r){return this.wNAF(Ys(e,de.l),r)}multiplyUnsafe(e){let r=Ys(e,de.l,!1),n=Y.BASE,i=Y.ZERO;if(r===Fe)return i;if(this.equals(i)||r===X)return this;if(this.equals(n))return this.wNAF(r);let s=i,o=this;for(;r>Fe;)r&X&&(s=s.add(o)),o=o.double(),r>>=X;return s}isSmallOrder(){return this.multiplyUnsafe(de.h).equals(Y.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(de.l/Sr).double();return de.l%Sr&&(e=e.add(this)),e.equals(Y.ZERO)}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(Y.ZERO);e==null&&(e=s?Kw:Ws(i));let o=A(r*e),a=A(n*e),c=A(i*e);if(s)return ge.ZERO;if(c!==X)throw new Error("invZ was invalid");return new ge(o,a)}fromRistrettoBytes(){xc()}toRistrettoBytes(){xc()}fromRistrettoHash(){xc()}};Y.BASE=new Y(de.Gx,de.Gy,X,A(de.Gx*de.Gy));Y.ZERO=new Y(Fe,X,X,Fe);function V0(t,e){let r=e.negate();return t?r:e}function q0(t){if(!(t instanceof Y))throw new TypeError("ExtendedPoint expected")}function gc(t){if(!(t instanceof tt))throw new TypeError("RistrettoPoint expected")}function xc(){throw new Error("Legacy method: switch to RistrettoPoint")}var tt=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:r}=de,n=A(Pi*e*e),i=A((n+X)*$w),s=BigInt(-1),o=A((s-r*n)*A(n+r)),{isValid:a,value:c}=_c(i,o),u=A(c*e);_r(u)||(u=A(-u)),a||(c=u),a||(s=n);let l=A(s*(n-X)*zw-o),f=c*c,h=A((c+c)*o),d=A(l*Vw),p=A(X-f),m=A(X+f);return new Y(A(h*m),A(p*d),A(d*m),A(h*p))}static hashToCurve(e){e=Ar(e,64);let r=wc(e.slice(0,32)),n=this.calcElligatorRistrettoMap(r),i=wc(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new tt(n.add(s))}static fromHex(e){e=Ar(e,32);let{a:r,d:n}=de,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=wc(e);if(!Qw(Di(s),e)||_r(s))throw new Error(i);let o=A(s*s),a=A(X+r*o),c=A(X-r*o),u=A(a*a),l=A(c*c),f=A(r*n*u-l),{isValid:h,value:d}=z0(A(f*l)),p=A(d*c),m=A(d*p*f),y=A((s+s)*p);_r(y)&&(y=A(-y));let g=A(a*m),w=A(y*g);if(!h||_r(w)||g===Fe)throw new Error(i);return new tt(new Y(y,g,X,w))}toRawBytes(){let{x:e,y:r,z:n,t:i}=this.ep,s=A(A(n+r)*A(n-r)),o=A(e*r),a=A(o*o),{value:c}=z0(A(s*a)),u=A(c*s),l=A(c*o),f=A(u*l*i),h;if(_r(i*f)){let p=A(r*Pi),m=A(e*Pi);e=p,r=m,h=A(u*qw)}else h=l;_r(e*f)&&(r=A(-r));let d=A((n-r)*h);return _r(d)&&(d=A(-d)),Di(d)}toHex(){return Ni(this.toRawBytes())}toString(){return this.toHex()}equals(e){gc(e);let r=this.ep,n=e.ep,i=A(r.x*n.y)===A(r.y*n.x),s=A(r.y*n.y)===A(r.x*n.x);return i||s}add(e){return gc(e),new tt(this.ep.add(e.ep))}subtract(e){return gc(e),new tt(this.ep.subtract(e.ep))}multiply(e){return new tt(this.ep.multiply(e))}multiplyUnsafe(e){return new tt(this.ep.multiplyUnsafe(e))}};tt.BASE=new tt(Y.BASE);tt.ZERO=new tt(Y.ZERO);var Ec=new WeakMap,ge=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Ec.delete(this)}static fromHex(e,r=!0){let{d:n,P:i}=de;e=Ar(e,32);let s=e.slice();s[31]=e[31]&-129;let o=ki(s);if(r&&o>=i)throw new Error("Expected 0 < hex < P");if(!r&&o>=H0)throw new Error("Expected 0 < hex < 2**256");let a=A(o*o),c=A(a-X),u=A(n*a+X),{isValid:l,value:f}=_c(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&X)===X;return(e[31]&128)!==0!==h&&(f=A(-f)),new ge(f,o)}static async fromPrivateKey(e){return(await Qs(e)).point}toRawBytes(){let e=Di(this.y);return e[31]|=this.x&X?128:0,e}toHex(){return Ni(this.toRawBytes())}toX25519(){let{y:e}=this,r=A((X+e)*Ws(X-e));return Di(r)}isTorsionFree(){return Y.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new ge(A(-this.x),this.y)}add(e){return Y.fromAffine(this).add(Y.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Y.fromAffine(this).multiply(e,this).toAffine()}};ge.BASE=new ge(de.Gx,de.Gy);ge.ZERO=new ge(Fe,X);var jr=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=Ar(e,64),n=ge.fromHex(r.slice(0,32),!1),i=ki(r.slice(32,64));return new jr(n,i)}assertValidity(){let{r:e,s:r}=this;if(!(e instanceof ge))throw new Error("Expected Point instance");return Ys(r,de.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Di(this.s),32),e}toHex(){return Ni(this.toRawBytes())}};function $0(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var Hw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ni(t){if(!(t instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Hw[t[r]];return e}function bc(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function G0(t){let r=t.toString(16).padStart(64,"0");return bc(r)}function Di(t){return G0(t).reverse()}function _r(t){return(A(t)&X)===X}function ki(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+Ni(Uint8Array.from(t).reverse()))}var Gw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function wc(t){return A(ki(t)&Gw)}function A(t,e=de.P){let r=t%e;return r>=Fe?r:e+r}function Ws(t,e=de.P){if(t===Fe||e<=Fe)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=A(t,e),n=e,i=Fe,s=X,o=X,a=Fe;for(;r!==Fe;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==X)throw new Error("invert: does not exist");return A(i,e)}function Yw(t,e=de.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===Fe?s:(r[a]=s,A(s*o,e)),X),i=Ws(n,e);return t.reduceRight((s,o,a)=>o===Fe?s:(r[a]=A(s*r[a],e),A(s*o,e)),i),r}function $t(t,e){let{P:r}=de,n=t;for(;e-- >Fe;)n*=n,n%=r;return n}function Ww(t){let{P:e}=de,r=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=t*t%e*t%e,u=$t(c,Sr)*c%e,l=$t(u,X)*t%e,f=$t(l,r)*l%e,h=$t(f,n)*f%e,d=$t(h,i)*h%e,p=$t(d,s)*d%e,m=$t(p,o)*p%e,y=$t(m,o)*p%e,g=$t(y,n)*f%e;return{pow_p_5_8:$t(g,Sr)*t%e,b2:c}}function _c(t,e){let r=A(e*e*e),n=A(r*r*e),i=Ww(t*n).pow_p_5_8,s=A(t*r*i),o=A(e*s*s),a=s,c=A(s*Pi),u=o===t,l=o===A(-t),f=o===A(-t*Pi);return u&&(s=a),(l||f)&&(s=c),_r(s)&&(s=A(-s)),{isValid:u||l,value:s}}function z0(t){return _c(X,t)}function Gs(t){return A(ki(t),de.l)}function Qw(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Ar(t,e){let r=t instanceof Uint8Array?Uint8Array.from(t):bc(t);if(typeof e=="number"&&r.length!==e)throw new Error(`Expected ${e} bytes`);return r}function Ys(t,e,r=!0){if(!e)throw new TypeError("Specify max value");if(typeof t=="number"&&Number.isSafeInteger(t)&&(t=BigInt(t)),typeof t=="bigint"&&t<e){if(r){if(Fe<t)return t}else if(Fe<=t)return t}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function Xw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Zw(t){if(t=typeof t=="bigint"||typeof t=="number"?G0(Ys(t,H0)):Ar(t),t.length!==32)throw new Error("Expected 32 bytes");return t}function jw(t){let e=Xw(t.slice(0,32)),r=t.slice(32,64),n=Gs(e),i=ge.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:r,scalar:n,point:i,pointBytes:s}}var vc;async function Qs(t){return jw(await Ir.sha512(Zw(t)))}async function Sc(t){return(await Qs(t)).pointBytes}async function Y0(t,e){t=Ar(t);let{prefix:r,scalar:n,pointBytes:i}=await Qs(e),s=Gs(await Ir.sha512(r,t)),o=ge.BASE.multiply(s),a=Gs(await Ir.sha512(o.toRawBytes(),i,t)),c=A(s+a*n,de.l);return new jr(o,c).toRawBytes()}function Jw(t,e,r){e=Ar(e),r instanceof ge||(r=ge.fromHex(r,!1));let{r:n,s:i}=t instanceof jr?t.assertValidity():jr.fromHex(t),s=Y.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:r,msg:e}}function e2(t,e,r,n){let i=Gs(n),s=Y.fromAffine(t).multiplyUnsafe(i);return Y.fromAffine(e).add(s).subtract(r).multiplyUnsafe(de.h).equals(Y.ZERO)}async function W0(t,e,r){let{r:n,SB:i,msg:s,pub:o}=Jw(t,e,r),a=await Ir.sha512(n.toRawBytes(),o.toRawBytes(),s);return e2(o,n,i,a)}ge.BASE._setWindowSize(8);var br={node:Uw,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Ir={bytesToHex:Ni,hexToBytes:bc,concatBytes:$0,getExtendedPublicKey:Qs,mod:A,invert:Ws,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:t=>{if(t=Ar(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return A(ki(t),de.l-X)+X},randomBytes:(t=32)=>{if(br.web)return br.web.getRandomValues(new Uint8Array(t));if(br.node){let{randomBytes:e}=br.node;return new Uint8Array(e(t).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ir.randomBytes(32),sha512:async(...t)=>{let e=$0(...t);if(br.web){let r=await br.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(r)}else{if(br.node)return Uint8Array.from(br.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(t=8,e=ge.BASE){let r=e.equals(ge.BASE)?e:new ge(e.x,e.y);return r._setWindowSize(t),r.multiply(Sr),r},sha512Sync:void 0};Object.defineProperties(Ir,{sha512Sync:{configurable:!1,get(){return vc},set(t){vc||(vc=t)}}});var Dn=32,ir=64,Xs=32;async function Q0(){let t=Ir.randomPrivateKey(),e=await Sc(t);return{privateKey:J0(t,e),publicKey:e}}async function X0(t){if(t.length!==Xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=await Sc(e);return{privateKey:J0(e,r),publicKey:r}}async function Z0(t,e){let r=t.subarray(0,Xs);return Y0(e,r)}async function j0(t,e,r){return W0(e,r,t)}function J0(t,e){let r=new Uint8Array(ir);for(let n=0;n<Xs;n++)r[n]=t[n],r[Xs+n]=e[n];return r}function Ce(t,e){e==null&&(e=t.reduce((i,s)=>i+s.length,0));let r=St(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Zr(r)}var rt={get(t=globalThis){let e=t.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Ac={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Zs(t){let e=t?.algorithm??"AES-GCM",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"SHA-256",s=t?.saltLength??16,o=t?.iterations??32767,a=rt.get();r*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof h=="string"&&(h=U(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,_,{name:e,length:r},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,_,{name:e,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,f);return Ce([d,m.iv,new Uint8Array(g)])}async function u(f,h){let d=f.subarray(0,s),p=f.subarray(s,s+n),m=f.subarray(s+n),y={name:e,iv:p};typeof h=="string"&&(h=U(h));let g;if(h.length===0)try{let _={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},N=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(_,N,{name:e,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Ac,{name:"AES-GCM"},!0,["decrypt"])}else{let _={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},N=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(_,N,{name:e,length:r},!0,["decrypt"])}let w=await a.subtle.decrypt(y,g,m);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function Nn(t,e){let n=await Zs().encrypt(t,e);return Wr.encode(n)}var Fc=V(Bc(),1),Vh=V(Dh(),1),qh=V(en(),1),Uc=V(Mc(),1),$h=V(Kh(),1);function f2(){qh.default._configure(),Fc.default._configure(Vh.default),Uc.default._configure($h.default)}f2();var zh=["uint64","int64","sint64","fixed64","sfixed64"];function h2(t){for(let e of zh){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function Kc(t){return h2(new Fc.default(t))}function d2(t){for(let e of zh){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function Vc(){return d2(Uc.default.create())}function qe(t,e){let r=Kc(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function $e(t,e){let r=Vc();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var On;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(On||(On={}));function ro(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function qc(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return ro("enum",On.VARINT,r,n)}function ze(t,e){return ro("message",On.LENGTH_DELIMITED,t,e)}var xe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(xe||(xe={}));var $c;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})($c||($c={}));(function(t){t.codec=()=>qc($c)})(xe||(xe={}));var Gt;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),xe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=xe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Gt||(Gt={}));var Yt;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),xe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=xe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Yt||(Yt={}));var Fi=class{_key;constructor(e){this._key=Mn(e,Dn)}async verify(e,r){return j0(this._key,r,e)}marshal(){return this._key}get bytes(){return Gt.encode({Type:xe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},rn=class{_key;_publicKey;constructor(e,r){this._key=Mn(e,ir),this._publicKey=Mn(r,Dn)}async sign(e){return Z0(this._key,e)}get public(){return new Fi(this._publicKey)}marshal(){return this._key}get bytes(){return Yt.encode({Type:xe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=vr.digest(this.public.bytes);return Re.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function p2(t){if(t.length>ir){t=Mn(t,ir+Dn);let n=t.subarray(0,ir),i=t.subarray(ir,t.length);return new rn(n,i)}t=Mn(t,ir);let e=t.subarray(0,ir),r=t.subarray(Dn);return new rn(e,r)}function m2(t){return t=Mn(t,Dn),new Fi(t)}async function y2(){let{privateKey:t,publicKey:e}=await Q0();return new rn(t,e)}async function Hh(t){let{privateKey:e,publicKey:r}=await X0(t);return new rn(e,r)}function Mn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}function $(t,e="utf8"){let r=Hs[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var UA=V(Ie(),1),KA=V(Us(),1),Gh=V(se(),1);function Rt(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Ce([new Uint8Array(e-r.length),r])}return $(r,"base64url")}function ot(t){let e=Yh(t);return new Gh.default.jsbn.BigInteger($(e,"base16"),16)}function Yh(t,e){let r=U(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Ce([new Uint8Array(e-r.length),r])}return r}var g2={"P-256":256,"P-384":384,"P-521":521},x2=Object.keys(g2),ZA=x2.join(" / ");async function Wh(t,e){let r=Wr.decode(t);return Zs().decrypt(r,e)}var tu={};Ke(tu,{RsaPrivateKey:()=>zn,RsaPublicKey:()=>Hi,fromJwk:()=>$2,generateKeyPair:()=>z2,unmarshalRsaPrivateKey:()=>V2,unmarshalRsaPublicKey:()=>q2});var zi=V(se(),1);var kI=V(ed(),1);var v2=V(zr(),1);var Z=BigInt(0),me=BigInt(1),Br=BigInt(2),Vi=BigInt(3),td=BigInt(8),_e=Object.freeze({a:Z,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:me,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),rd=(t,e)=>(t+e/Br)/e,io={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){let{n:e}=_e,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-me*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=rd(s*t,e),c=rd(-n*t,e),u=P(t-a*r-c*i,e),l=P(-a*n-c*s,e),f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}},Ct=32,Kn=32,E2=32,nd=Ct+1,id=2*Ct+1;function sd(t){let{a:e,b:r}=_e,n=P(t*t),i=P(n*t);return P(i+e*t+r)}var so=_e.a===Z,co=class extends Error{constructor(e){super(e)}};function od(t){if(!(t instanceof te))throw new TypeError("JacobianPoint expected")}var te=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof re))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(re.ZERO)?te.ZERO:new te(e.x,e.y,me)}static toAffineBatch(e){let r=I2(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return te.toAffineBatch(e).map(te.fromAffine)}equals(e){od(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=P(i*i),u=P(a*a),l=P(r*u),f=P(s*c),h=P(P(n*a)*u),d=P(P(o*i)*c);return l===f&&h===d}negate(){return new te(this.x,P(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=P(e*e),s=P(r*r),o=P(s*s),a=e+s,c=P(Br*(P(a*a)-i-o)),u=P(Vi*i),l=P(u*u),f=P(l-Br*c),h=P(u*(c-f)-td*o),d=P(Br*r*n);return new te(f,h,d)}add(e){od(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Z||o===Z)return this;if(r===Z||n===Z)return e;let c=P(i*i),u=P(a*a),l=P(r*u),f=P(s*c),h=P(P(n*a)*u),d=P(P(o*i)*c),p=P(f-l),m=P(d-h);if(p===Z)return m===Z?this.double():te.ZERO;let y=P(p*p),g=P(p*y),w=P(l*y),_=P(m*m-g-Br*w),N=P(m*(w-_)-h*g),C=P(i*a*p);return new te(_,N,C)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=te.ZERO;if(typeof e=="bigint"&&e===Z)return r;let n=ud(e);if(n===me)return this;if(!so){let f=r,h=this;for(;n>Z;)n&me&&(f=f.add(h)),h=h.double(),n>>=me;return f}let{k1neg:i,k1:s,k2neg:o,k2:a}=io.splitScalar(n),c=r,u=r,l=this;for(;s>Z||a>Z;)s&me&&(c=c.add(l)),a&me&&(u=u.add(l)),l=l.double(),s>>=me,a>>=me;return i&&(c=c.negate()),o&&(u=u.negate()),u=new te(P(u.x*io.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let r=so?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(te.BASE)&&(r=re.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&Wc.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=te.normalizeZ(i),Wc.set(r,i)));let s=te.ZERO,o=te.BASE,a=1+(so?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);e>>=f,p>c&&(p-=l,e+=me);let m=d,y=d+Math.abs(p)-1,g=h%2!==0,w=p<0;p===0?o=o.add(oo(g,i[m])):s=s.add(oo(w,i[y]))}return{p:s,f:o}}multiply(e,r){let n=ud(e),i,s;if(so){let{k1neg:o,k1:a,k2neg:c,k2:u}=io.splitScalar(n),{p:l,f}=this.wNAF(a,r),{p:h,f:d}=this.wNAF(u,r);l=oo(o,l),h=oo(c,h),h=new te(P(h.x*io.beta),h.y,h.z),i=l.add(h),s=f.add(d)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return te.normalizeZ([i,s])[0]}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(te.ZERO);e==null&&(e=s?td:$n(i));let o=e,a=P(o*o),c=P(a*o),u=P(r*a),l=P(n*c),f=P(i*o);if(s)return re.ZERO;if(f!==me)throw new Error("invZ was invalid");return new re(u,l)}};te.BASE=new te(_e.Gx,_e.Gy,me);te.ZERO=new te(Z,me,Z);function oo(t,e){let r=e.negate();return t?r:e}var Wc=new WeakMap,re=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Wc.delete(this)}hasEvenY(){return this.y%Br===Z}static fromCompressedHex(e){let r=e.length===32,n=Lr(r?e:e.subarray(1));if(!Yc(n))throw new Error("Point is not on curve");let i=sd(n),s=A2(i),o=(s&me)===me;r?o&&(s=P(-s)):(e[0]&1)===1!==o&&(s=P(-s));let a=new re(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=Lr(e.subarray(1,Ct+1)),n=Lr(e.subarray(Ct+1,Ct*2+1)),i=new re(r,n);return i.assertValidity(),i}static fromHex(e){let r=qn(e),n=r.length,i=r[0];if(n===Ct)return this.fromCompressedHex(r);if(n===nd&&(i===2||i===3))return this.fromCompressedHex(r);if(n===id&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-${nd} compressed bytes or ${id} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return re.BASE.multiply(lo(e))}static fromSignature(e,r,n){let{r:i,s}=ld(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=Zc(qn(e)),{n:a}=_e,c=n===2||n===3?i+a:i,u=$n(c,a),l=P(-o*u,a),f=P(s*u,a),h=n&1?"03":"02",d=re.fromHex(h+Fn(c)),p=re.BASE.multiplyAndAddUnsafe(d,l,f);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return sn(this.toHex(e))}toHex(e=!1){let r=Fn(this.x);return e?`${this.hasEvenY()?"02":"03"}${r}`:`04${r}${Fn(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!Yc(r)||!Yc(n))throw new Error(e);let i=P(n*n),s=sd(r);if(P(i-s)!==Z)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new re(this.x,P(-this.y))}double(){return te.fromAffine(this).double().toAffine()}add(e){return te.fromAffine(this).add(te.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return te.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let i=te.fromAffine(this),s=r===Z||r===me||this!==re.BASE?i.multiplyUnsafe(r):i.multiply(r),o=te.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(te.ZERO)?void 0:a.toAffine()}};re.BASE=new re(_e.Gx,_e.Gy);re.ZERO=new re(Z,Z);function ad(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function cd(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${Vn(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Lr(r),left:t.subarray(e+2)}}function b2(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${Vn(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=cd(t.subarray(2)),{data:n,left:i}=cd(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${Vn(i)}`);return{r:e,s:n}}var Wt=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?Vn(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Wt(uo(i.slice(0,64)),uo(i.slice(64,128)))}static fromDER(e){let r=e instanceof Uint8Array;if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=b2(r?e:sn(e));return new Wt(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!$i(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!$i(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=_e.n>>me;return this.s>e}normalizeS(){return this.hasHighS()?new Wt(this.r,P(-this.s,_e.n)):this}toDERRawBytes(){return sn(this.toDERHex())}toDERHex(){let e=ad(Ki(this.s)),r=ad(Ki(this.r)),n=e.length/2,i=r.length/2,s=Ki(n),o=Ki(i);return`30${Ki(i+n+4)}02${o}${r}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return sn(this.toCompactHex())}toCompactHex(){return Fn(this.r)+Fn(this.s)}};function Tr(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var _2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Vn(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;r<t.length;r++)e+=_2[t[r]];return e}var S2=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Fn(t){if(typeof t!="bigint")throw new Error("Expected bigint");if(!(Z<=t&&t<S2))throw new Error("Expected number 0 <= n < 2^256");return t.toString(16).padStart(64,"0")}function Qc(t){let e=sn(Fn(t));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function Ki(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function uo(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function sn(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function Lr(t){return uo(Vn(t))}function qn(t){return t instanceof Uint8Array?Uint8Array.from(t):sn(t)}function ud(t){if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if(typeof t=="bigint"&&$i(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function P(t,e=_e.P){let r=t%e;return r>=Z?r:e+r}function wt(t,e){let{P:r}=_e,n=t;for(;e-- >Z;)n*=n,n%=r;return n}function A2(t){let{P:e}=_e,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,l=wt(u,Vi)*u%e,f=wt(l,Vi)*u%e,h=wt(f,Br)*c%e,d=wt(h,n)*h%e,p=wt(d,i)*d%e,m=wt(p,o)*p%e,y=wt(m,a)*m%e,g=wt(y,o)*p%e,w=wt(g,Vi)*u%e,_=wt(w,s)*d%e,N=wt(_,r)*c%e,C=wt(N,Br);if(C*C%e!==t)throw new Error("Cannot find square root");return C}function $n(t,e=_e.P){if(t===Z||e<=Z)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=P(t,e),n=e,i=Z,s=me,o=me,a=Z;for(;r!==Z;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==me)throw new Error("invert: does not exist");return P(i,e)}function I2(t,e=_e.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===Z?s:(r[a]=s,P(s*o,e)),me),i=$n(n,e);return t.reduceRight((s,o,a)=>o===Z?s:(r[a]=P(s*r[a],e),P(s*o,e)),i),r}function R2(t){let e=t.length*8-Kn*8,r=Lr(t);return e>0?r>>BigInt(e):r}function Zc(t,e=!1){let r=R2(t);if(e)return r;let{n}=_e;return r>=n?r-n:r}var Un,qi,Xc=class{constructor(e,r){if(this.hashLen=e,this.qByteLen=r,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof r!="number"||r<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Tt.hmacSha256(this.k,...e)}hmacSync(...e){return qi(this.k,...e)}checkSync(){if(typeof qi!="function")throw new co("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return Tr(...r)}generateSync(){this.checkSync(),this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return Tr(...r)}};function $i(t){return Z<t&&t<_e.n}function Yc(t){return Z<t&&t<_e.P}function C2(t,e,r,n=!0){let{n:i}=_e,s=Zc(t,!0);if(!$i(s))return;let o=$n(s,i),a=re.BASE.multiply(s),c=P(a.x,i);if(c===Z)return;let u=P(o*P(e+r*c,i),i);if(u===Z)return;let l=new Wt(c,u),f=(a.x===l.r?0:2)|Number(a.y&me);return n&&l.hasHighS()&&(l=l.normalizeS(),f^=1),{sig:l,recovery:f}}function lo(t){let e;if(typeof t=="bigint")e=t;else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==2*Kn)throw new Error("Expected 32 bytes of private key");e=uo(t)}else if(t instanceof Uint8Array){if(t.length!==Kn)throw new Error("Expected 32 bytes of private key");e=Lr(t)}else throw new TypeError("Expected valid private key");if(!$i(e))throw new Error("Expected private key: 0 < key < n");return e}function T2(t){return t instanceof re?(t.assertValidity(),t):re.fromHex(t)}function ld(t){if(t instanceof Wt)return t.assertValidity(),t;try{return Wt.fromDER(t)}catch{return Wt.fromCompact(t)}}function jc(t,e=!1){return re.fromPrivateKey(t).toRawBytes(e)}function fd(t){let e=t.length>Ct?t.slice(0,Ct):t;return Lr(e)}function B2(t){let e=fd(t),r=P(e,_e.n);return hd(r<Z?e:r)}function hd(t){return Qc(t)}function L2(t,e,r){if(t==null)throw new Error(`sign: expected valid message hash, not "${t}"`);let n=qn(t),i=lo(e),s=[hd(i),B2(n)];if(r!=null){r===!0&&(r=Tt.randomBytes(Ct));let c=qn(r);if(c.length!==Ct)throw new Error(`sign: Expected ${Ct} bytes of extra data`);s.push(c)}let o=Tr(...s),a=fd(n);return{seed:o,m:a,d:i}}function P2(t,e){let{sig:r,recovery:n}=t,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}async function dd(t,e,r={}){let{seed:n,m:i,d:s}=L2(t,e,r.extraEntropy),o=new Xc(E2,Kn);await o.reseed(n);let a;for(;!(a=C2(await o.generate(),i,s,r.canonical));)await o.reseed();return P2(a,r)}var D2={strict:!0};function pd(t,e,r,n=D2){let i;try{i=ld(t),e=qn(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=Zc(e),c;try{c=T2(r)}catch{return!1}let{n:u}=_e,l=$n(o,u),f=P(a*l,u),h=P(s*l,u),d=re.BASE.multiplyAndAddUnsafe(c,f,h);return d?P(d.x,u)===s:!1}re.BASE._setWindowSize(8);var at={node:v2,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var ao={},Tt={bytesToHex:Vn,hexToBytes:sn,concatBytes:Tr,mod:P,invert:$n,isValidPrivateKey(t){try{return lo(t),!0}catch{return!1}},_bigintTo32Bytes:Qc,_normalizePrivateKey:lo,hashToPrivateKey:t=>{t=qn(t);let e=Kn+8;if(t.length<e||t.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let r=P(Lr(t),_e.n-me)+me;return Qc(r)},randomBytes:(t=32)=>{if(at.web)return at.web.getRandomValues(new Uint8Array(t));if(at.node){let{randomBytes:e}=at.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Tt.hashToPrivateKey(Tt.randomBytes(Kn+8)),precompute(t=8,e=re.BASE){let r=e===re.BASE?e:new re(e.x,e.y);return r._setWindowSize(t),r.multiply(Vi),r},sha256:async(...t)=>{if(at.web){let e=await at.web.subtle.digest("SHA-256",Tr(...t));return new Uint8Array(e)}else if(at.node){let{createHash:e}=at.node,r=e("sha256");return t.forEach(n=>r.update(n)),Uint8Array.from(r.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(at.web){let r=await at.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Tr(...e),i=await at.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(at.node){let{createHmac:r}=at.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let r=ao[t];if(r===void 0){let n=await Tt.sha256(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Tr(n,n),ao[t]=r}return Tt.sha256(r,...e)},taggedHashSync:(t,...e)=>{if(typeof Un!="function")throw new co("sha256Sync is undefined, you need to set it");let r=ao[t];if(r===void 0){let n=Un(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Tr(n,n),ao[t]=r}return Un(r,...e)},_JacobianPoint:te};Object.defineProperties(Tt,{sha256Sync:{configurable:!1,get(){return Un},set(t){Un||(Un=t)}},hmacSha256Sync:{configurable:!1,get(){return qi},set(t){qi||(qi=t)}}});function on(t){if(isNaN(t)||t<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Tt.randomBytes(t)}var gI=V(qs(),1),Jc=V(se(),1);function md(t,e){return e.map(r=>ot(t[r]))}function yd(t){return Jc.default.pki.setRsaPrivateKey(...md(t,["n","e","d","p","q","dp","dq","qi"]))}function gd(t){return Jc.default.pki.setRsaPublicKey(...md(t,["n","e"]))}var an={};Ke(an,{jwkToPkcs1:()=>O2,jwkToPkix:()=>F2,pkcs1ToJwk:()=>k2,pkixToJwk:()=>M2});var vI=V(Ii(),1),EI=V(qs(),1);var sr=V(se(),1);function k2(t){let e=sr.default.asn1.fromDer($(t,"ascii")),r=sr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Rt(r.n),e:Rt(r.e),d:Rt(r.d),p:Rt(r.p),q:Rt(r.q),dp:Rt(r.dP),dq:Rt(r.dQ),qi:Rt(r.qInv),alg:"RS256"}}function O2(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=sr.default.pki.privateKeyToAsn1({n:ot(t.n),e:ot(t.e),d:ot(t.d),p:ot(t.p),q:ot(t.q),dP:ot(t.dp),dQ:ot(t.dq),qInv:ot(t.qi)});return U(sr.default.asn1.toDer(e).getBytes(),"ascii")}function M2(t){let e=sr.default.asn1.fromDer($(t,"ascii")),r=sr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Rt(r.n),e:Rt(r.e)}}function F2(t){if(t.n==null||t.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=sr.default.pki.publicKeyToAsn1({n:ot(t.n),e:ot(t.e)});return U(sr.default.asn1.toDer(e).getBytes(),"ascii")}async function xd(t){let e=await rt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Ed(e);return{privateKey:r[0],publicKey:r[1]}}async function eu(t){let r=[await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await U2(t)],n=await Ed({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function wd(t,e){let r=await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function vd(t,e,r){let n=await rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)}async function Ed(t){if(t.privateKey==null||t.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([rt.get().subtle.exportKey("jwk",t.privateKey),rt.get().subtle.exportKey("jwk",t.publicKey)])}async function U2(t){return rt.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function bd(t,e,r,n){let i=e?gd(t):yd(t),s=$(Uint8Array.from(r),"ascii"),o=n(s,i);return U(o,"ascii")}function _d(t,e){return bd(t,!0,e,(r,n)=>n.encrypt(r))}function Sd(t,e){return bd(t,!1,e,(r,n)=>n.decrypt(r))}var Hi=class{_key;constructor(e){this._key=e}async verify(e,r){return vd(this._key,r,e)}marshal(){return an.jwkToPkix(this._key)}get bytes(){return Gt.encode({Type:xe.RSA,Data:this.marshal()}).subarray()}encrypt(e){return _d(this._key,e)}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},zn=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return on(16)}async sign(e){return wd(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Hi(this._publicKey)}decrypt(e){return Sd(this._key,e)}marshal(){return an.jwkToPkcs1(this._key)}get bytes(){return Yt.encode({Type:xe.RSA,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new zi.default.util.ByteBuffer(this.marshal()),i=zi.default.asn1.fromDer(n),s=zi.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return zi.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function V2(t){let e=an.pkcs1ToJwk(t),r=await eu(e);return new zn(r.privateKey,r.publicKey)}function q2(t){let e=an.pkixToJwk(t);return new Hi(e)}async function $2(t){let e=await eu(t);return new zn(e.privateKey,e.publicKey)}async function z2(t){let e=await xd(t);return new zn(e.privateKey,e.publicKey)}var nu={};Ke(nu,{Secp256k1PrivateKey:()=>Yi,Secp256k1PublicKey:()=>Gi,generateKeyPair:()=>W2,unmarshalSecp256k1PrivateKey:()=>G2,unmarshalSecp256k1PublicKey:()=>Y2});function Ad(){return Tt.randomPrivateKey()}async function Id(t,e){let{digest:r}=await Ve.digest(e);try{return await dd(r,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}async function Rd(t,e,r){try{let{digest:n}=await Ve.digest(r);return pd(e,n,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function Cd(t){return re.fromHex(t).toRawBytes(!0)}function Td(t){try{jc(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ru(t){try{re.fromHex(t)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Bd(t){try{return jc(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Gi=class{_key;constructor(e){ru(e),this._key=e}async verify(e,r){return Rd(this._key,r,e)}marshal(){return Cd(this._key)}get bytes(){return Gt.encode({Type:xe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}},Yi=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??Bd(e),Td(this._key),ru(this._publicKey)}async sign(e){return Id(this._key,e)}get public(){return new Gi(this._publicKey)}marshal(){return this._key}get bytes(){return Yt.encode({Type:xe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ve(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ve.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Nn(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function G2(t){return new Yi(t)}function Y2(t){return new Gi(t)}async function W2(){let t=Ad();return new Yi(t)}var or={rsa:tu,ed25519:zc,secp256k1:nu};function iu(t){let e=Object.keys(or).join(" / ");return new E(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function su(t){if(t=t.toLowerCase(),t==="rsa"||t==="ed25519"||t==="secp256k1")return or[t];throw iu(t)}async function ho(t,e){return su(t).generateKeyPair(e??2048)}function cn(t){let e=Gt.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case xe.RSA:return or.rsa.unmarshalRsaPublicKey(r);case xe.Ed25519:return or.ed25519.unmarshalEd25519PublicKey(r);case xe.Secp256k1:return or.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw iu(e.Type??"RSA")}}function ou(t,e){return e=(e??"rsa").toLowerCase(),su(e),t.bytes}async function Hn(t){let e=Yt.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case xe.RSA:return or.rsa.unmarshalRsaPrivateKey(r);case xe.Ed25519:return or.ed25519.unmarshalEd25519PrivateKey(r);case xe.Secp256k1:return or.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw iu(e.Type??"RSA")}}function Ld(t,e){return e=(e??"rsa").toLowerCase(),su(e),t.bytes}async function Wi(t,e){try{let i=await Wh(t,e);return await Hn(i)}catch{}let r=fo.default.pki.decryptRsaPrivateKey(t,e);if(r===null)throw new E("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=fo.default.asn1.toDer(fo.default.pki.privateKeyToAsn1(r));return n=U(n.getBytes(),"ascii"),or.rsa.unmarshalRsaPrivateKey(n)}var au=Symbol.for("@libp2p/content-routing");var cu=Symbol.for("@libp2p/peer-discovery");var uu=Symbol.for("@libp2p/peer-routing");var Qi=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new fu(e,r))}},lu=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},fu=globalThis.CustomEvent??lu;var ut=V(du(),1);ut.default.formatters.b=t=>t==null?"undefined":Re.baseEncode(t);ut.default.formatters.t=t=>t==null?"undefined":st.baseEncode(t);ut.default.formatters.m=t=>t==null?"undefined":Wr.baseEncode(t);ut.default.formatters.p=t=>t==null?"undefined":t.toString();ut.default.formatters.c=t=>t==null?"undefined":t.toString();ut.default.formatters.k=t=>t==null?"undefined":t.toString();ut.default.formatters.a=t=>t==null?"undefined":t.toString();function cv(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function G(t){let e=cv(`${t}:trace`);return ut.default.enabled(`${t}:trace`)&&ut.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,ut.default)(`${t}:trace`)),Object.assign((0,ut.default)(t),{error:(0,ut.default)(`${t}:error`),trace:e})}var sp=V($d(),1);var jd=V(Zd(),1),Pr=jd.default;var xo=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var ar="/",Jd=new TextEncoder().encode(ar),wo=Jd[0],Se=class{_buf;constructor(e,r){if(typeof e=="string")this._buf=U(e);else if(e instanceof Uint8Array)this._buf=e;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]!==wo)throw new Error("Invalid key")}toString(e="utf8"){return $(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Se(e.join(ar))}static random(){return new Se(xo().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new Se(e):typeof e.uint8Array=="function"?new Se(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Jd),this._buf[0]!==wo){let e=new Uint8Array(this._buf.byteLength+1);e.fill(wo,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===wo;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let s=r[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return r.length<n.length}reverse(){return Se.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ar).slice(1)}type(){return Iv(this.baseNamespace())}name(){return Rv(this.baseNamespace())}instance(e){return new Se(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ar)||(e+=ar),e+=this.type(),new Se(e)}parent(){let e=this.list();return e.length===1?new Se(ar):new Se(e.slice(0,-1).join(ar))}child(e){return this.toString()===ar?e:e.toString()===ar?this:new Se(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return Se.withNamespaces([...this.namespaces(),...Cv(e.map(r=>r.namespaces()))])}};function Iv(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Rv(t){let e=t.split(":");return e[e.length-1]}function Cv(t){return[].concat(...t)}var j;(function(t){t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(j||(j={}));var SR=V(Ls(),1),Tv=V(se(),1);var tp=V(Ka(),1),rp=V(Ie(),1),ep={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function Xi(t,e,r,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(ep).join(" / ");throw new E(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=ep[i],o=(0,tp.default)(t,e,r,n,s);return rp.default.encode64(o,null)}var mu=Symbol.for("@libp2p/peer-id");function vo(t){return t!=null&&!!t[mu]}var Pv=Symbol.for("nodejs.util.inspect.custom"),np=Object.values(Er).map(t=>t.decoder).reduce((t,e)=>t.or(e),Er.identity.decoder),ip=114,yu=36,gu=37,Zi=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[mu](){return!0}toString(){return this.string==null&&(this.string=Re.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ue.createV1(ip,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return ve(this.multihash.bytes,e);if(typeof e=="string")return ie(e).equals(this);if(e?.multihash?.bytes!=null)return ve(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Pv](){return`PeerId(${this.toString()})`}},Zn=class extends Zi{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},jn=class extends Zi{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Jn=class extends Zi{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function ie(t,e){if(e=e??np,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=Qr(Re.decode(`z${t}`));return t.startsWith("12D")?new jn({multihash:r}):t.startsWith("16U")?new Jn({multihash:r}):new Zn({multihash:r})}return ei(np.decode(t))}function ei(t){try{let e=Qr(t);if(e.code===vr.code){if(e.digest.length===yu)return new jn({multihash:e});if(e.digest.length===gu)return new Jn({multihash:e})}if(e.code===Ve.code)return new Zn({multihash:e})}catch{return Dv(ue.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function Dv(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==ip)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===Ve.code)return new Zn({multihash:t.multihash});if(e.code===vr.code){if(e.digest.length===yu)return new jn({multihash:t.multihash});if(e.digest.length===gu)return new Jn({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ln(t,e){return t.length===yu?new jn({multihash:qt(vr.code,t),privateKey:e}):t.length===gu?new Jn({multihash:qt(vr.code,t),privateKey:e}):new Zn({multihash:await Ve.digest(t),publicKey:t,privateKey:e})}var Eo=G("libp2p:keychain"),Nv="/pkcs8/",op="/info/",fn=new WeakMap,hn={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},xu={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function cr(t){return t==null||typeof t!="string"?!1:t===(0,sp.default)(t.trim())&&t.length>0}async function ae(){let r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function Qt(t){return new Se(Nv+t)}function Dr(t){return new Se(op+t)}var dn=class{constructor(e,r){if(this.components=e,this.init=Pr(xu,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.keyLength<hn.minKeyLength)throw new Error(`dek.keyLength must be least ${hn.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<hn.minSaltLength)throw new Error(`dek.saltLength must be least ${hn.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<hn.minIterationCount)throw new Error(`dek.iterationCount must be least ${hn.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?Xi(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";fn.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},xu),r=Math.ceil(hn.minSaltLength/3)*3;return e.dek.salt=$(on(r),"base64"),e}static get options(){return xu}async createKey(e,r,n=2048){if(!cr(e)||e==="self")throw await ae(),new E("Invalid key name",j.ERR_INVALID_KEY_NAME);if(typeof r!="string")throw await ae(),new E("Invalid key type",j.ERR_INVALID_KEY_TYPE);let i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E("Key name already exists",j.ERR_KEY_ALREADY_EXISTS);switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await ae(),new E("Invalid RSA key size",j.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await ho(r,n),c=await a.id(),u=fn.get(this);if(u==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let l=u.dek,f=await a.export(l);o={name:e,id:c};let h=this.components.datastore.batch();h.put(i,U(f)),h.put(Dr(e),U(JSON.stringify(o))),await h.commit()}catch(a){throw await ae(),a}return o}async listKeys(){let e={prefix:op},r=[];for await(let n of this.components.datastore.query(e))r.push(JSON.parse($(n.value)));return r}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new E(`Key with id '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND);return n}catch(r){throw await ae(),r}}async findKeyByName(e){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);let r=Dr(e);try{let n=await this.components.datastore.get(r);return JSON.parse($(n))}catch(n){throw await ae(),Eo.error(n),new E(`Key '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);let r=Qt(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(r),i.delete(Dr(e)),await i.commit(),n}async renameKey(e,r){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid old key name '${e}'`,j.ERR_OLD_KEY_NAME_INVALID);if(!cr(r)||r==="self")throw await ae(),new E(`Invalid new key name '${r}'`,j.ERR_NEW_KEY_NAME_INVALID);let n=Qt(e),i=Qt(r),s=Dr(e),o=Dr(r);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${r}' already exists`,j.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse($(u));l.name=r;let f=this.components.datastore.batch();return f.put(i,c),f.put(o,U(JSON.stringify(l))),f.delete(n),f.delete(s),await f.commit(),l}catch(c){throw await ae(),c}}async exportKey(e,r){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw await ae(),new E("Password is required",j.ERR_PASSWORD_REQUIRED);let n=Qt(e);try{let i=await this.components.datastore.get(n),s=$(i),o=fn.get(this);if(o==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Wi(s,a)).export(r)}catch(i){throw await ae(),i}}async exportPeerId(e){let r="temporary-password",n=await this.exportKey(e,r),i=await Wi(n,r);return await ln(i.public.bytes,i.bytes)}async importKey(e,r,n){if(!cr(e)||e==="self")throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw await ae(),new E("PEM encoded key is required",j.ERR_PEM_REQUIRED);let i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${e}' already exists`,j.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Wi(r,n)}catch{throw await ae(),new E("Cannot read the key, most likely the password is wrong",j.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=fn.get(this);if(l==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let f=l.dek;r=await o.export(f)}catch(l){throw await ae(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,U(r)),u.put(Dr(e),U(JSON.stringify(c))),await u.commit(),c}async importPeer(e,r){try{if(!cr(e))throw new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);if(r==null)throw new E("PeerId is required",j.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new E("PeerId.privKey is required",j.ERR_MISSING_PRIVATE_KEY);let n=await Hn(r.privateKey),i=Qt(e);if(await this.components.datastore.has(i))throw await ae(),new E(`Key '${e}' already exists`,j.ERR_KEY_ALREADY_EXISTS);let o=fn.get(this);if(o==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:r.toString()},l=this.components.datastore.batch();return l.put(i,U(c)),l.put(Dr(e),U(JSON.stringify(u))),await l.commit(),u}catch(n){throw await ae(),n}}async getPrivateKey(e){if(!cr(e))throw await ae(),new E(`Invalid key name '${e}'`,j.ERR_INVALID_KEY_NAME);try{let r=Qt(e),n=await this.components.datastore.get(r);return $(n)}catch(r){throw await ae(),Eo.error(r),new E(`Key '${e}' does not exist.`,j.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,r){if(typeof e!="string")throw await ae(),new E(`Invalid old pass type '${typeof e}'`,j.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await ae(),new E(`Invalid new pass type '${typeof r}'`,j.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await ae(),new E(`Invalid pass length ${r.length}`,j.ERR_INVALID_PASS_LENGTH);Eo("recreating keychain");let n=fn.get(this);if(n==null)throw new E("dek missing",j.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=r;let s=r!=null&&this.init.dek?.salt!=null?Xi(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";fn.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Qt(a.name)),u=$(c),l=await Wi(u,i),f=s.toString(),h=await l.export(f),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Qt(a.name),U(h)),d.put(Dr(a.name),U(JSON.stringify(p))),await d.commit()}Eo("keychain reconstructed")}};function ur(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return r}var lr=class{constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return ur(this.map.entries(),e=>[ie(e[0]),e[1]])}forEach(e){this.map.forEach((r,n)=>{e(r,ie(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),r)}keys(){return ur(this.map.keys(),e=>ie(e))}values(){return this.map.values()}get size(){return this.map.size}};var Bt=class{constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return ur(this.set.entries(),e=>{let r=ie(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=ie(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ur(this.set.values(),e=>ie(e))}intersection(e){let r=new Bt;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new Bt;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new Bt;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var ti=class{constructor(e){if(this.list=[],e!=null)for(let r of e)this.list.push(r.toString())}[Symbol.iterator](){return ur(this.list.entries(),e=>ie(e[1]))}concat(e){let r=new ti(this);for(let n of e)r.push(n);return r}entries(){return ur(this.list.entries(),e=>[e[0],ie(e[1])])}every(e){return this.list.every((r,n)=>e(ie(r),n,this))}filter(e){let r=new ti;return this.list.forEach((n,i)=>{let s=ie(n);e(s,i,this)&&r.push(s)}),r}find(e){let r=this.list.find((n,i)=>e(ie(n),i,this));if(r!=null)return ie(r)}findIndex(e){return this.list.findIndex((r,n)=>e(ie(r),n,this))}forEach(e){this.list.forEach((r,n)=>{e(ie(r),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return ie(e)}push(...e){for(let r of e)this.list.push(r.toString())}shift(){let e=this.list.shift();if(e!=null)return ie(e)}unshift(...e){let r=this.list.length;for(let n=e.length-1;n>-1;n--)r=this.list.unshift(e[n].toString());return r}get length(){return this.list.length}};var wu;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(wu||(wu={}));var ap=async()=>{let t=await ho("Ed25519"),e=await kv(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function cp(t){return await ln(ou(t))}async function kv(t){return await ln(ou(t.public),Ld(t))}var up={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var ji;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(ji||(ji={}));var fp=Symbol.for("@achingbrain/uint8arraylist");function lp(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function bo(t){return!!t?.[fp]}var Ae=class{constructor(...e){Object.defineProperty(this,fp,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(bo(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(bo(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(e){let r=lp(this.bufs,e);return r.buf[r.index]}set(e,r){let n=lp(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(bo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return Ce(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Ce(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),s=new Ae;return s.length=i,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(o);break}let f=e-a;n.push(o.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(r===c){n.push(o);break}n.push(o.subarray(0,r-a));break}n.push(o)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!bo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let f=0;f<s;f++)o[f]=-1;for(let f=0;f<i;f++)o[n[f]]=f;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=nr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=nr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=nr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=nr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof Ae)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!ve(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new Ae;return n.bufs=e,r==null&&(r=e.reduce((i,s)=>i+s.byteLength,0)),n.length=r,n}};function _o(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var hp=4294967296,lt=class{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new lt(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new lt(r,n)}toBytes(e,r=0){let n=_o(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new lt;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>hp&&(i=0,++n>hp&&(n=0))),new lt(n,i)}static fromNumber(e){if(e===0)return new lt;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new lt(i,n)}static fromBytes(e,r=0){let n=_o(e),i=new lt,s=0;if(e.length-r>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;s=0}else for(;s<4;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;s<5;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var Ov=Math.pow(2,7),Mv=Math.pow(2,14),Fv=Math.pow(2,21),Uv=Math.pow(2,28),Kv=Math.pow(2,35),Vv=Math.pow(2,42),qv=Math.pow(2,49),$v=Math.pow(2,56),zv=Math.pow(2,63),Lt={encodingLength(t){return t<Ov?1:t<Mv?2:t<Fv?3:t<Uv?4:t<Kv?5:t<Vv?6:t<qv?7:t<$v?8:t<zv?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=St(Lt.encodingLength(t))),lt.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return lt.fromBytes(t,e).toNumber(!0)}};var Hv,ft=class{constructor(e){let{peerId:r,payloadType:n,payload:i,signature:s}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=ji.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ve(this.marshal(),e.marshal())}async validate(e){let r=dp(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await cn(this.peerId.publicKey).verify(r.subarray(),this.signature)}};Hv=ft;ft.createFromProtobuf=async t=>{let e=ji.decode(t),r=await ln(e.publicKey);return new ft({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};ft.seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let r=t.domain,n=t.codec,i=t.marshal(),s=dp(r,n,i),a=await(await Hn(e.privateKey)).sign(s.subarray());return new ft({peerId:e,payloadType:n,payload:i,signature:a})};ft.openAndCertify=async(t,e)=>{let r=await ft.createFromProtobuf(t);if(!await r.validate(e))throw new E("envelope signature is not valid for the given domain",up.ERR_SIGNATURE_NOT_VALID);return r};var dp=(t,e,r)=>{let n=U(t),i=Lt.encode(n.byteLength),s=Lt.encode(e.length),o=Lt.encode(r.length);return new Ae(i,n,s,e,o,r)};var Du=V(So(),1);var ii=V(So(),1);var Ao=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(s*=e,s+=l,s>u||(o+=1,r!==void 0&&o>r))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return r[i]=o[0],r[i+1]=o[1],r[i+2]=o[2],r[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];r[i]=s>>8,r[i+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var _p=45,sE=15,ri=new Ao;function bu(t){if(!(t.length>sE))return ri.new(t).parseWith(()=>ri.readIPv4Addr())}function _u(t){if(!(t.length>_p))return ri.new(t).parseWith(()=>ri.readIPv6Addr())}function Io(t){if(!(t.length>_p))return ri.new(t).parseWith(()=>ri.readIPAddr())}var oC=parseInt("0xFFFF",16),aC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Xt=V(So(),1);function Ip(t){return!!bu(t)}function Rp(t){return!!_u(t)}function ni(t){return!!Io(t)}var Cp=Ip,lE=Rp,Su=function(t){let e=0;if(t=t.toString().trim(),Cp(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(lE(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Cp(r[n]),o;s&&(o=Su(r[n]),r[n]=$(o.slice(0,2),"base16")),o!=null&&++n<8&&r.splice(n,0,$(o.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},Tp=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let s=0;s<r;s++)i.push(t[e+s]);return i.join(".")}if(r===16){let i=[];for(let s=0;s<r;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ji={},Au={},hE=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];hE.forEach(t=>{let e=dE(...t);Au[e.code]=e,Ji[e.name]=e});function dE(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function ce(t){if(typeof t=="number"){if(Au[t]!=null)return Au[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(Ji[t]!=null)return Ji[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var zC=ce("ip4"),HC=ce("ip6"),GC=ce("ipcidr");function Np(t,e){switch(ce(t).code){case 4:case 41:return mE(e);case 42:return Pp(e);case 6:case 273:case 33:case 132:return Op(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Pp(e);case 421:return wE(e);case 444:return Dp(e);case 445:return Dp(e);case 466:return xE(e);default:return $(e,"base16")}}function kp(t,e){switch(ce(t).code){case 4:return Bp(e);case 41:return Bp(e);case 42:return Lp(e);case 6:case 273:case 33:case 132:return Ru(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Lp(e);case 421:return yE(e);case 444:return vE(e);case 445:return EE(e);case 466:return gE(e);default:return U(e,"base16")}}var Iu=Object.values(Er).map(t=>t.decoder),pE=function(){let t=Iu[0].or(Iu[1]);return Iu.slice(2).forEach(e=>t=t.or(e)),t}();function Bp(t){if(!ni(t))throw new Error("invalid ip address");return Su(t)}function mE(t){let e=Tp(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!ni(e))throw new Error("invalid ip address");return e}function Ru(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Op(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function Lp(t){let e=U(t),r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function Pp(t){let e=Xt.default.decode(t);if(t=t.slice(Xt.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return $(t)}function yE(t){let e;t[0]==="Q"||t[0]==="1"?e=Qr(Re.decode(`z${t}`)).bytes:e=ue.parse(t).multihash.bytes;let r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function gE(t){let e=pE.decode(t),r=Uint8Array.from(Xt.default.encode(e.length));return Ce([r,e],r.length+e.length)}function xE(t){let e=Xt.default.decode(t),r=t.slice(Xt.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+$(r,"base64url")}function wE(t){let e=Xt.default.decode(t),r=t.slice(Xt.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return $(r,"base58btc")}function vE(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=st.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ru(n);return Ce([r,i],r.length+i.length)}function EE(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=st.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ru(n);return Ce([r,i],r.length+i.length)}function Dp(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=$(e,"base32"),i=Op(r);return`${n}:${i}`}function bE(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=ce(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw Fp("invalid address: "+t);if(s.path===!0){e.push([i,Pu(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function _E(t){let e=[];return t.map(r=>{let n=To(r);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Pu(e.join("/"))}function SE(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=To(e);return e.length>1?[r.code,kp(r.code,e[1])]:[r.code]})}function Cu(t){return t.map(e=>{let r=To(e);return e[1]!=null?[r.code,Np(r.code,e[1])]:[r.code]})}function Tu(t){return Co(Ce(t.map(e=>{let r=To(e),n=Uint8Array.from(ii.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=Ce([n,e[1]])),n})))}function Bu(t,e){return t.size>0?t.size/8:t.size===0?0:ii.default.decode(e)+(ii.default.decode.bytes??0)}function Ro(t){let e=[],r=0;for(;r<t.length;){let n=ii.default.decode(t,r),i=ii.default.decode.bytes??0,s=ce(n),o=Bu(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw Fp("Invalid address Uint8Array: "+$(t,"base16"));e.push([n,a])}return e}function Lu(t){let e=Ro(t),r=Cu(e);return _E(r)}function AE(t){t=Pu(t);let e=bE(t),r=SE(e);return Tu(r)}function Mp(t){return AE(t)}function Co(t){let e=IE(t);if(e!=null)throw e;return Uint8Array.from(t)}function IE(t){try{Ro(t)}catch(e){return e}}function Pu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function Fp(t){return new Error("Error parsing address: "+t)}function To(t){return ce(t[0])}var CE=Symbol.for("nodejs.util.inspect.custom"),TE=[ce("dns").code,ce("dns4").code,ce("dns6").code,ce("dnsaddr").code],Nu=new Map,Up=Symbol.for("@multiformats/js-multiaddr/multiaddr");function pn(t){return!!t?.[Up]}var fr=class{bytes;#e;#t;#n;#r;[Up]=!0;constructor(e){if(e==null&&(e=""),e instanceof Uint8Array)this.bytes=Co(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=Mp(e)}else if(pn(e))this.bytes=Co(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return this.#e==null&&(this.#e=Lu(this.bytes)),this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,i,s="",o=ce("tcp"),a=ce("udp"),c=ce("ip4"),u=ce("ip6"),l=ce("dns6"),f=ce("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(s=`%${p??""}`),TE.includes(d)&&(r=o.name,i=443,n=`${p??""}${s}`,e=d===l.code?6:4),(d===o.code||d===a.code)&&(r=ce(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(r=ce(d).name,n=`${p??""}${s}`,e=d===u.code?6:4);if(e==null||r==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:r,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},ce(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=Du.default.decode(r,n),s=Du.default.decode.bytes??0,o=ce(i),a=Bu(o,r.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return this.#t==null&&(this.#t=Ro(this.bytes)),this.#t}stringTuples(){return this.#n==null&&(this.#n=Cu(this.tuples())),this.#n}encapsulate(e){return e=new fr(e),new fr(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new fr(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new fr(Tu(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Ji.ipfs.code).pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?$(Re.decode(`z${n}`),"base58btc"):$(ue.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(this.#r===void 0)try{this.#r=this.stringTuples().filter(e=>ce(e[0]).path===!0)[0][1],this.#r==null&&(this.#r=null)}catch{this.#r=null}return this.#r}equals(e){return ve(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=Nu.get(r.name);if(n==null)throw new E(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new fr(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[CE](){return`Multiaddr(${Lu(this.bytes)})`}};function Ne(t){return new fr(t)}function Kp(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var es;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=ze((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>$e(s,n.codec()),n.decode=s=>qe(s,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=ze((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),r),t.encode=n=>$e(n,t.codec()),t.decode=n=>qe(n,t.codec())})(es||(es={}));var Vp="libp2p-peer-record",qp=Uint8Array.from([3,1]);var Ze=class{constructor(e){this.domain=Ze.DOMAIN,this.codec=Ze.CODEC;let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=es.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Ze)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Kp(this.multiaddrs,e.multiaddrs))}};Ze.createFromProtobuf=t=>{let e=es.decode(t),r=ei(e.peerId),n=(e.addresses??[]).map(s=>Ne(s.multiaddr)),i=e.seq;return new Ze({peerId:r,multiaddrs:n,seqNumber:i})};Ze.DOMAIN=Vp;Ze.CODEC=qp;var Jp=V(zp(),1);var rs=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ou=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Hp=t=>globalThis.DOMException===void 0?new Ou(t):new DOMException(t),Gp=t=>{let e=t.reason===void 0?Hp("This operation was aborted."):t.reason;return e instanceof Error?e:Hp(e)};function Mu(t,e,r,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(Gp(c)),c.addEventListener("abort",()=>{a(Gp(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new rs(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{o(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function Fu(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var mn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},hr,ns=class{constructor(){hr.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&mn(this,hr,"f")[this.size-1].priority>=r.priority){mn(this,hr,"f").push(n);return}let i=Fu(mn(this,hr,"f"),n,(s,o)=>o.priority-s.priority);mn(this,hr,"f").splice(i,0,n)}dequeue(){let e=mn(this,hr,"f").shift();return e?.run}filter(e){return mn(this,hr,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return mn(this,hr,"f").length}};hr=new WeakMap;var Ee=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},k=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Be,ss,os,kr,Oo,as,Lo,Pt,is,ht,Po,dt,cs,Nr,Do,Yp,Wp,Zp,Qp,Xp,No,Uu,Ku,Mo,jp,ko,Fo=class extends Error{},Dt=class extends Jp.default{constructor(e){var r,n,i,s;if(super(),Be.add(this),ss.set(this,void 0),os.set(this,void 0),kr.set(this,0),Oo.set(this,void 0),as.set(this,void 0),Lo.set(this,0),Pt.set(this,void 0),is.set(this,void 0),ht.set(this,void 0),Po.set(this,void 0),dt.set(this,0),cs.set(this,void 0),Nr.set(this,void 0),Do.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ns,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);Ee(this,ss,e.carryoverConcurrencyCount,"f"),Ee(this,os,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Ee(this,Oo,e.intervalCap,"f"),Ee(this,as,e.interval,"f"),Ee(this,ht,new e.queueClass,"f"),Ee(this,Po,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Ee(this,Do,e.throwOnTimeout===!0,"f"),Ee(this,Nr,e.autoStart===!1,"f")}get concurrency(){return k(this,cs,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Ee(this,cs,e,"f"),k(this,Be,"m",Mo).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:k(this,Do,"f"),...r},new Promise((n,i)=>{k(this,ht,"f").enqueue(async()=>{var s,o,a;Ee(this,dt,(o=k(this,dt,"f"),o++,o),"f"),Ee(this,kr,(a=k(this,kr,"f"),a++,a),"f");try{if(!((s=r.signal)===null||s===void 0)&&s.aborted)throw new Fo("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=Mu(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,k(this,Be,"m",jp).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof rs&&!r.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{k(this,Be,"m",Zp).call(this)}},r),this.emit("add"),k(this,Be,"m",No).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return k(this,Nr,"f")?(Ee(this,Nr,!1,"f"),k(this,Be,"m",Mo).call(this),this):this}pause(){Ee(this,Nr,!0,"f")}clear(){Ee(this,ht,new(k(this,Po,"f")),"f")}async onEmpty(){k(this,ht,"f").size!==0&&await k(this,Be,"m",ko).call(this,"empty")}async onSizeLessThan(e){k(this,ht,"f").size<e||await k(this,Be,"m",ko).call(this,"next",()=>k(this,ht,"f").size<e)}async onIdle(){k(this,dt,"f")===0&&k(this,ht,"f").size===0||await k(this,Be,"m",ko).call(this,"idle")}get size(){return k(this,ht,"f").size}sizeBy(e){return k(this,ht,"f").filter(e).length}get pending(){return k(this,dt,"f")}get isPaused(){return k(this,Nr,"f")}};ss=new WeakMap,os=new WeakMap,kr=new WeakMap,Oo=new WeakMap,as=new WeakMap,Lo=new WeakMap,Pt=new WeakMap,is=new WeakMap,ht=new WeakMap,Po=new WeakMap,dt=new WeakMap,cs=new WeakMap,Nr=new WeakMap,Do=new WeakMap,Be=new WeakSet,Yp=function(){return k(this,os,"f")||k(this,kr,"f")<k(this,Oo,"f")},Wp=function(){return k(this,dt,"f")<k(this,cs,"f")},Zp=function(){var e;Ee(this,dt,(e=k(this,dt,"f"),e--,e),"f"),k(this,Be,"m",No).call(this),this.emit("next")},Qp=function(){k(this,Be,"m",Ku).call(this),k(this,Be,"m",Uu).call(this),Ee(this,is,void 0,"f")},Xp=function(){let e=Date.now();if(k(this,Pt,"f")===void 0){let r=k(this,Lo,"f")-e;if(r<0)Ee(this,kr,k(this,ss,"f")?k(this,dt,"f"):0,"f");else return k(this,is,"f")===void 0&&Ee(this,is,setTimeout(()=>{k(this,Be,"m",Qp).call(this)},r),"f"),!0}return!1},No=function(){if(k(this,ht,"f").size===0)return k(this,Pt,"f")&&clearInterval(k(this,Pt,"f")),Ee(this,Pt,void 0,"f"),this.emit("empty"),k(this,dt,"f")===0&&this.emit("idle"),!1;if(!k(this,Nr,"f")){let e=!k(this,Be,"a",Xp);if(k(this,Be,"a",Yp)&&k(this,Be,"a",Wp)){let r=k(this,ht,"f").dequeue();return r?(this.emit("active"),r(),e&&k(this,Be,"m",Uu).call(this),!0):!1}}return!1},Uu=function(){k(this,os,"f")||k(this,Pt,"f")!==void 0||(Ee(this,Pt,setInterval(()=>{k(this,Be,"m",Ku).call(this)},k(this,as,"f")),"f"),Ee(this,Lo,Date.now()+k(this,as,"f"),"f"))},Ku=function(){k(this,kr,"f")===0&&k(this,dt,"f")===0&&k(this,Pt,"f")&&(clearInterval(k(this,Pt,"f")),Ee(this,Pt,void 0,"f")),Ee(this,kr,k(this,ss,"f")?k(this,dt,"f"):0,"f"),k(this,Be,"m",Mo).call(this)},Mo=function(){for(;k(this,Be,"m",No).call(this););},jp=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Fo("The task was aborted."))},{once:!0})})},ko=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var Vu=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},qu=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},em=t=>globalThis.DOMException===void 0?new qu(t):new DOMException(t),tm=t=>{let e=t.reason===void 0?em("This operation was aborted."):t.reason;return e instanceof Error?e:em(e)};function $u(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,u)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(r===Number.POSITIVE_INFINITY){c(t);return}if(e.signal){let{signal:f}=e;f.aborted&&u(tm(f)),f.addEventListener("abort",()=>{u(tm(f))})}let l=new Vu;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(f){u(f)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${r} milliseconds`,u(l))},r),(async()=>{try{c(await t)}catch(f){u(f)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var zu="lock:worker:request-read",Hu="lock:worker:release-read",Gu="lock:master:grant-read",Yu="lock:worker:request-write",Wu="lock:worker:release-write",Qu="lock:master:grant-write";var Or={},si=t=>{t.addEventListener("message",e=>{si.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{si.dispatchEvent("message",t,e)})};si.addEventListener=(t,e)=>{Or[t]==null&&(Or[t]=[]),Or[t].push(e)};si.removeEventListener=(t,e)=>{Or[t]!=null&&(Or[t]=Or[t].filter(r=>r===e))};si.dispatchEvent=function(t,e,r){Or[t]!=null&&Or[t].forEach(n=>n(e,r))};var Xu=si;var rm=(t,e,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},nm=(t,e,r,n)=>async()=>{let i=xo();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},PE={singleProcess:!1},im=t=>{if(t=Object.assign({},PE,t),!!globalThis.document||t.singleProcess){let r=new EventTarget;return Xu.addEventListener("message",rm(r,"requestReadLock",zu,Hu,Gu)),Xu.addEventListener("message",rm(r,"requestWriteLock",Yu,Wu,Qu)),r}return{isWorker:!0,readLock:r=>nm(r,zu,Gu,Hu),writeLock:r=>nm(r,Yu,Qu,Wu)}};var yn={},Mr;async function Zu(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await $u((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var DE=(t,e)=>{if(Mr.isWorker===!0)return{readLock:Mr.readLock(t,e),writeLock:Mr.writeLock(t,e)};let r=new Dt({concurrency:1}),n;return{async readLock(){if(n!=null)return await Zu(n,e);n=new Dt({concurrency:e.concurrency,autoStart:!1});let i=n,s=Zu(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await Zu(r,e)}}},NE={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ju(t){let e=Object.assign({},NE,t);return Mr==null&&(Mr=im(e),Mr.isWorker!==!0&&(Mr.addEventListener("requestReadLock",r=>{yn[r.data.name]!=null&&yn[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Mr.addEventListener("requestWriteLock",async r=>{yn[r.data.name]!=null&&yn[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),yn[e.name]==null&&(yn[e.name]=DE(e.name,e)),yn[e.name]}var He={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var oi;(function(t){let e;(function(i){let s;i.codec=()=>(s==null&&(s=ze((o,a,c={})=>{c.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)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>$e(o,i.codec()),i.decode=o=>qe(o,i.codec())})(e=t.Peer$metadataEntry||(t.Peer$metadataEntry={}));let r;(function(i){let s;i.codec=()=>(s==null&&(s=ze((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),Ko.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=Ko.codec().decode(o,o.uint32());break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>$e(o,i.codec()),i.decode=o=>qe(o,i.codec())})(r=t.Peer$tagsEntry||(t.Peer$tagsEntry={}));let n;t.codec=()=>(n==null&&(n=ze((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),Uo.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),t.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),t.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(Uo.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let u=t.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(u.key,u.value);break}case 7:{let u=t.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return o})),n),t.encode=i=>$e(i,t.codec()),t.decode=i=>qe(i,t.codec())})(oi||(oi={}));var Uo;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Uo||(Uo={}));var Ko;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,i={})=>{i.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)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={value:0},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.value=r.uint32();break;case 2:i.expiry=r.uint64();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>$e(r,t.codec()),t.decode=r=>qe(r,t.codec())})(Ko||(Ko={}));async function ai(t,e){let r=oi.decode(e);r.publicKey!=null&&t.publicKey==null&&(t=await cp(cn(r.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of r.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...r,id:t,addresses:r.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:Ne(s),isCertified:o??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}var Ju="/peers/";function ci(t){if(!vo(t)||t.type==null)throw new E("Invalid PeerId",He.ERR_INVALID_PARAMETERS);let e=t.toCID().toString();return new Se(`${Ju}${e}`)}async function sm(t,e,r){let n=new Map;for(let i of r){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=Ne(i.multiaddr)),!pn(i.multiaddr))throw new E("Multiaddr was invalid",He.ERR_INVALID_PARAMETERS);if(!await e(t,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function qo(t,e,r,n){if(e==null)throw new E("Invalid PeerData",He.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&t.publicKey!=null&&!ve(e.publicKey,t.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",He.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!t.equals(i.id))throw new E("peer id did not match existing peer id",He.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(r==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Vo(f,{validate:om})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Vo(f,{validate:am,map:cm})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(r==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,d]of f)d==null?a.delete(h):a.set(h,d);a=Vo([...a.entries()],{validate:om})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[d,p]of f)p==null?h.delete(d):h.set(d,p);c=Vo([...h.entries()],{validate:am,map:cm})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await sm(t,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??t.publicKey,peerRecordEnvelope:u};return t.type!=="RSA"&&delete l.publicKey,l}function Vo(t,e){let r=new Map;for(let[n,i]of t)i!=null&&e.validate(n,i);for(let[n,i]of t.sort(([s],[o])=>s.localeCompare(o)))i!=null&&r.set(n,e.map?.(n,i)??i);return r}function om(t,e){if(typeof t!="string")throw new E("Metadata key must be a string",He.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",He.ERR_INVALID_PARAMETERS)}function am(t,e){if(typeof t!="string")throw new E("Tag name must be a string",He.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",He.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",He.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",He.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",He.ERR_INVALID_PARAMETERS)}}function cm(t,e){let r;return e.expiry!=null&&(r=e.expiry),e.ttl!=null&&(r=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:r}}var $o=class{peerId;datastore;lock;addressFilter;constructor(e,r={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=r.addressFilter,this.lock=ju({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ci(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",He.ERR_INVALID_PARAMETERS);await this.datastore.delete(ci(e))}async load(e){let r=await this.datastore.get(ci(e));return ai(e,r)}async save(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await qo(e,r,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:r}of this.datastore.query({prefix:Ju})){let n=e.toString().split("/")[2],i=st.decode(n),s=ei(i);s.equals(this.peerId)||(yield ai(s,r))}}async#e(e){try{let r=await this.datastore.get(ci(e)),n=await ai(e,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}}async#t(e,r,n,i){let s=oi.encode(r);return n!=null&&ve(s,n)?{peer:await ai(e,s),previous:i,updated:!1}:(await this.datastore.put(ci(e),s),{peer:await ai(e,s),previous:i,updated:!0})}};var fe=G("libp2p:peer-store"),zo=class{store;events;peerId;constructor(e,r={}){this.events=e.events,this.peerId=e.peerId,this.store=new $o(e,r)}async forEach(e){fe.trace("forEach await read lock");let r=await this.store.lock.readLock();fe.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{fe.trace("forEach release read lock"),r()}}async all(){fe.trace("all await read lock");let e=await this.store.lock.readLock();fe.trace("all got read lock");try{let r=[];for await(let n of this.store.all())r.push(n);return r}finally{fe.trace("all release read lock"),e()}}async delete(e){fe.trace("delete await write lock");let r=await this.store.lock.writeLock();fe.trace("delete got write lock");try{await this.store.delete(e)}finally{fe.trace("delete release write lock"),r()}}async has(e){fe.trace("has await read lock");let r=await this.store.lock.readLock();fe.trace("has got read lock");try{return await this.store.has(e)}finally{fe.trace("has release read lock"),r()}}async get(e){fe.trace("get await read lock");let r=await this.store.lock.readLock();fe.trace("get got read lock");try{return await this.store.load(e)}finally{fe.trace("get release read lock"),r()}}async save(e,r){fe.trace("save await write lock");let n=await this.store.lock.writeLock();fe.trace("save got write lock");try{let i=await this.store.save(e,r);return this.#e(e,i),i.peer}finally{fe.trace("save release write lock"),n()}}async patch(e,r){fe.trace("patch await write lock");let n=await this.store.lock.writeLock();fe.trace("patch got write lock");try{let i=await this.store.patch(e,r);return this.#e(e,i),i.peer}finally{fe.trace("patch release write lock"),n()}}async merge(e,r){fe.trace("merge await write lock");let n=await this.store.lock.writeLock();fe.trace("merge got write lock");try{let i=await this.store.merge(e,r);return this.#e(e,i),i.peer}finally{fe.trace("merge release write lock"),n()}}async consumePeerRecord(e,r){let n=await ft.openAndCertify(e,Ze.DOMAIN);if(r?.equals(n.peerId)===!1)return fe("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;let i=Ze.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await ft.createFromProtobuf(s.peerRecordEnvelope),a=Ze.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return fe("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,r){r.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))}};function kE(t){return t[Symbol.asyncIterator]!=null}function OE(t){if(kE(t))return(async()=>{for await(let e of t);})();for(let e of t);}var el=OE;function ME(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var Ho=ME;function FE(t){return t[Symbol.asyncIterator]!=null}function UE(t,e){if(FE(t))return async function*(){for await(let a of t)await e(a)&&(yield a)}();let r=Ho(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of r)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of r)o(a)&&(yield a)}()}var Nt=UE;function KE(t){return t[Symbol.asyncIterator]!=null}function VE(t){if(KE(t))return(async()=>{let r=[];for await(let n of t)r.push(n);return r})();let e=[];for(let r of t)e.push(r);return e}var tl=VE;function qE(t){return t[Symbol.asyncIterator]!=null}function $E(t,e){return qE(t)?async function*(){yield*(await tl(t)).sort(e)}():function*(){yield*tl(t).sort(e)}()}var rl=$E;function zE(t){return t[Symbol.asyncIterator]!=null}function HE(t,e){return zE(t)?async function*(){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}}():function*(){let r=0;if(!(e<1)){for(let n of t)if(yield n,r++,r===e)return}}()}var nl=HE;var Go=class{put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield n}async*getMany(e,r={}){for await(let n of e)yield{key:n,value:await this.get(n,r)}}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await el(this.putMany(e,n)),e=[],await el(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null){let i=e.prefix;n=Nt(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Nt(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>rl(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Nt(n,()=>i++>=s)}return e.limit!=null&&(n=nl(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null){let i=e.prefix;n=Nt(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Nt(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>rl(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Nt(n,()=>s++>=i)}return e.limit!=null&&(n=nl(n,e.limit)),n}};var fm=V(il(),1);function hm(t){return t=t??new Error("Not Found"),(0,fm.default)(t,"ERR_NOT_FOUND")}var Yo=class extends Go{data;constructor(){super(),this.data=new Map}put(e,r){return this.data.set(e.toString(),r),e}get(e){let r=this.data.get(e.toString());if(r==null)throw hm();return r}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,r]of this.data.entries())yield{key:new Se(e),value:r}}*_allKeys(){for(let e of this.data.keys())yield new Se(e)}};function dm(t,e){let r;return function(){let n=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(n,e)}}var WE=G("libp2p:address-manager"),QE=t=>t;function sl(t,e){let r=t.getPeerId();return r!=null&&ie(r).equals(e)&&(t=t.decapsulate(Ne(`/p2p/${e.toString()}`))),t}var Wo=class{components;listen;announce;observed;announceFilter;constructor(e,r={}){let{listen:n=[],announce:i=[]}=r;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??QE,this._updatePeerStoreAddresses=dm(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>Ne(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:e}).catch(r=>{WE.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(e=>Ne(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Ne(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Ne(e))}addObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString(),i=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=sl(e,this.components.peerId);let r=e.toString();this.observed.delete(r)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let r=new Set(e);return this.announceFilter(Array.from(r).map(n=>Ne(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function pm(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}var ol=class{components={};_started=!1;constructor(e={}){this.components={};for(let[r,n]of Object.entries(e))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(r=>pm(r)).map(async r=>{await r[e]?.()}))}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")}},XE=["metrics","connectionProtector"],ZE=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mm(t={}){let e=new ol(t);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!ZE.includes(i)){let o=e.components[i];if(o==null&&!XE.includes(i))throw new E(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}var bm=V(ym(),1);var gm="[a-fA-F\\d:]",Fr=t=>t&&t.includeBoundaries?`(?:(?<=\\s|^)(?=${gm})|(?<=${gm})(?=\\s|$))`:"",kt="(?: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}",Pe="[a-fA-F\\d]{1,4}",Qo=`
38
38
  (?:
39
39
  (?:${Pe}:){7}(?:${Pe}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
40
40
  (?:${Pe}:){6}(?:${kt}|:${Pe}|:)| // 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
@@ -45,7 +45,7 @@
45
45
  (?:${Pe}:){1}(?:(?::${Pe}){0,4}:${kt}|(?::${Pe}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
46
46
  (?::(?:(?::${Pe}){0,5}:${kt}|(?::${Pe}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
47
47
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
48
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),jE=new RegExp(`(?:^${kt}$)|(?:^${Qo}$)`),JE=new RegExp(`^${kt}$`),eb=new RegExp(`^${Qo}$`),al=t=>t&&t.exact?jE:new RegExp(`(?:${Fr(t)}${kt}${Fr(t)})|(?:${Fr(t)}${Qo}${Fr(t)})`,"g");al.v4=t=>t&&t.exact?JE:new RegExp(`${Fr(t)}${kt}${Fr(t)}`,"g");al.v6=t=>t&&t.exact?eb:new RegExp(`${Fr(t)}${Qo}${Fr(t)}`,"g");var xm=al;var _m=V(vm(),1),{isValid:tb,parse:rb}=_m.default,nb=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],ib=nb.map(t=>new bm.Netmask(t));function sb(t){for(let e of ib)if(e.contains(t))return!0;return!1}function Em(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var Sm=t=>{if(tb(t)){let e=rb(t);if(e.kind()==="ipv4")return sb(e.toNormalizedString());if(e.kind()==="ipv6")return Em(t)}else if(ni(t)&&xm.v6().test(t))return Em(t)};var Zo=Sm;function Am(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Zo(`${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,...t}}var c3=Symbol.for("@libp2p/transport");var Ur;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ur||(Ur={}));function cl(t){try{let{address:e}=t.nodeAddress();return!!Zo(e)}catch{return!0}}function ui(t,e){let r=cl(t.multiaddr),n=cl(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var ll=V(du(),1),fl=V(Cm(),1);var Tm=globalThis.fetch,Bm=globalThis.Headers,m3=globalThis.Request,y3=globalThis.Response;function jo(t,e,r){return`${t}?name=${e}&type=${r}`}async function Lm(t,e){return await(await Tm(t,{headers:new Bm({accept:"application/dns-json"}),signal:e})).json()}function gn(t,e){return`${e}_${t}`}var ul=Object.assign((0,ll.default)("dns-over-http-resolver"),{error:(0,ll.default)("dns-over-http-resolver:error")}),hl=class{constructor(e={}){this._cache=new fl.default({max:e?.maxCache??100}),this._TXTcache=new fl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Lm,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Pm=hl;var Dm=Pm;var{code:lb}=ce("dnsaddr");async function li(t,e={}){let r=new Dm;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===lb)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Zt;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(Zt||(Zt={}));var D;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(D||(D={}));var fb={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:li},addressSorter:ui},transportManager:{faultTolerance:Ur.FATAL_ALL}};function Nm(t){let e=Pr(fb,t);if(e.transports==null||e.transports.length<1)throw new E(Zt.ERR_TRANSPORTS_REQUIRED,D.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Zt.ERR_PROTECTOR_REQUIRED,D.ERR_PROTECTOR_REQUIRED);return e}var km="keep-alive";var Ny=V(By(),1);var Yb=G("libp2p:get-peer");function ea(t){if(vo(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:ie(r),t.forEach(n=>{if(!pn(n))throw Yb.error("multiaddr %s was invalid",n),new E("Invalid Multiaddr",D.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",D.ERR_INVALID_PARAMETERS)}else{let s=ie(i);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",D.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}var jt=G("libp2p:connection-manager:auto-dial"),ta={minConnections:50,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},ra=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialInterval;started;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??ta.minConnections,this.autoDialPriority=r.autoDialPriority??ta.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??ta.autoDialInterval,this.started=!1,this.queue=new Dt({concurrency:r.autoDialConcurrency??ta.autoDialConcurrency}),this.queue.addListener("error",n=>{jt.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{jt.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setInterval(()=>{this.autoDial().catch(e=>{jt.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{jt.error("error while autodialing",e)})}stop(){this.queue.clear(),clearInterval(this.autoDialInterval),this.started=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size,n=new Bt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean));if(r>=this.minConnections){jt.trace("have enough connections %d/%d",r,this.minConnections);return}jt("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let i=await this.peerStore.all(),o=i.filter(u=>!(u.addresses.length===0||e.has(u.id)||n.has(u.id))).sort(()=>Math.random()>.5?1:-1),a=new lr;for(let u of o)a.has(u.id)||a.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=o.sort((u,l)=>{let f=a.get(u.id)??0,h=a.get(l.id)??0;return f>h?-1:f<h?1:0});jt("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){jt("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}jt("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})}).catch(l=>{jt.error("could not connect to peerStore stored peer",l)})}};var mi=G("libp2p:connection-manager:connection-pruner"),Ly={maxConnections:300,allow:[]},na=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Ly.maxConnections,this.allow=r.allow??Ly.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{mi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(mi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;mi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new lr;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&mi.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.stat.timeline.open,h=c.stat.timeline.open;return f<h?1:f>h?-1:0}),o=[];for(let a of s)if(mi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){mi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var Pl=V(bi(),1);function yi(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function hs(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Bl=V(bi(),1);var Py=G("libp2p:connection-manager:utils");async function Ll(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await Qb(t,e),o=(await Promise.all(n.map(async a=>Ll(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Py("resolved %s to",t,o.map(a=>a.toString())),o}async function Qb(t,e){try{return t=Ne(t.toString()),await t.resolve(e)}catch(r){return Py.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Dy(...t){let e=[];for(let n of t)if(n!=null){try{(0,Bl.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=yi(e);try{(0,Bl.setMaxListeners)?.(1/0,r)}catch{}return r}var Ye=G("libp2p:connection-manager:dial-queue"),ds={addressSorter:ui,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:li}},ia=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??ds.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??ds.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??ds.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??ds.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,Pl.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))Nu.set(n,i);this.queue=new Dt({concurrency:r.maxParallelDials??ds.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=>{Ye.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(e,r={}){let{peerId:n,multiaddrs:i}=ea(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return Ye("joining existing dial target for %p",n),o.clear(),c.promise;Ye("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:Zb(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(l=>{throw Ye.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),o.aborted?new E(l.message,D.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=yi([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,Pl.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new E("Tried to dial self",D.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",D.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){Ye("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),Ye("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==D.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Ll(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),s=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),o=new Map;for(let l of s){let f=l.multiaddr.toString(),h=o.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(Ye("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),Ye("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new E("The dial request has no valid addresses",D.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new E("dial with more addresses than allowed",D.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new E("The connection gater denied all addresses in the dial request",D.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Dt({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{Ye.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new E("dialAction did not come with an AbortController",D.ERR_INVALID_PARAMETERS);let u=Dy(c.signal,r.signal);u.addEventListener("abort",()=>{Ye("dial to %s aborted",o)});let l=hs();return await i.add(async()=>{if(u.aborted){Ye("dial to %s was aborted before reaching the head of the peer dial queue",o),l.reject(new xr);return}await this.queue.add(async()=>{try{if(u.aborted){Ye("dial to %s was aborted before reaching the head of the dial queue",o),l.reject(new xr);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){Ye("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{Ye.error("error closing superfluous connection",h)}),l.reject(new xr);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),Ye("dial to %s succeeded",o),l.resolve(f)}catch(f){Ye.error("error during dial of %s",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new E("successful dial led to empty object returned from peer dial queue",D.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function Zb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pt=G("libp2p:connection-manager"),e_=50,gi={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0},sa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??gi.maxConnections;let n=r.minConnections??gi.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",D.ERR_INVALID_PARAMETERS);this.connections=new lr,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ne(i)),this.deny=(r.deny??[]).map(i=>Ne(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??gi.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Ny.RateLimiterMemory({points:r.inboundConnectionThreshold??gi.inboundConnectionThreshold,duration:1}),this.autoDial=new ra({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??gi.autoDialConcurrency,autoDialPriority:r.autoDialPriority??gi.autoDialPriority}),this.connectionPruner=new na({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ia({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??ui,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:li}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.stat.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.stat.direction} ${i.stat.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.stat.direction} ${o.stat.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,pt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=[];for(let r of await this.peerStore.all())r.tags.has(km)&&e.push(r.id);await Promise.all(e.map(async r=>{await this.openConnection(r).catch(n=>{pt.error(n)})}))}).catch(e=>{pt.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){pt.error(i)}})());pt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),pt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{pt.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new E("Not started",D.ERR_NODE_NOT_STARTED);let{peerId:n}=ea(e);if(n!=null){pt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return pt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??e_}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e){let r=this.connections.get(e)??[];await Promise.all(r.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return pt("connection from %s refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return pt("connection from %s refused - incomingPendingConnections exceeded by peer %s",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return pt("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(pt("connection from %s refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var oa=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},xi=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new oa(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new oa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function xn(t={}){return t_(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function t_(t,e){e=e??{};let r=e.onEnd,n=new xi,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((m,y)=>{s=g=>{s=null,n.push(g);try{m(t(n))}catch(w){y(w)}return i}}):t(n),c=m=>s!=null?s(m):(n.push(m),i),u=m=>(n=new xi,s!=null?s({error:m}):(n.push({error:m}),i)),l=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},f=m=>o?i:(o=!0,m!=null?u(m):c({done:!0})),h=()=>(n=new xi,f(),{done:!0}),d=m=>(f(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:d,push:l,end:f,get readableLength(){return n.size}},r==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(m){return p.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return p.readableLength}},i}function r_(t){return t[Symbol.asyncIterator]!=null}function n_(...t){let e=[];for(let r of t)r_(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=xn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Vr=n_;function wn(t,...e){if(t==null)throw new Error("Empty pipeline");if(Ol(t)){let n=t;t=()=>n.source}else if(Oy(t)||ky(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Ol(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Ol(r[n])&&(r[n]=s_(r[n]));return i_(...r)}var i_=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},ky=t=>t?.[Symbol.asyncIterator]!=null,Oy=t=>t?.[Symbol.iterator]!=null,Ol=t=>t==null?!1:t.sink!=null&&t.source!=null,s_=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=xn({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(ky(s))i=async function*(){yield*s,n.end()};else if(Oy(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vr(n,i())}return t.source};function o_(t){return t[Symbol.asyncIterator]!=null}function a_(t,e){if(o_(t))return async function*(){for await(let a of t)yield e(a)}();let r=Ho(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var My=a_;async function*ps(t,e){yield*My(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function aa(t){let e=new Set;return Nt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*ca(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new E(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var ua=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new E("No content routers available",D.ERR_NO_ROUTERS_AVAILABLE);yield*wn(Vr(...this.routers.map(n=>n.findProviders(e,r))),n=>ps(n,this.components.peerStore),n=>aa(n),n=>ca(n))}async provide(e,r={}){if(this.routers.length===0)throw new E("No content routers available",D.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new E(Zt.NOT_STARTED_YET,D.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new E(Zt.NOT_STARTED_YET,D.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function c_(t){return t[Symbol.asyncIterator]!=null}function u_(t){if(c_(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var la=u_;var l_=G("libp2p:peer-routing"),fa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new E("No peer routers available",D.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new E("Should not try to find self",D.ERR_FIND_SELF);let n=await wn(Vr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){l_.error(s)}}())),i=>Nt(i,Boolean),i=>ps(i,this.components.peerStore),async i=>la(i));if(n!=null)return n;throw new E(Zt.NOT_FOUND,D.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new E("No peer routers available",D.ERR_NO_ROUTERS_AVAILABLE);yield*wn(Vr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>ps(n,this.components.peerStore),n=>aa(n),n=>ca(n))}};var f_=Symbol.for("@libp2p/topology");function Fy(t){return t!=null&&!!t[f_]}var ha=G("libp2p:registrar"),Ml=32,Fl=64,da=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,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(e){let r=this.handlers.get(e);if(r==null)throw new E(`No handler registered for protocol ${e}`,D.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,D.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Pr.bind({ignoreUndefined:!0})({maxInboundStreams:Ml,maxOutboundStreams:Fl},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(!Fy(r))throw ha.error("topology must be an instance of interfaces/topology"),new E("topology must be an instance of interfaces/topology",D.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),await r.setRegistrar(this),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(r)}}).catch(n=>{n.code!==D.ERR_NOT_FOUND&&ha.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){ha("peer %p connected but the connection manager did not have a connection",n);return}for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onConnect(r,i)}}).catch(n=>{n.code!==D.ERR_NOT_FOUND&&ha.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o)),s=r.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect(r.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect(r.id,u)}}}};var Ul=class extends Map{constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Uy(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ul({name:e,metrics:r}):n=new Map,n}var vn=G("libp2p:transports"),pa=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=Uy({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Ur.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new E("Transport must have a valid tag",D.ERR_INVALID_KEY);if(this.transports.has(r))throw new E(`There is already a transport with the tag ${r}`,D.ERR_DUPLICATE_TRANSPORT);vn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(vn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),vn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,D.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=D.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(e==null||e.length===0){vn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){vn("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(d=>d===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ur.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,D.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Ur.FATAL_ALL)throw new E(n,D.ERR_NO_VALID_ADDRESSES);vn(`libp2p in dial mode only: ${n}`)}}async remove(e){vn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var zl=V(bi(),1);var dr="/multistream/1.0.0";function ma(t){return t[Symbol.asyncIterator]!=null}var ya=t=>{let e=Lt.encodingLength(t),r=St(e);return Lt.encode(t,r),ya.bytes=e,r};ya.bytes=0;function ga(t,e){e=e??{};let r=e.lengthEncoder??ya;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ma(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}ga.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??ya;return new Ae(r(t.byteLength),t)};var wi=V(il(),1);var h_=8,d_=1024*1024*4,En;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(En||(En={}));var Kl=t=>{let e=Lt.decode(t);return Kl.bytes=Lt.encodingLength(e),e};Kl.bytes=0;function ms(t,e){let r=new Ae,n=En.LENGTH,i=-1,s=e?.lengthDecoder??Kl,o=e?.maxLengthLength??h_,a=e?.maxDataLength??d_;function*c(){for(;r.byteLength>0;){if(n===En.LENGTH)try{if(i=s(r),i<0)throw(0,wi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,wi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=En.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,wi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===En.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=En.LENGTH}}}return ma(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,wi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,wi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}ms.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return ms(n,{...e??{},onLength:s=>{r=s}})};var ys=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Ky(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function xa(t,e,r){let n=r??{},i=Ky(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new ys(l,f)}let u=new Promise((l,f)=>{o=()=>{let{abortMessage:h,abortCode:d}=n;f(new ys(h,d))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function m_(t,e,r){return n=>t(xa(n,e,r))}function Vy(t,e,r){return{sink:m_(t.sink,e,{...r,onAbort:void 0}),source:xa(t.source,e,r)}}var g_=G("libp2p:mss"),qy=U(`
48
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),jE=new RegExp(`(?:^${kt}$)|(?:^${Qo}$)`),JE=new RegExp(`^${kt}$`),eb=new RegExp(`^${Qo}$`),al=t=>t&&t.exact?jE:new RegExp(`(?:${Fr(t)}${kt}${Fr(t)})|(?:${Fr(t)}${Qo}${Fr(t)})`,"g");al.v4=t=>t&&t.exact?JE:new RegExp(`${Fr(t)}${kt}${Fr(t)}`,"g");al.v6=t=>t&&t.exact?eb:new RegExp(`${Fr(t)}${Qo}${Fr(t)}`,"g");var xm=al;var _m=V(vm(),1),{isValid:tb,parse:rb}=_m.default,nb=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],ib=nb.map(t=>new bm.Netmask(t));function sb(t){for(let e of ib)if(e.contains(t))return!0;return!1}function Em(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var Sm=t=>{if(tb(t)){let e=rb(t);if(e.kind()==="ipv4")return sb(e.toNormalizedString());if(e.kind()==="ipv6")return Em(t)}else if(ni(t)&&xm.v6().test(t))return Em(t)};var Zo=Sm;function Am(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Zo(`${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,...t}}var c3=Symbol.for("@libp2p/transport");var Ur;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ur||(Ur={}));function cl(t){try{let{address:e}=t.nodeAddress();return!!Zo(e)}catch{return!0}}function ui(t,e){let r=cl(t.multiaddr),n=cl(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var ll=V(du(),1),fl=V(Cm(),1);var Tm=globalThis.fetch,Bm=globalThis.Headers,m3=globalThis.Request,y3=globalThis.Response;function jo(t,e,r){return`${t}?name=${e}&type=${r}`}async function Lm(t,e){return await(await Tm(t,{headers:new Bm({accept:"application/dns-json"}),signal:e})).json()}function gn(t,e){return`${e}_${t}`}var ul=Object.assign((0,ll.default)("dns-over-http-resolver"),{error:(0,ll.default)("dns-over-http-resolver:error")}),hl=class{constructor(e={}){this._cache=new fl.default({max:e?.maxCache??100}),this._TXTcache=new fl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Lm,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(jo(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),ul.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Pm=hl;var Dm=Pm;var{code:lb}=ce("dnsaddr");async function li(t,e={}){let r=new Dm;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===lb)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Zt;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(Zt||(Zt={}));var D;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(D||(D={}));var fb={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:li},addressSorter:ui},transportManager:{faultTolerance:Ur.FATAL_ALL}};function Nm(t){let e=Pr(fb,t);if(e.transports==null||e.transports.length<1)throw new E(Zt.ERR_TRANSPORTS_REQUIRED,D.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Zt.ERR_PROTECTOR_REQUIRED,D.ERR_PROTECTOR_REQUIRED);return e}var km="keep-alive";var Ny=V(By(),1);var Yb=G("libp2p:get-peer");function ea(t){if(vo(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:ie(r),t.forEach(n=>{if(!pn(n))throw Yb.error("multiaddr %s was invalid",n),new E("Invalid Multiaddr",D.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",D.ERR_INVALID_PARAMETERS)}else{let s=ie(i);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",D.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}var jt=G("libp2p:connection-manager:auto-dial"),ta={minConnections:50,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},ra=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialInterval;started;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??ta.minConnections,this.autoDialPriority=r.autoDialPriority??ta.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??ta.autoDialInterval,this.started=!1,this.queue=new Dt({concurrency:r.autoDialConcurrency??ta.autoDialConcurrency}),this.queue.addListener("error",n=>{jt.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{jt.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setInterval(()=>{this.autoDial().catch(e=>{jt.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{jt.error("error while autodialing",e)})}stop(){this.queue.clear(),clearInterval(this.autoDialInterval),this.started=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size,n=new Bt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean));if(r>=this.minConnections){jt.trace("have enough connections %d/%d",r,this.minConnections);return}jt("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let i=await this.peerStore.all(),o=i.filter(u=>!(u.addresses.length===0||e.has(u.id)||n.has(u.id))).sort(()=>Math.random()>.5?1:-1),a=new lr;for(let u of o)a.has(u.id)||a.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=o.sort((u,l)=>{let f=a.get(u.id)??0,h=a.get(l.id)??0;return f>h?-1:f<h?1:0});jt("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){jt("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}jt("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})}).catch(l=>{jt.error("could not connect to peerStore stored peer",l)})}};var mi=G("libp2p:connection-manager:connection-pruner"),Ly={maxConnections:300,allow:[]},na=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Ly.maxConnections,this.allow=r.allow??Ly.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{mi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(mi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;mi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new lr;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&mi.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.stat.timeline.open,h=c.stat.timeline.open;return f<h?1:f>h?-1:0}),o=[];for(let a of s)if(mi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){mi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var Pl=V(bi(),1);function yi(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function hs(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Bl=V(bi(),1);var Py=G("libp2p:connection-manager:utils");async function Ll(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await Qb(t,e),o=(await Promise.all(n.map(async a=>Ll(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Py("resolved %s to",t,o.map(a=>a.toString())),o}async function Qb(t,e){try{return t=Ne(t.toString()),await t.resolve(e)}catch(r){return Py.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Dy(...t){let e=[];for(let n of t)if(n!=null){try{(0,Bl.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=yi(e);try{(0,Bl.setMaxListeners)?.(1/0,r)}catch{}return r}var Ye=G("libp2p:connection-manager:dial-queue"),ds={addressSorter:ui,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:li}},ia=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??ds.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??ds.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??ds.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??ds.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,Pl.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))Nu.set(n,i);this.queue=new Dt({concurrency:r.maxParallelDials??ds.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=>{Ye.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(e,r={}){let{peerId:n,multiaddrs:i}=ea(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return Ye("joining existing dial target for %p",n),o.clear(),c.promise;Ye("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:Zb(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(l=>{throw Ye.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),o.aborted?new E(l.message,D.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=yi([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,Pl.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new E("Tried to dial self",D.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",D.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){Ye("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),Ye("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==D.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Ll(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),s=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),o=new Map;for(let l of s){let f=l.multiaddr.toString(),h=o.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(Ye("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),Ye("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new E("The dial request has no valid addresses",D.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new E("dial with more addresses than allowed",D.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new E("The connection gater denied all addresses in the dial request",D.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Dt({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{Ye.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new E("dialAction did not come with an AbortController",D.ERR_INVALID_PARAMETERS);let u=Dy(c.signal,r.signal);u.addEventListener("abort",()=>{Ye("dial to %s aborted",o)});let l=hs();return await i.add(async()=>{if(u.aborted){Ye("dial to %s was aborted before reaching the head of the peer dial queue",o),l.reject(new xr);return}await this.queue.add(async()=>{try{if(u.aborted){Ye("dial to %s was aborted before reaching the head of the dial queue",o),l.reject(new xr);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){Ye("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{Ye.error("error closing superfluous connection",h)}),l.reject(new xr);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),Ye("dial to %s succeeded",o),l.resolve(f)}catch(f){Ye.error("error during dial of %s",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new E("successful dial led to empty object returned from peer dial queue",D.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function Zb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var mt=G("libp2p:connection-manager"),e_=50,gi={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0},sa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??gi.maxConnections;let n=r.minConnections??gi.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",D.ERR_INVALID_PARAMETERS);this.connections=new lr,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ne(i)),this.deny=(r.deny??[]).map(i=>Ne(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??gi.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Ny.RateLimiterMemory({points:r.inboundConnectionThreshold??gi.inboundConnectionThreshold,duration:1}),this.autoDial=new ra({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??gi.autoDialConcurrency,autoDialPriority:r.autoDialPriority??gi.autoDialPriority}),this.connectionPruner=new na({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ia({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??ui,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:li}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.stat.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.stat.direction} ${i.stat.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.stat.direction} ${o.stat.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,mt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=[];for(let r of await this.peerStore.all())r.tags.has(km)&&e.push(r.id);await Promise.all(e.map(async r=>{await this.openConnection(r).catch(n=>{mt.error(n)})}))}).catch(e=>{mt.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){mt.error(i)}})());mt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),mt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{mt.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new E("Not started",D.ERR_NODE_NOT_STARTED);let{peerId:n}=ea(e);if(n!=null){mt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return mt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??e_}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e){let r=this.connections.get(e)??[];await Promise.all(r.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return mt("connection from %s refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return mt("connection from %s refused - incomingPendingConnections exceeded by peer %s",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return mt("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(mt("connection from %s refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var oa=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},xi=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new oa(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new oa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function xn(t={}){return t_(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function t_(t,e){e=e??{};let r=e.onEnd,n=new xi,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((m,y)=>{s=g=>{s=null,n.push(g);try{m(t(n))}catch(w){y(w)}return i}}):t(n),c=m=>s!=null?s(m):(n.push(m),i),u=m=>(n=new xi,s!=null?s({error:m}):(n.push({error:m}),i)),l=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},f=m=>o?i:(o=!0,m!=null?u(m):c({done:!0})),h=()=>(n=new xi,f(),{done:!0}),d=m=>(f(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:d,push:l,end:f,get readableLength(){return n.size}},r==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(m){return p.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return p.readableLength}},i}function r_(t){return t[Symbol.asyncIterator]!=null}function n_(...t){let e=[];for(let r of t)r_(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=xn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Vr=n_;function wn(t,...e){if(t==null)throw new Error("Empty pipeline");if(Ol(t)){let n=t;t=()=>n.source}else if(Oy(t)||ky(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Ol(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Ol(r[n])&&(r[n]=s_(r[n]));return i_(...r)}var i_=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},ky=t=>t?.[Symbol.asyncIterator]!=null,Oy=t=>t?.[Symbol.iterator]!=null,Ol=t=>t==null?!1:t.sink!=null&&t.source!=null,s_=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=xn({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(ky(s))i=async function*(){yield*s,n.end()};else if(Oy(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vr(n,i())}return t.source};function o_(t){return t[Symbol.asyncIterator]!=null}function a_(t,e){if(o_(t))return async function*(){for await(let a of t)yield e(a)}();let r=Ho(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var My=a_;async function*ps(t,e){yield*My(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function aa(t){let e=new Set;return Nt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*ca(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new E(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var ua=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new E("No content routers available",D.ERR_NO_ROUTERS_AVAILABLE);yield*wn(Vr(...this.routers.map(n=>n.findProviders(e,r))),n=>ps(n,this.components.peerStore),n=>aa(n),n=>ca(n))}async provide(e,r={}){if(this.routers.length===0)throw new E("No content routers available",D.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new E(Zt.NOT_STARTED_YET,D.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new E(Zt.NOT_STARTED_YET,D.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function c_(t){return t[Symbol.asyncIterator]!=null}function u_(t){if(c_(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var la=u_;var l_=G("libp2p:peer-routing"),fa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new E("No peer routers available",D.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new E("Should not try to find self",D.ERR_FIND_SELF);let n=await wn(Vr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){l_.error(s)}}())),i=>Nt(i,Boolean),i=>ps(i,this.components.peerStore),async i=>la(i));if(n!=null)return n;throw new E(Zt.NOT_FOUND,D.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new E("No peer routers available",D.ERR_NO_ROUTERS_AVAILABLE);yield*wn(Vr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>ps(n,this.components.peerStore),n=>aa(n),n=>ca(n))}};var f_=Symbol.for("@libp2p/topology");function Fy(t){return t!=null&&!!t[f_]}var ha=G("libp2p:registrar"),Ml=32,Fl=64,da=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,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(e){let r=this.handlers.get(e);if(r==null)throw new E(`No handler registered for protocol ${e}`,D.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,D.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Pr.bind({ignoreUndefined:!0})({maxInboundStreams:Ml,maxOutboundStreams:Fl},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(!Fy(r))throw ha.error("topology must be an instance of interfaces/topology"),new E("topology must be an instance of interfaces/topology",D.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),await r.setRegistrar(this),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(r)}}).catch(n=>{n.code!==D.ERR_NOT_FOUND&&ha.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){ha("peer %p connected but the connection manager did not have a connection",n);return}for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onConnect(r,i)}}).catch(n=>{n.code!==D.ERR_NOT_FOUND&&ha.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o)),s=r.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect(r.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect(r.id,u)}}}};var Ul=class extends Map{constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Uy(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ul({name:e,metrics:r}):n=new Map,n}var vn=G("libp2p:transports"),pa=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=Uy({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Ur.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new E("Transport must have a valid tag",D.ERR_INVALID_KEY);if(this.transports.has(r))throw new E(`There is already a transport with the tag ${r}`,D.ERR_DUPLICATE_TRANSPORT);vn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(vn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),vn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,D.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=D.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(e==null||e.length===0){vn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){vn("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(d=>d===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ur.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,D.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Ur.FATAL_ALL)throw new E(n,D.ERR_NO_VALID_ADDRESSES);vn(`libp2p in dial mode only: ${n}`)}}async remove(e){vn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var zl=V(bi(),1);var dr="/multistream/1.0.0";function ma(t){return t[Symbol.asyncIterator]!=null}var ya=t=>{let e=Lt.encodingLength(t),r=St(e);return Lt.encode(t,r),ya.bytes=e,r};ya.bytes=0;function ga(t,e){e=e??{};let r=e.lengthEncoder??ya;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ma(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}ga.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??ya;return new Ae(r(t.byteLength),t)};var wi=V(il(),1);var h_=8,d_=1024*1024*4,En;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(En||(En={}));var Kl=t=>{let e=Lt.decode(t);return Kl.bytes=Lt.encodingLength(e),e};Kl.bytes=0;function ms(t,e){let r=new Ae,n=En.LENGTH,i=-1,s=e?.lengthDecoder??Kl,o=e?.maxLengthLength??h_,a=e?.maxDataLength??d_;function*c(){for(;r.byteLength>0;){if(n===En.LENGTH)try{if(i=s(r),i<0)throw(0,wi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,wi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=En.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,wi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===En.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=En.LENGTH}}}return ma(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,wi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,wi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}ms.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return ms(n,{...e??{},onLength:s=>{r=s}})};var ys=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Ky(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function xa(t,e,r){let n=r??{},i=Ky(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new ys(l,f)}let u=new Promise((l,f)=>{o=()=>{let{abortMessage:h,abortCode:d}=n;f(new ys(h,d))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function m_(t,e,r){return n=>t(xa(n,e,r))}function Vy(t,e,r){return{sink:m_(t.sink,e,{...r,onAbort:void 0}),source:xa(t.source,e,r)}}var g_=G("libp2p:mss"),qy=U(`
49
49
  `);function gs(t){let e=new Ae(t,qy);return ga.single(e)}function bn(t,e,r={}){let n=gs(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function $y(t,e,r={}){let n=new Ae;for(let i of e)n.append(gs(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function x_(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await t.next(r)},i=n;e?.signal!=null&&(i=xa(n,e.signal));let s=a=>{r=a},o=await wn(i,a=>ms(a,{onLength:s,maxDataLength:1024}),async a=>await la(a));if(o==null||o.length===0)throw new E("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==qy[0])throw g_.error("Invalid mss message - missing newline - %s",o.subarray()),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function vi(t,e){let r=await x_(t,e);return $(r.subarray())}function Vl(t){let e=async function*(){let r=yield,n=new Ae;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Ae;continue}for(n.append(i);n.length>=r;){let s=n.sublist(0,r);if(n.consume(r),r=yield s,r==null){n.length>0&&(r=yield n,n=new Ae);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function wa(t){let e=xn(),r=Vl(t.source),n=hs(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var xs=G("libp2p:mss:select");async function ws(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=wa(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");xs.trace('select: write ["%s", "%s"]',dr,a);let c=U(dr),u=U(a);$y(i,[c,u],r);let l=await vi(n,r);if(xs.trace('select: read "%s"',l),l===dr&&(l=await vi(n,r),xs.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let f of e){xs.trace('select: write "%s"',f),bn(i,U(f),r);let h=await vi(n,r);if(xs.trace('select: read "%s" for "%s"',h,f),h===f)return s(),{stream:o,protocol:f}}throw s(),new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var vs=G("libp2p:mss:handle");async function Es(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=wa(t);for(;;){let a=await vi(i,r);if(vs.trace('read "%s"',a),a===dr){vs.trace('respond with "%s" for "%s"',dr,a),bn(n,U(dr),r);continue}if(e.includes(a))return bn(n,U(a),r),vs.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){bn(n,new Ae(...e.map(c=>gs(U(c)))),r),vs.trace('respond with "%s" for %s',e,a);continue}bn(n,U("na"),r),vs('respond with "na" for "%s"',a)}}var Hy=Symbol.for("@libp2p/connection");var Gy="OPEN",ql="CLOSING",va="CLOSED";var v_=G("libp2p:connection"),$l=class{id;remoteAddr;remotePeer;stat;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.stat={...a,status:Gy},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[Hy]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.stat.status===ql)throw new E("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===va)throw new E("the connection is closed","ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,r);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===va||this._closing)){this.stat.status=ql;try{this.streams.forEach(e=>{e.close()})}catch(e){v_.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=va}}};function Yy(t){return new $l(t)}var we=G("libp2p:upgrader");function b_(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==D.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Ml}function __(t,e){try{let{options:r}=e.getHandler(t);return r.maxOutboundStreams}catch(r){if(r.code!==D.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Fl}function Wy(t,e,r){let n=0;return r.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===t&&n++}),n}var Ea=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,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??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new E(`The multiaddr connection is blocked by gater.${n}`,D.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",D.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=yi([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,zl.setMaxListeners)?.(1/0,u)}catch{}try{let l=Vy(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",D.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),we("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(we("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new E("inbound connection that skipped encryption must have a peer id",D.ERR_INVALID_MULTIADDR);let d=ie(h);c="native",s=d}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw we.error("Failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),we("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=ie(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),we("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...s};await this.shouldBlockConnection(o,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new E("Encryption was skipped but no peer id was passed",D.ERR_INVALID_PEER);c="native",o=i}if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw we.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),we("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await Es(d,p);if(we("%s: incoming stream opened on %s",n,y),l==null)return;let g=b_(y,this.components.registrar);if(Wy(y,"inbound",l)===g){let _=new E(`Too many inbound protocol streams for protocol "${y}" - limit ${g}`,D.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(_),_}d.source=m.source,d.sink=m.sink,d.stat.protocol=y,await this.components.peerStore.merge(o,{protocols:[y]}),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:y})}).catch(p=>{we.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw new E("Stream is not multiplexed",D.ERR_MUXER_UNAVAILABLE);we("%s: starting new stream on %s",n,d);let m=await c.newStream();try{if(p.signal==null){we("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),p.signal=AbortSignal.timeout(3e4);try{(0,zl.setMaxListeners)?.(1/0,p.signal)}catch{}}let{stream:y,protocol:g}=await ws(m,d,p),w=__(g,this.components.registrar);if(Wy(g,"outbound",l)===w){let N=new E(`Too many outbound protocol streams for protocol "${g}" - limit ${w}`,D.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(N),N}return await this.components.peerStore.merge(o,{protocols:[g]}),m.source=y.source,m.sink=y.sink,m.stat.protocol=g,this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw we.error("could not create new stream",y),m.stat.timeline.close==null&&m.close(),y.code!=null?y:new E(String(y),D.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{we.error(d)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){we.error(p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{we.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",D.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Yy({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:r},newStream:u??h,getStreams:()=>c!=null?c.streams:h(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());we("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await Es(e,r,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return we("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new E(String(n),D.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());we("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await ws(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return we("encrypting outbound connection to %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw new E(String(i),D.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());we("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await ws(e,n,{writeBytes:!0});we("%s selected as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw we.error("error multiplexing outbound stream",i),new E(String(i),D.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());we("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await Es(e,n,{writeBytes:!0}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw we.error("error multiplexing inbound stream",i),new E(String(i),D.ERR_MUXER_UNAVAILABLE)}}};var nt=G("libp2p"),Hl=class extends Qi{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new Qi,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new fu(c.type,{detail:c.detail}));return u||l};try{(0,Qy.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=mm({peerId:e.peerId,events:r,datastore:e.datastore??new Yo,connectionGater:Am(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new zo(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ea(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new pa(this.components,e.transportManager)),this.configureComponent("connectionManager",new sa(this.components,e.connectionManager)),this.configureComponent("registrar",new da(this.components)),this.configureComponent("addressManager",new Wo(this.components,e.addresses));let s=dn.generateOptions();this.keychain=this.configureComponent("keyChain",new dn(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new fa(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ua(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){nt.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[au]!=null&&(nt("registering service %s for content routing",c),a.push(l[au])),l[uu]!=null&&(nt("registering service %s for peer routing",c),o.push(l[uu])),l[cu]!=null&&(nt("registering service %s for peer discovery",c),l[cu].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&nt.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,nt("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(nt("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}),nt("libp2p has started")}catch(r){throw nt.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(nt("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),nt("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Bt;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new E("no protocols were provided to open a stream",D.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new E("no protocols were provided to open a stream",D.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){pn(e)&&(e=ie(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,r={}){if(nt("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Ce([U("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,r);return cn(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){nt.error(new Error(D.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{nt.error(n)})}};async function Xy(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new dn({datastore:e},Pr(dn.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await ap()),new Hl(Nm(t))}async function S_(t){let e=await Xy(t);return t.start!==!1&&await e.start(),e}return ng(A_);})();
50
50
  /*! Bundled license information:
51
51