libp2p 1.9.3-1675adee2 → 1.9.3-2265e59ba

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
@@ -1,23 +1,23 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2P=(()=>{var mp=Object.create;var To=Object.defineProperty;var gp=Object.getOwnPropertyDescriptor;var yp=Object.getOwnPropertyNames;var wp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var _t=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)To(r,t,{get:e[t],enumerable:!0})},cu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yp(e))!bp.call(r,o)&&o!==t&&To(r,o,{get:()=>e[o],enumerable:!(n=gp(e,o))||n.enumerable});return r};var pr=(r,e,t)=>(t=r!=null?mp(wp(r)):{},cu(e||!r||!r.__esModule?To(t,"default",{value:r,enumerable:!0}):t,r)),Ep=r=>cu(To({},"__esModule",{value:!0}),r);var df=_t(on=>{"use strict";var Zg="[object ArrayBuffer]",Nt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Zg}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},gc="string",Qg=/^[0-9a-f]+$/i,Jg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,e0=/^[a-zA-Z0-9-_]+$/,Zo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Nt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},tt=class{static toString(e,t=!1){let n=Nt.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},Qo=class r{static isHex(e){return typeof e===gc&&Qg.test(e)}static isBase64(e){return typeof e===gc&&Jg.test(e)}static isBase64Url(e){return typeof e===gc&&e0.test(e)}static ToString(e,t="utf8"){let n=Nt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return tt.toString(n,!0);case"utf16":case"utf16be":return tt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return tt.fromString(e,!0);case"utf16":case"utf16be":return tt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Nt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Zo.fromString(e);case"utf16":case"utf16be":return tt.fromString(e);case"utf16le":case"usc2":return tt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Zo.toString(e);case"utf16":case"utf16be":return tt.toString(e);case"utf16le":case"usc2":return tt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Nt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Nt.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return tt.toString(e,t)}static FromUtf16String(e,t=!1){return tt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Qo.DEFAULT_UTF8_ENCODING="utf8";function t0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function r0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function n0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}on.BufferSourceConverter=Nt;on.Convert=Qo;on.assign=t0;on.combine=r0;on.isEqual=n0});var Ih=_t((io,qs)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var d=0;d<h.length;d++)if(!Number.isInteger(h[d])||h[d]<0||h[d]>255)return!1;return!0}function o(h,d){return(h&65535)*d+(((h>>>16)*d&65535)<<16)}function s(h,d){return h<<d|h>>>32-d}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*d[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*d[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*d[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*d[3]+h[1]*d[2]+h[2]*d[1]+h[3]*d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,d){return d%=64,d===32?[h[1],h[0]]:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d|h[0]>>>32-d]:(d-=32,[h[1]<<d|h[0]>>>32-d,h[0]<<d|h[1]>>>32-d])}function f(h,d){return d%=64,d===0?h:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d]:[h[1]<<d-32,0]}function l(h,d){return[h[0]^d[0],h[1]^d[1]]}function p(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%4,w=h.length-m,g=d,y=0,b=3432918353,x=461845907,A=0;A<w;A=A+4)y=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,y=o(y,b),y=s(y,15),y=o(y,x),g^=y,g=s(g,13),g=o(g,5)+3864292196;switch(y=0,m){case 3:y^=h[A+2]<<16;case 2:y^=h[A+1]<<8;case 1:y^=h[A],y=o(y,b),y=s(y,15),y=o(y,x),g^=y}return g^=h.length,g=i(g),g>>>0},t.x86.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=d,y=d,b=d,x=d,A=0,R=0,_=0,I=0,$=597399067,V=2869860233,K=951274213,Q=2716044179,D=0;D<w;D=D+16)A=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,R=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,_=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,I=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,A=o(A,$),A=s(A,15),A=o(A,V),g^=A,g=s(g,19),g+=y,g=o(g,5)+1444728091,R=o(R,V),R=s(R,16),R=o(R,K),y^=R,y=s(y,17),y+=b,y=o(y,5)+197830471,_=o(_,K),_=s(_,17),_=o(_,Q),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,I=o(I,Q),I=s(I,18),I=o(I,$),x^=I,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(A=0,R=0,_=0,I=0,m){case 15:I^=h[D+14]<<16;case 14:I^=h[D+13]<<8;case 13:I^=h[D+12],I=o(I,Q),I=s(I,18),I=o(I,$),x^=I;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,K),_=s(_,17),_=o(_,Q),b^=_;case 8:R^=h[D+7]<<24;case 7:R^=h[D+6]<<16;case 6:R^=h[D+5]<<8;case 5:R^=h[D+4],R=o(R,V),R=s(R,16),R=o(R,K),y^=R;case 4:A^=h[D+3]<<24;case 3:A^=h[D+2]<<16;case 2:A^=h[D+1]<<8;case 1:A^=h[D],A=o(A,$),A=s(A,15),A=o(A,V),g^=A}return g^=h.length,y^=h.length,b^=h.length,x^=h.length,g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,g=i(g),y=i(y),b=i(b),x=i(x),g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=[0,d],y=[0,d],b=[0,0],x=[0,0],A=[2277735313,289559509],R=[1291169091,658871167],_=0;_<w;_=_+16)b=[h[_+4]|h[_+5]<<8|h[_+6]<<16|h[_+7]<<24,h[_]|h[_+1]<<8|h[_+2]<<16|h[_+3]<<24],x=[h[_+12]|h[_+13]<<8|h[_+14]<<16|h[_+15]<<24,h[_+8]|h[_+9]<<8|h[_+10]<<16|h[_+11]<<24],b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b),g=u(g,27),g=a(g,y),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x),y=u(y,31),y=a(y,g),y=a(c(y,[0,5]),[0,944331445]);switch(b=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[_+14]],48));case 14:x=l(x,f([0,h[_+13]],40));case 13:x=l(x,f([0,h[_+12]],32));case 12:x=l(x,f([0,h[_+11]],24));case 11:x=l(x,f([0,h[_+10]],16));case 10:x=l(x,f([0,h[_+9]],8));case 9:x=l(x,[0,h[_+8]]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x);case 8:b=l(b,f([0,h[_+7]],56));case 7:b=l(b,f([0,h[_+6]],48));case 6:b=l(b,f([0,h[_+5]],40));case 5:b=l(b,f([0,h[_+4]],32));case 4:b=l(b,f([0,h[_+3]],24));case 3:b=l(b,f([0,h[_+2]],16));case 2:b=l(b,f([0,h[_+1]],8));case 1:b=l(b,[0,h[_]]),b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b)}return g=l(g,[0,h.length]),y=l(y,[0,h.length]),g=a(g,y),y=a(y,g),g=p(g),y=p(y),g=a(g,y),y=a(y,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)},typeof io<"u"?(typeof qs<"u"&&qs.exports&&(io=qs.exports=t),io.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(io)});var Bh=_t((Jv,Th)=>{Th.exports=Ih()});var Jh=_t((B2,tl)=>{"use strict";var Ty=Object.prototype.hasOwnProperty,He="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(He=!1));function By(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Qh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new By(t,n||r,o),i=He?He+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Zs(r,e){--r._eventsCount===0?r._events=new ho:delete r._events[e]}function Oe(){this._events=new ho,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ty.call(t,n)&&e.push(He?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Oe.prototype.listeners=function(e){var t=He?He+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Oe.prototype.listenerCount=function(e){var t=He?He+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Oe.prototype.emit=function(e,t,n,o,s,i){var a=He?He+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;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,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var p=c.length,h;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Oe.prototype.on=function(e,t,n){return Qh(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Qh(this,e,t,n,!0)};Oe.prototype.removeListener=function(e,t,n,o){var s=He?He+e:e;if(!this._events[s])return this;if(!t)return Zs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Zs(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Zs(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&Zs(this,t)):(this._events=new ho,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=He;Oe.EventEmitter=Oe;typeof tl<"u"&&(tl.exports=Oe)});var pd=_t((WS,dd)=>{"use strict";function hd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Gy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return hd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),hd(new o,t)}}dd.exports=Gy});var Ed=_t(yo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,p;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,p=c&255,[u,f,l,p].join(".")},i=function(c){var u,f,l,p,h,d;for(u=[],l=p=0;p<=3&&c.length!==0;l=++p){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),h=d[0],f=d[1],c=c.substring(f),u.push(h)}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")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,p,h;for(p=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)p=p*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")p=p*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")p=p*u+(10+t(c[l])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[p,l]},r=function(){function c(u,f){var l,p,h,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);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):(i(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 f,l,p;for(p=i(this.first),l=i(this.last),f=0;p<=l;)u(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),yo.ip2long=i,yo.long2ip=a,yo.Netmask=r}).call(yo)});var Ld=_t((rI,Nd)=>{Nd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Md=_t((EI,Ud)=>{"use strict";Ud.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var qd=_t((Hd,$d)=>{"use strict";var wi=Md(),{hasOwnProperty:Vd}=Object.prototype,{propertyIsEnumerable:Ew}=Object,An=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),xw=Hd,Fd={concatArrays:!1,ignoreUndefined:!1},bi=r=>{let e=[];for(let t in r)Vd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ew.call(r,n)&&e.push(n)}return e};function Sn(r){return Array.isArray(r)?vw(r):wi(r)?_w(r):r}function vw(r){let e=r.slice(0,0);return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}function _w(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}var Kd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?An(r,o,kl(r[o],e[o],n)):An(r,o,Sn(e[o])))}),r),Aw=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Vd.call(s,a)&&(i.push(String(a)),s===r?An(n,o++,s[a]):An(n,o++,Sn(s[a])));n=Kd(n,s,bi(s).filter(a=>!i.includes(a)),t)}),n};function kl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Aw(r,e,t):!wi(e)||!wi(r)?Sn(e):Kd(r,e,bi(e),t)}$d.exports=function(...r){let e=kl(Sn(Fd),this!==xw&&this||{},Fd),t={_:{}};for(let n of r)if(n!==void 0){if(!wi(n))throw new TypeError("`"+n+"` is not an Option Object");t=kl(t,{_:n},e)}return t._}});var rb={};ve(rb,{createLibp2p:()=>tb});var lu=Symbol.for("@libp2p/connection");var ia=Symbol.for("@libp2p/content-routing");var aa=Symbol.for("@libp2p/peer-discovery");var Bo=Symbol.for("@libp2p/peer-id");function Co(r){return r!=null&&!!r[Bo]}var ca=Symbol.for("@libp2p/peer-routing");var uu="keep-alive";var ub=Symbol.for("@libp2p/transport");var Ht;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var $t=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},E=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},ko=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var No="ERR_TIMEOUT";var ie=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),ie(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new la(e,t))}},la=globalThis.CustomEvent;function fu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var kn=Symbol.for("@libp2p/service-capabilities"),ua=Symbol.for("@libp2p/service-dependencies");var pc={};ve(pc,{Ed25519PrivateKey:()=>Ar,Ed25519PublicKey:()=>Hn,generateKeyPair:()=>Wg,generateKeyPairFromSeed:()=>hf,unmarshalEd25519PrivateKey:()=>Gg,unmarshalEd25519PublicKey:()=>Yg});var ma={};ve(ma,{base58btc:()=>ae,base58flickr:()=>Rp});var Vb=new Uint8Array(0);function hu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function St(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function du(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}function xp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,w=0,g=0,y=d.length;g!==y&&d[g]===0;)g++,m++;for(var b=(y-g)*f+1>>>0,x=new Uint8Array(b);g!==y;){for(var A=d[g],R=0,_=b-1;(A!==0||R<w)&&_!==-1;_--,R++)A+=256*x[_]>>>0,x[_]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");w=R,g++}for(var I=b-w;I!==b&&x[I]===0;)I++;for(var $=c.repeat(m);I<b;++I)$+=r.charAt(x[I]);return $}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var w=0,g=0;d[m]===c;)w++,m++;for(var y=(d.length-m)*u+1>>>0,b=new Uint8Array(y);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var A=0,R=y-1;(x!==0||A<g)&&R!==-1;R--,A++)x+=a*b[R]>>>0,b[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=A,m++}if(d[m]!==" "){for(var _=y-g;_!==y&&b[_]===0;)_++;for(var I=new Uint8Array(w+(y-_)),$=w;_!==y;)I[$++]=b[_++];return I}}}function h(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:h}}var vp=xp,_p=vp,gu=_p;var fa=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ha=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 yu(this,e)}},da=class{decoders;constructor(e){this.decoders=e}or(e){return yu(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function yu(r,e){return new da({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var pa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new fa(e,t,n),this.decoder=new ha(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kr({name:r,prefix:e,encode:t,decode:n}){return new pa(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gu(t,r);return Kr({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function Ap(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Sp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Kr({prefix:e,name:r,encode(o){return Sp(o,n,t)},decode(o){return Ap(o,n,t,r)}})}var ae=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rp=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ya={};ve(ya,{identity:()=>Rt});var Ip=Eu,wu=128,Tp=127,Bp=~Tp,Cp=Math.pow(2,31);function Eu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Cp;)e[t++]=r&255|wu,r/=128;for(;r&Bp;)e[t++]=r&255|wu,r>>>=7;return e[t]=r|0,Eu.bytes=t-n+1,e}var kp=ga,Np=128,bu=127;function ga(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ga.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&bu)<<o:(i&bu)*Math.pow(2,o),o+=7}while(i>=Np);return ga.bytes=s-n,t}var Lp=Math.pow(2,7),Dp=Math.pow(2,14),Pp=Math.pow(2,21),Op=Math.pow(2,28),Up=Math.pow(2,35),Mp=Math.pow(2,42),Fp=Math.pow(2,49),Vp=Math.pow(2,56),Kp=Math.pow(2,63),Hp=function(r){return r<Lp?1:r<Dp?2:r<Pp?3:r<Op?4:r<Up?5:r<Mp?6:r<Fp?7:r<Vp?8:r<Kp?9:10},$p={encode:Ip,decode:kp,encodingLength:Hp},qp=$p,Nn=qp;function Ln(r,e=0){return[Nn.decode(r,e),Nn.decode.bytes]}function Hr(r,e,t=0){return Nn.encode(r,e,t),e}function $r(r){return Nn.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=$r(r),o=n+$r(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new qr(r,t,e,s)}function mr(r){let e=St(r),[t,n]=Ln(e),[o,s]=Ln(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function xu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hu(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vu=0,zp="identity",_u=St;function Gp(r){return mt(vu,_u(r))}var Rt={code:vu,name:zp,encode:_u,digest:Gp};var Ea={};ve(Ea,{sha256:()=>Se,sha512:()=>Yp});function ba({name:r,code:e,encode:t}){return new wa(r,e,t)}var wa=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?mt(this.code,t):t.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Su(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Se=ba({name:"sha2-256",code:18,encode:Su("SHA-256")}),Yp=ba({name:"sha2-512",code:19,encode:Su("SHA-512")});function J(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function st(r=0){return new Uint8Array(r)}function ke(r=0){return new Uint8Array(r)}function Re(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ke(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var xa={};ve(xa,{base10:()=>Wp});var Wp=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var va={};ve(va,{base16:()=>jp,base16upper:()=>Xp});var jp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _a={};ve(_a,{base2:()=>Zp});var Zp=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Aa={};ve(Aa,{base256emoji:()=>rm});var Ru=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}"),Qp=Ru.reduce((r,e,t)=>(r[t]=e,r),[]),Jp=Ru.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function em(r){return r.reduce((e,t)=>(e+=Qp[t],e),"")}function tm(r){let e=[];for(let t of r){let n=Jp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rm=Kr({prefix:"\u{1F680}",name:"base256emoji",encode:em,decode:tm});var Sa={};ve(Sa,{base32:()=>Ye,base32hex:()=>im,base32hexpad:()=>cm,base32hexpadupper:()=>lm,base32hexupper:()=>am,base32pad:()=>om,base32padupper:()=>sm,base32upper:()=>nm,base32z:()=>um});var Ye=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nm=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),om=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),im=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),am=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),um=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ra={};ve(Ra,{base36:()=>fm,base36upper:()=>hm});var fm=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hm=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ta={};ve(Ta,{base64:()=>Dn,base64pad:()=>dm,base64url:()=>Ia,base64urlpad:()=>pm});var Dn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ia=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pm=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ba={};ve(Ba,{base8:()=>mm});var mm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ca={};ve(Ca,{identity:()=>gm});var gm=Kr({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>du(r)});var pE=new TextEncoder,mE=new TextDecoder;function Iu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Em(t,ka(r),e??ae.encoder);default:return xm(t,ka(r),e??Ye.encoder)}}var Tu=new WeakMap;function ka(r){let e=Tu.get(r);if(e==null){let t=new Map;return Tu.set(r,t),t}return e}var Qe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==vm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=mt(e,t);return r.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 r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&xu(e.multihash,n.multihash)}toString(e){return Iu(this,e)}toJSON(){return{"/":Iu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Bu(n,o,s.bytes))}else if(t[_m]===!0){let{version:n,multihash:o,code:s}=t,i=mr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Pn)throw new Error(`Version 0 CID must use dag-pb (code: ${Pn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Bu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=St(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Ln(e.subarray(t));return t+=p,l},o=n(),s=Pn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=bm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ka(s).set(n,e),s}};function bm(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Em(r,e,t){let{prefix:n}=t;if(n!==ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function xm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Pn=112,vm=18;function Bu(r,e,t){let n=$r(r),o=n+$r(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var _m=Symbol.for("@ipld/js-cid/CID");var zt={...Ca,..._a,...Ba,...xa,...va,...Sa,...Ra,...ma,...Ta,...Aa},kE={...Ea,...ya};function ku(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cu=ku("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Na=ku("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ke(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Am={utf8:Cu,"utf-8":Cu,hex:zt.base16,latin1:Na,ascii:Na,binary:Na,...zt},Do=Am;function L(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Je(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function zr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Sm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...e){if(!Sm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Po(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(r.outputLen),zr(r.blockLen)}function Yr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Nu(r,e){Gr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Oo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var jr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var zE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Rm=async()=>{};async function Lu(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Rm(),n+=s)}}function Du(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gt(r){return typeof r=="string"&&(r=Du(r)),Gr(r),r}function La(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Wr=class{clone(){return this._cloneInto()}},Im={}.toString;function Pu(r,e){if(e!==void 0&&Im.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Uo(r){let e=n=>r().update(Gt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xr(r=32){if(Oo&&typeof Oo.getRandomValues=="function")return Oo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Tm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Ou=(r,e,t)=>r&e^~r&t,Uu=(r,e,t)=>r&e^r&t^e&t,Zr=class extends Wr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=jr(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=Gt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=jr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),Nu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;Tm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=jr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Mo=BigInt(4294967295),Da=BigInt(32);function Mu(r,e=!1){return e?{h:Number(r&Mo),l:Number(r>>Da&Mo)}:{h:Number(r>>Da&Mo)|0,l:Number(r&Mo)|0}}function Bm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Mu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Cm=(r,e)=>BigInt(r>>>0)<<Da|BigInt(e>>>0),km=(r,e,t)=>r>>>t,Nm=(r,e,t)=>r<<32-t|e>>>t,Lm=(r,e,t)=>r>>>t|e<<32-t,Dm=(r,e,t)=>r<<32-t|e>>>t,Pm=(r,e,t)=>r<<64-t|e>>>t-32,Om=(r,e,t)=>r>>>t-32|e<<64-t,Um=(r,e)=>e,Mm=(r,e)=>r,Fm=(r,e,t)=>r<<t|e>>>32-t,Vm=(r,e,t)=>e<<t|r>>>32-t,Km=(r,e,t)=>e<<t-32|r>>>64-t,Hm=(r,e,t)=>r<<t-32|e>>>64-t;function $m(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var qm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),zm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ym=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Wm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),jm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Xm={fromBig:Mu,split:Bm,toBig:Cm,shrSH:km,shrSL:Nm,rotrSH:Lm,rotrSL:Dm,rotrBH:Pm,rotrBL:Om,rotr32H:Um,rotr32L:Mm,rotlSH:Fm,rotlSL:Vm,rotlBH:Km,rotlBL:Hm,add:$m,add3L:qm,add3H:zm,add4L:Gm,add4H:Ym,add5H:jm,add5L:Wm},M=Xm;var[Zm,Qm]=M.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Yt=new Uint32Array(80),Wt=new Uint32Array(80),Pa=class extends Zr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:p,Gh:h,Gl:d,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=p|0,this.Gh=h|0,this.Gl=d|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let b=0;b<16;b++,t+=4)Yt[b]=e.getUint32(t),Wt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Yt[b-15]|0,A=Wt[b-15]|0,R=M.rotrSH(x,A,1)^M.rotrSH(x,A,8)^M.shrSH(x,A,7),_=M.rotrSL(x,A,1)^M.rotrSL(x,A,8)^M.shrSL(x,A,7),I=Yt[b-2]|0,$=Wt[b-2]|0,V=M.rotrSH(I,$,19)^M.rotrBH(I,$,61)^M.shrSH(I,$,6),K=M.rotrSL(I,$,19)^M.rotrBL(I,$,61)^M.shrSL(I,$,6),Q=M.add4L(_,K,Wt[b-7],Wt[b-16]),D=M.add4H(Q,R,V,Yt[b-7],Yt[b-16]);Yt[b]=D|0,Wt[b]=Q|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:p,Fh:h,Fl:d,Gh:m,Gl:w,Hh:g,Hl:y}=this;for(let b=0;b<80;b++){let x=M.rotrSH(l,p,14)^M.rotrSH(l,p,18)^M.rotrBH(l,p,41),A=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),R=l&h^~l&m,_=p&d^~p&w,I=M.add5L(y,A,_,Qm[b],Wt[b]),$=M.add5H(I,g,x,R,Zm[b],Yt[b]),V=I|0,K=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),Q=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,N=o&i^o&c^i&c;g=m|0,y=w|0,m=h|0,w=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,$|0,V|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let S=M.add3L(V,Q,N);n=M.add3H(S,$,K,D),o=S|0}({h:n,l:o}=M.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=M.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=M.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=M.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:p}=M.add(this.Eh|0,this.El|0,l|0,p|0),{h,l:d}=M.add(this.Fh|0,this.Fl|0,h|0,d|0),{h:m,l:w}=M.add(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:y}=M.add(this.Hh|0,this.Hl|0,g|0,y|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,w,g,y)}roundClean(){Yt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var On=Uo(()=>new Pa);var Vo={};ve(Vo,{aInRange:()=>qe,abool:()=>at,abytes:()=>Qr,bitGet:()=>sg,bitLen:()=>og,bitMask:()=>Mn,bitSet:()=>ig,bytesToHex:()=>Tt,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>Va,ensureBytes:()=>le,equalBytes:()=>rg,hexToBytes:()=>yr,hexToNumber:()=>Fa,inRange:()=>Un,isBytes:()=>jt,memoized:()=>br,notImplemented:()=>cg,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>Ku,numberToVarBytesBE:()=>tg,utf8ToBytes:()=>ng,validateObject:()=>gt});var Ma=BigInt(0),Fo=BigInt(1),Jm=BigInt(2);function jt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qr(r){if(!jt(r))throw new Error("Uint8Array expected")}function at(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var eg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Tt(r){Qr(r);let e="";for(let t=0;t<r.length;t++)e+=eg[r[t]];return e}function Ku(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var It={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fu(r){if(r>=It._0&&r<=It._9)return r-It._0;if(r>=It._A&&r<=It._F)return r-(It._A-10);if(r>=It._a&&r<=It._f)return r-(It._a-10)}function yr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Fu(r.charCodeAt(s)),a=Fu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return Fa(Tt(r))}function Xt(r){return Qr(r),Fa(Tt(Uint8Array.from(r).reverse()))}function Zt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Zt(r,e).reverse()}function tg(r){return yr(Ku(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=yr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(jt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Ct(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Qr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function rg(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ng(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Oa=r=>typeof r=="bigint"&&Ma<=r;function Un(r,e,t){return Oa(r)&&Oa(e)&&Oa(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Un(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function og(r){let e;for(e=0;r>Ma;r>>=Fo,e+=1);return e}function sg(r,e){return r>>BigInt(e)&Fo}function ig(r,e,t){return r|(t?Fo:Ma)<<BigInt(e)}var Mn=r=>(Jm<<BigInt(r-1))-Fo,Ua=r=>new Uint8Array(r),Vu=r=>Uint8Array.from(r);function Va(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ua(r),o=Ua(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ua())=>{o=a(Vu([0]),l),n=a(),l.length!==0&&(o=a(Vu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,p=[];for(;l<e;){n=a();let h=n.slice();p.push(h),l+=n.length}return Ct(...p)};return(l,p)=>{i(),c(l);let h;for(;!(h=p(u()));)c();return i(),h}}var ag={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||jt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function gt(r,e,t={}){let n=(o,s,i)=>{let a=ag[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var cg=()=>{throw new Error("not implemented")};function br(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),ee=BigInt(1),Er=BigInt(2),lg=BigInt(3),Ka=BigInt(4),Hu=BigInt(5),$u=BigInt(8),ug=BigInt(9),fg=BigInt(16);function X(r,e){let t=r%e;return t>=ge?t:e+t}function hg(r,e,t){if(t<=ge||e<ge)throw new Error("Expected power/modulo > 0");if(t===ee)return ge;let n=ee;for(;e>ge;)e&ee&&(n=n*r%t),r=r*r%t,e>>=ee;return n}function te(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function Ko(r,e){if(r===ge||e<=ge)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=ge,s=ee,i=ee,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=o-i*u,p=s-a*u;n=t,t=f,o=i,s=a,i=l,a=p}if(n!==ee)throw new Error("invert: does not exist");return X(o,e)}function dg(r){let e=(r-ee)/Er,t,n,o;for(t=r-ee,n=0;t%Er===ge;t/=Er,n++);for(o=Er;o<r&&hg(o,e,r)!==r-ee;o++);if(n===1){let i=(r+ee)/Ka;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+ee)/Er;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(p);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let d=a.pow(f,ee<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function pg(r){if(r%Ka===lg){let e=(r+ee)/Ka;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%$u===Hu){let e=(r-Hu)/$u;return function(n,o){let s=n.mul(o,Er),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Er),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%fg,dg(r)}var qu=(r,e)=>(X(r,e)&ee)===ee,mg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ha(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=mg.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function gg(r,e,t){if(t<ge)throw new Error("Expected power > 0");if(t===ge)return r.ONE;if(t===ee)return e;let n=r.ONE,o=e;for(;t>ge;)t&ee&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ee;return n}function yg(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function $a(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Ho(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=$a(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=pg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Mn(o),ZERO:ge,ONE:ee,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&ee)===ee,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>gg(a,c,u),div:(c,u)=>X(c*Ko(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ko(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>yg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function zu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function qa(r){let e=zu(r);return e+Math.ceil(e/2)}function Gu(r,e,t=!1){let n=r.length,o=zu(e),s=qa(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Xt(r),a=X(i,e-ee)+ee;return t?wr(a,o):Zt(a,o)}var bg=BigInt(0),za=BigInt(1),Ga=new WeakMap,Yu=new WeakMap;function $o(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>bg;)i&za&&(a=a.add(c)),c=c.double(),i>>=za;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let p=0;p<a;p++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,p=BigInt(2**s-1),h=2**s,d=BigInt(s);for(let m=0;m<c;m++){let w=m*u,g=Number(a&p);a>>=d,g>u&&(g-=h,a+=za);let y=w,b=w+Math.abs(g)-1,x=m%2!==0,A=g<0;g===0?l=l.add(t(x,i[y])):f=f.add(t(A,i[b]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=Yu.get(s)||1,u=Ga.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Ga.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),Yu.set(s,i),Ga.delete(s)}}}function Fn(r){return Ha(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$a(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),ze=BigInt(1),qo=BigInt(2),Eg=BigInt(8),xg={zip215:!0};function vg(r){let e=Fn(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Wu(r){let e=vg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=qo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((S,v)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(v))}}catch{return{isValid:!1,value:ct}}}),p=e.adjustScalarBytes||(S=>S),h=e.domain||((S,v,T)=>{if(at("phflag",T),v.length||T)throw new Error("Contexts/pre-hash are not supported");return S});function d(S,v){qe("coordinate "+S,v,ct,u)}function m(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=br((S,v)=>{let{ex:T,ey:B,ez:P}=S,O=S.is0();v==null&&(v=O?Eg:t.inv(P));let U=f(T*v),z=f(B*v),H=f(P*v);if(O)return{x:ct,y:ze};if(H!==ze)throw new Error("invZ was invalid");return{x:U,y:z}}),g=br(S=>{let{a:v,d:T}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:B,ey:P,ez:O,et:U}=S,z=f(B*B),H=f(P*P),G=f(O*O),oe=f(G*G),se=f(z*v),$e=f(G*f(se+H)),Ee=f(oe+f(T*f(z*H)));if($e!==Ee)throw new Error("bad point: equation left != right (1)");let me=f(B*P),nt=f(O*U);if(me!==nt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,B,P){this.ex=v,this.ey=T,this.ez=B,this.et=P,d("x",v),d("y",T),d("z",B),d("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:B}=v||{};return d("x",T),d("y",B),new y(T,B,ze,f(T*B))}static normalizeZ(v){let T=t.invertBatch(v.map(B=>B.ez));return v.map((B,P)=>B.toAffine(T[P])).map(y.fromAffine)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){g(this)}equals(v){m(v);let{ex:T,ey:B,ez:P}=this,{ex:O,ey:U,ez:z}=v,H=f(T*z),G=f(O*P),oe=f(B*z),se=f(U*P);return H===G&&oe===se}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:v}=e,{ex:T,ey:B,ez:P}=this,O=f(T*T),U=f(B*B),z=f(qo*f(P*P)),H=f(v*O),G=T+B,oe=f(f(G*G)-O-U),se=H+U,$e=se-z,Ee=H-U,me=f(oe*$e),nt=f(se*Ee),xe=f(oe*Ee),ot=f($e*se);return new y(me,nt,ot,xe)}add(v){m(v);let{a:T,d:B}=e,{ex:P,ey:O,ez:U,et:z}=this,{ex:H,ey:G,ez:oe,et:se}=v;if(T===BigInt(-1)){let tu=f((O-P)*(G+H)),ru=f((O+P)*(G-H)),sa=f(ru-tu);if(sa===ct)return this.double();let nu=f(U*qo*se),ou=f(z*qo*oe),su=ou+nu,iu=ru+tu,au=ou-nu,fp=f(su*sa),hp=f(iu*au),dp=f(su*au),pp=f(sa*iu);return new y(fp,hp,pp,dp)}let $e=f(P*H),Ee=f(O*G),me=f(z*B*se),nt=f(U*oe),xe=f((P+O)*(H+G)-$e-Ee),ot=nt-me,dr=nt+me,Cn=f(Ee-T*$e),Io=f(xe*ot),cp=f(dr*Cn),lp=f(xe*Cn),up=f(ot*dr);return new y(Io,cp,up,lp)}subtract(v){return this.add(v.negate())}wNAF(v){return A.wNAFCached(this,v,y.normalizeZ)}multiply(v){let T=v;qe("scalar",T,ze,n);let{p:B,f:P}=this.wNAF(T);return y.normalizeZ([B,P])[0]}multiplyUnsafe(v){let T=v;return qe("scalar",T,ct,n),T===ct?x:this.equals(x)||T===ze?this:this.equals(b)?this.wNAF(T).p:A.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(v){return w(this,v)}clearCofactor(){let{h:v}=e;return v===ze?this:this.multiplyUnsafe(v)}static fromHex(v,T=!1){let{d:B,a:P}=e,O=t.BYTES;v=le("pointHex",v,O),at("zip215",T);let U=v.slice(),z=v[O-1];U[O-1]=z&-129;let H=Xt(U),G=T?u:t.ORDER;qe("pointHex.y",H,ct,G);let oe=f(H*H),se=f(oe-ze),$e=f(B*oe-P),{isValid:Ee,value:me}=l(se,$e);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let nt=(me&ze)===ze,xe=(z&128)!==0;if(!T&&me===ct&&xe)throw new Error("Point.fromHex: x=0 and x_0=1");return xe!==nt&&(me=f(-me)),y.fromAffine({x:me,y:H})}static fromPrivateKey(v){return I(v).point}toRawBytes(){let{x:v,y:T}=this.toAffine(),B=wr(T,t.BYTES);return B[B.length-1]|=v&ze?128:0,B}toHex(){return Tt(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),y.ZERO=new y(ct,ze,ze,ct);let{BASE:b,ZERO:x}=y,A=$o(y,a*8);function R(S){return X(S,n)}function _(S){return R(Xt(S))}function I(S){let v=a;S=le("private key",S,v);let T=le("hashed private key",s(S),2*v),B=p(T.slice(0,v)),P=T.slice(v,2*v),O=_(B),U=b.multiply(O),z=U.toRawBytes();return{head:B,prefix:P,scalar:O,point:U,pointBytes:z}}function $(S){return I(S).pointBytes}function V(S=new Uint8Array,...v){let T=Ct(...v);return _(s(h(T,le("context",S),!!o)))}function K(S,v,T={}){S=le("message",S),o&&(S=o(S));let{prefix:B,scalar:P,pointBytes:O}=I(v),U=V(T.context,B,S),z=b.multiply(U).toRawBytes(),H=V(T.context,z,O,S),G=R(U+H*P);qe("signature.s",G,ct,n);let oe=Ct(z,wr(G,t.BYTES));return le("result",oe,a*2)}let Q=xg;function D(S,v,T,B=Q){let{context:P,zip215:O}=B,U=t.BYTES;S=le("signature",S,2*U),v=le("message",v),O!==void 0&&at("zip215",O),o&&(v=o(v));let z=Xt(S.slice(U,2*U)),H,G,oe;try{H=y.fromHex(T,O),G=y.fromHex(S.slice(0,U),O),oe=b.multiplyUnsafe(z)}catch{return!1}if(!O&&H.isSmallOrder())return!1;let se=V(P,G.toRawBytes(),H.toRawBytes(),v);return G.add(H.multiplyUnsafe(se)).subtract(oe).clearCofactor().equals(y.ZERO)}return b._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:K,verify:D,ExtendedPoint:y,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,v=y.BASE){return v._setWindowSize(S),v.multiply(BigInt(3)),v}}}}var Ya=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ju=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),px=BigInt(0),_g=BigInt(1),Xu=BigInt(2),mx=BigInt(3),Ag=BigInt(5),Sg=BigInt(8);function Rg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ya,a=r*r%s*r%s,c=te(a,Xu,s)*a%s,u=te(c,_g,s)*r%s,f=te(u,Ag,s)*u%s,l=te(f,e,s)*f%s,p=te(l,t,s)*l%s,h=te(p,n,s)*p%s,d=te(h,o,s)*h%s,m=te(d,o,s)*h%s,w=te(m,e,s)*f%s;return{pow_p_5_8:te(w,Xu,s)*r%s,b2:a}}function Ig(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Tg(r,e){let t=Ya,n=X(e*e*e,t),o=X(n*n*e,t),s=Rg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*ju,t),f=a===r,l=a===X(-r,t),p=a===X(-r*ju,t);return f&&(i=c),(l||p)&&(i=u),qu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Bg=Ho(Ya,void 0,!0),Cg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Bg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Sg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:On,randomBytes:Xr,adjustScalarBytes:Ig,uvRatio:Tg},Jr=Wu(Cg);var en=32,kt=64,zo=32;function Zu(){let r=Jr.utils.randomPrivateKey(),e=Jr.getPublicKey(r);return{privateKey:tf(r,e),publicKey:e}}function Qu(r){if(r.length!==zo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Jr.getPublicKey(e);return{privateKey:tf(e,t),publicKey:t}}function Ju(r,e){let t=r.subarray(0,zo);return Jr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function ef(r,e,t){return Jr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function tf(r,e){let t=new Uint8Array(kt);for(let n=0;n<zo;n++)t[n]=r[n],t[zo+n]=e[n];return t}var Ue={get(r=globalThis){let e=r.crypto;if(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/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Wa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function rf(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ue.get();t*=8;async function c(l,p){let h=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:d};typeof p=="string"&&(p=L(p));let w;if(p.length===0){w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"]);try{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"])}}else{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,w,l);return Re([h,m.iv,new Uint8Array(g)])}async function u(l,p){let h=l.subarray(0,s),d=l.subarray(s,s+n),m=l.subarray(s+n),w={name:e,iv:d};typeof p=="string"&&(p=L(p));let g;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}let y=await a.subtle.decrypt(w,g,m);return new Uint8Array(y)}return{encrypt:c,decrypt:u}}async function tn(r,e){let n=await rf().encrypt(r,e);return Dn.encode(n)}var Lg=Math.pow(2,7),Dg=Math.pow(2,14),Pg=Math.pow(2,21),ja=Math.pow(2,28),Xa=Math.pow(2,35),Za=Math.pow(2,42),Qa=Math.pow(2,49),W=128,Ne=127;function de(r){if(r<Lg)return 1;if(r<Dg)return 2;if(r<Pg)return 3;if(r<ja)return 4;if(r<Xa)return 5;if(r<Za)return 6;if(r<Qa)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ja(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Og(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ec(r,e){let t=r[e],n=0;if(n+=t&Ne,t<W||(t=r[e+1],n+=(t&Ne)<<7,t<W)||(t=r[e+2],n+=(t&Ne)<<14,t<W)||(t=r[e+3],n+=(t&Ne)<<21,t<W)||(t=r[e+4],n+=(t&Ne)*ja,t<W)||(t=r[e+5],n+=(t&Ne)*Xa,t<W)||(t=r[e+6],n+=(t&Ne)*Za,t<W)||(t=r[e+7],n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Ug(r,e){let t=r.get(e),n=0;if(n+=t&Ne,t<W||(t=r.get(e+1),n+=(t&Ne)<<7,t<W)||(t=r.get(e+2),n+=(t&Ne)<<14,t<W)||(t=r.get(e+3),n+=(t&Ne)<<21,t<W)||(t=r.get(e+4),n+=(t&Ne)*ja,t<W)||(t=r.get(e+5),n+=(t&Ne)*Xa,t<W)||(t=r.get(e+6),n+=(t&Ne)*Za,t<W)||(t=r.get(e+7),n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Le(r,e,t=0){return e==null&&(e=ke(de(r))),e instanceof Uint8Array?Ja(r,e,t):Og(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?ec(r,e):Ug(r,e)}var tc=new Float32Array([-0]),Qt=new Uint8Array(tc.buffer);function nf(r,e,t){tc[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function of(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],tc[0]}var rc=new Float64Array([-0]),De=new Uint8Array(rc.buffer);function sf(r,e,t){rc[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function af(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],rc[0]}var Mg=BigInt(Number.MAX_SAFE_INTEGER),Fg=BigInt(Number.MIN_SAFE_INTEGER),We=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return vr;if(e<Mg&&e>Fg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>cf&&(o=0n,++n>cf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):vr}},vr=new We(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var cf=4294967296n;function lf(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function uf(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function nc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Go(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var oc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;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,ut(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ut(this,4);return Go(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return Go(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=of(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=af(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return uf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ut(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new We(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ut(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ut(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ut(this,8);let e=Go(this.buf,this.pos+=4),t=Go(this.buf,this.pos+=4);return new We(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ec(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function sc(r){return new oc(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=sc(r);return e.decode(n,void 0,t)}function ic(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ke(i);o+i>e&&(n=ke(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var _r=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ac(){}var lc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Vg=ic();function Kg(r){return globalThis.Buffer!=null?ke(r):Vg(r)}var Kn=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(ac,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _r(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Yo,10,We.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=We.fromBigInt(e);return this._push(Yo,t.length(),t)}uint64Number(e){return this._push(Ja,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=We.fromBigInt(e).zzEncode();return this._push(Yo,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(Yo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(cc,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(nf,4,e)}double(e){return this._push(sf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(cc,1,0):this.uint32(t)._push($g,t,e)}string(e){let t=lf(e);return t!==0?this.uint32(t)._push(nc,t,e):this._push(cc,1,0)}fork(){return this.states=new lc(this),this.head=this.tail=new _r(ac,0,0),this.len=0,this}reset(){return this.states!=null?(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 _r(ac,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Kg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function cc(r,e,t){e[t]=r&255}function Hg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var uc=class extends _r{next;constructor(e,t){super(Hg,e,t),this.next=void 0}};function Yo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Vn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function $g(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Kn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qg,e,r),this},Kn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zg,e,r),this});function qg(r,e,t){e.set(r,t)}function zg(r,e,t){r.length<40?nc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function fc(){return new Kn}function Fe(r,e){let t=fc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(rn||(rn={}));function Wo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function hc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Wo("enum",rn.VARINT,t,n)}function Ve(r,e){return Wo("message",rn.LENGTH_DELIMITED,r,e)}var re;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(re||(re={}));var dc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(dc||(dc={}));(function(r){r.codec=()=>hc(dc)})(re||(re={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(yt||(yt={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(wt||(wt={}));var Hn=class{_key;constructor(e){this._key=nn(e,en)}verify(e,t){return ef(this._key,t,e)}marshal(){return this._key}get bytes(){return yt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},Ar=class{_key;_publicKey;constructor(e,t){this._key=nn(e,kt),this._publicKey=nn(t,en)}sign(e){return Ju(this._key,e)}get public(){return new Hn(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Rt.digest(this.public.bytes);return ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Gg(r){if(r.length>kt){r=nn(r,kt+en);let n=r.subarray(0,kt),o=r.subarray(kt,r.length);return new Ar(n,o)}r=nn(r,kt);let e=r.subarray(0,kt),t=r.subarray(en);return new Ar(e,t)}function Yg(r){return r=nn(r,en),new Hn(r)}async function Wg(){let{privateKey:r,publicKey:e}=Zu();return new Ar(r,e)}async function hf(r){let{privateKey:e,publicKey:t}=Qu(r);return new Ar(e,t)}function nn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function F(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ac={};ve(Ac,{MAX_RSA_KEY_SIZE:()=>eo,RsaPrivateKey:()=>ln,RsaPublicKey:()=>Jn,fromJwk:()=>x0,generateKeyPair:()=>v0,unmarshalRsaPrivateKey:()=>vc,unmarshalRsaPublicKey:()=>E0});function et(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Xr(r)}var rr={};ve(rr,{exportToPem:()=>m0,importFromPem:()=>g0,jwkToPkcs1:()=>f0,jwkToPkix:()=>d0,pkcs1ToJwk:()=>u0,pkixToJwk:()=>h0});var Xo=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Po(e);let n=Gt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Gr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},$n=(r,e,t)=>new Xo(r,e).update(t).digest();$n.create=(r,e)=>new Xo(r,e);function jg(r,e,t,n){Po(r);let o=Pu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(zr(s),zr(i),zr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gt(e),u=Gt(t),f=new Uint8Array(i),l=$n.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Xg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function mc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=jg(r,e,t,n),f,l=new Uint8Array(4),p=jr(l),h=new Uint8Array(c.outputLen);for(let d=1,m=0;m<s;d++,m+=c.outputLen){let w=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),w.set(h.subarray(0,w.length)),await Lu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<w.length;g++)w[g]^=h[g]})}return Xg(c,u,a,f,h)}var q=pr(df());function Sr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Jt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Jo(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function yc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Sr(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Sr(s,8)-n}function pf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Jt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function mf(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Ge(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var _1=Math.log(2);function es(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function wc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ot(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var zn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return wc(this.items)}},qn=[new Uint8Array([1])],gf="0123456789";var an="",ht=new ArrayBuffer(0),bc=new Uint8Array(0),Gn="EndOfContent",wf="OCTET STRING",bf="BIT STRING";function Ut(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):bc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ht)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=an,warnings:n=[],valueBeforeDecode:o=bc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Lt.NAME="baseBlock";var Pe=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pe.NAME="valueBlock";var ts=class extends Ut(Lt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):bc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ht}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Jt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let p=0;p<c;p++)l[p]=u[p];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Sr(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ts.NAME="identificationBlock";var rs=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Sr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Jt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ht;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};rs.NAME="lengthBlock";var C={},Ie=class extends Lt{constructor({name:e=an,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ts(o),this.lenBlock=new rs(o),this.valueBlock=s?new s(o):new Pe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new zn;t||Ef(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ht:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return mf(t,n)}};Ie.NAME="BaseBlock";function Ef(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Ef(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Ie{constructor({value:e=an,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ns.NAME="BaseStringBlock";var os=class extends Ut(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};os.NAME="PrimitiveValueBlock";var xf,ss=class extends Ie{constructor(e={}){super(e,os),this.idBlock.isConstructed=!1}};xf=ss;C.Primitive=xf;ss.NAME="PRIMITIVE";function s0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ms(r,e=0,t=r.length){let n=e,o=new Ie({},Pe),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ie;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=s0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function cn(r){if(!r.byteLength){let e=new Ie({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ms(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function i0(r,e){return r?1:e}var bt=class extends Pe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;i0(this.isIndefiniteForm,n)>0;){let i=Ms(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Gn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ht:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};bt.NAME="ConstructedValueBlock";var vf,er=class extends Ie{constructor(e={}){super(e,bt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
2
+ "use strict";var Libp2P=(()=>{var wp=Object.create;var ko=Object.defineProperty;var bp=Object.getOwnPropertyDescriptor;var Ep=Object.getOwnPropertyNames;var xp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty;var At=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},fu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ep(e))!vp.call(r,o)&&o!==t&&ko(r,o,{get:()=>e[o],enumerable:!(n=bp(e,o))||n.enumerable});return r};var gr=(r,e,t)=>(t=r!=null?wp(xp(r)):{},fu(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r)),_p=r=>fu(ko({},"__esModule",{value:!0}),r);var mf=At(cn=>{"use strict";var Jg="[object ArrayBuffer]",Lt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Jg}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},bc="string",e0=/^[0-9a-f]+$/i,t0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,r0=/^[a-zA-Z0-9-_]+$/,Jo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Lt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},nt=class{static toString(e,t=!1){let n=Lt.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},es=class r{static isHex(e){return typeof e===bc&&e0.test(e)}static isBase64(e){return typeof e===bc&&t0.test(e)}static isBase64Url(e){return typeof e===bc&&r0.test(e)}static ToString(e,t="utf8"){let n=Lt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return nt.toString(n,!0);case"utf16":case"utf16be":return nt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return nt.fromString(e,!0);case"utf16":case"utf16be":return nt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Lt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Jo.fromString(e);case"utf16":case"utf16be":return nt.fromString(e);case"utf16le":case"usc2":return nt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Jo.toString(e);case"utf16":case"utf16be":return nt.toString(e);case"utf16le":case"usc2":return nt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Lt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Lt.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return nt.toString(e,t)}static FromUtf16String(e,t=!1){return nt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};es.DEFAULT_UTF8_ENCODING="utf8";function n0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function o0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function s0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}cn.BufferSourceConverter=Lt;cn.Convert=es;cn.assign=n0;cn.combine=o0;cn.isEqual=s0});var Bh=At((uo,Gs)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,E=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,E),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,E),y^=b}return y^=h.length,y=i(y),y>>>0},t.x86.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,E=p,A=0,R=0,v=0,I=0,N=597399067,ee=2869860233,H=951274213,K=2716044179,O=0;O<g;O=O+16)A=h[O]|h[O+1]<<8|h[O+2]<<16|h[O+3]<<24,R=h[O+4]|h[O+5]<<8|h[O+6]<<16|h[O+7]<<24,v=h[O+8]|h[O+9]<<8|h[O+10]<<16|h[O+11]<<24,I=h[O+12]|h[O+13]<<8|h[O+14]<<16|h[O+15]<<24,A=o(A,N),A=s(A,15),A=o(A,ee),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,R=o(R,ee),R=s(R,16),R=o(R,H),b^=R,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,H),v=s(v,17),v=o(v,K),w^=v,w=s(w,15),w+=E,w=o(w,5)+2530024501,I=o(I,K),I=s(I,18),I=o(I,N),E^=I,E=s(E,13),E+=y,E=o(E,5)+850148119;switch(A=0,R=0,v=0,I=0,m){case 15:I^=h[O+14]<<16;case 14:I^=h[O+13]<<8;case 13:I^=h[O+12],I=o(I,K),I=s(I,18),I=o(I,N),E^=I;case 12:v^=h[O+11]<<24;case 11:v^=h[O+10]<<16;case 10:v^=h[O+9]<<8;case 9:v^=h[O+8],v=o(v,H),v=s(v,17),v=o(v,K),w^=v;case 8:R^=h[O+7]<<24;case 7:R^=h[O+6]<<16;case 6:R^=h[O+5]<<8;case 5:R^=h[O+4],R=o(R,ee),R=s(R,16),R=o(R,H),b^=R;case 4:A^=h[O+3]<<24;case 3:A^=h[O+2]<<16;case 2:A^=h[O+1]<<8;case 1:A^=h[O],A=o(A,N),A=s(A,15),A=o(A,ee),y^=A}return y^=h.length,b^=h.length,w^=h.length,E^=h.length,y+=b,y+=w,y+=E,b+=y,w+=y,E+=y,y=i(y),b=i(b),w=i(w),E=i(E),y+=b,y+=w,y+=E,b+=y,w+=y,E+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],E=[0,0],A=[2277735313,289559509],R=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],E=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,R),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),E=c(E,R),E=u(E,33),E=c(E,A),b=l(b,E),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],E=[0,0],m){case 15:E=l(E,f([0,h[v+14]],48));case 14:E=l(E,f([0,h[v+13]],40));case 13:E=l(E,f([0,h[v+12]],32));case 12:E=l(E,f([0,h[v+11]],24));case 11:E=l(E,f([0,h[v+10]],16));case 10:E=l(E,f([0,h[v+9]],8));case 9:E=l(E,[0,h[v+8]]),E=c(E,R),E=u(E,33),E=c(E,A),b=l(b,E);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,R),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof uo<"u"?(typeof Gs<"u"&&Gs.exports&&(uo=Gs.exports=t),uo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(uo)});var kh=At((t_,Ch)=>{Ch.exports=Bh()});var td=At((k2,ol)=>{"use strict";var Cy=Object.prototype.hasOwnProperty,qe="~";function yo(){}Object.create&&(yo.prototype=Object.create(null),new yo().__proto__||(qe=!1));function ky(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ed(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new ky(t,n||r,o),i=qe?qe+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Js(r,e){--r._eventsCount===0?r._events=new yo:delete r._events[e]}function Ue(){this._events=new yo,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Cy.call(t,n)&&e.push(qe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.prototype.listeners=function(e){var t=qe?qe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ue.prototype.listenerCount=function(e){var t=qe?qe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=qe?qe+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;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,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Ue.prototype.on=function(e,t,n){return ed(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return ed(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=qe?qe+e:e;if(!this._events[s])return this;if(!t)return Js(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Js(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Js(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Js(this,t)):(this._events=new yo,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=qe;Ue.EventEmitter=Ue;typeof ol<"u"&&(ol.exports=Ue)});var gd=At((XS,md)=>{"use strict";function pd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function jy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return pd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),pd(new o,t)}}md.exports=jy});var vd=At(xo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}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")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);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):(i(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 f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),xo.ip2long=i,xo.long2ip=a,xo.Netmask=r}).call(xo)});var Pd=At((oI,Dd)=>{Dd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Vd=At((vI,Fd)=>{"use strict";Fd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Gd=At((qd,zd)=>{"use strict";var Ei=Vd(),{hasOwnProperty:Hd}=Object.prototype,{propertyIsEnumerable:vw}=Object,In=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),_w=qd,Kd={concatArrays:!1,ignoreUndefined:!1},xi=r=>{let e=[];for(let t in r)Hd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)vw.call(r,n)&&e.push(n)}return e};function Tn(r){return Array.isArray(r)?Aw(r):Ei(r)?Sw(r):r}function Aw(r){let e=r.slice(0,0);return xi(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}function Sw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return xi(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}var $d=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?In(r,o,Dl(r[o],e[o],n)):In(r,o,Tn(e[o])))}),r),Rw=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Hd.call(s,a)&&(i.push(String(a)),s===r?In(n,o++,s[a]):In(n,o++,Tn(s[a])));n=$d(n,s,xi(s).filter(a=>!i.includes(a)),t)}),n};function Dl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Rw(r,e,t):!Ei(e)||!Ei(r)?Tn(e):$d(r,e,xi(e),t)}zd.exports=function(...r){let e=Dl(Tn(Kd),this!==_w&&this||{},Kd),t={_:{}};for(let n of r)if(n!==void 0){if(!Ei(n))throw new TypeError("`"+n+"` is not an Option Object");t=Dl(t,{_:n},e)}return t._}});var ob={};ve(ob,{createLibp2p:()=>nb});var hu=Symbol.for("@libp2p/connection");var ca=Symbol.for("@libp2p/content-routing");var la=Symbol.for("@libp2p/peer-discovery");var No=Symbol.for("@libp2p/peer-id");function Lo(r){return r!=null&&!!r[No]}var ua=Symbol.for("@libp2p/peer-routing");var du="keep-alive";var hb=Symbol.for("@libp2p/transport");var zt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(zt||(zt={}));var Gt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},x=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},Do=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var Po="ERR_TIMEOUT";var ie=(r,...e)=>{try{[...e]}catch{}};var St=class extends EventTarget{#e=new Map;constructor(){super(),ie(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new fa(e,t))}},fa=globalThis.CustomEvent;function pu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Pn=Symbol.for("@libp2p/service-capabilities"),ha=Symbol.for("@libp2p/service-dependencies");var yc={};ve(yc,{Ed25519PrivateKey:()=>Tr,Ed25519PublicKey:()=>Gn,generateKeyPair:()=>Xg,generateKeyPairFromSeed:()=>pf,unmarshalEd25519PrivateKey:()=>jg,unmarshalEd25519PublicKey:()=>Wg});var ya={};ve(ya,{base58btc:()=>ae,base58flickr:()=>Bp});var Hb=new Uint8Array(0);function mu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Rt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function gu(r){return new TextEncoder().encode(r)}function yu(r){return new TextDecoder().decode(r)}function Ap(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(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,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,E=new Uint8Array(w);y!==b;){for(var A=p[y],R=0,v=w-1;(A!==0||R<g)&&v!==-1;v--,R++)A+=256*E[v]>>>0,E[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=R,y++}for(var I=w-g;I!==w&&E[I]===0;)I++;for(var N=c.repeat(m);I<w;++I)N+=r.charAt(E[I]);return N}function d(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 g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var E=t[p.charCodeAt(m)];if(E===255)return;for(var A=0,R=b-1;(E!==0||A<y)&&R!==-1;R--,A++)E+=a*w[R]>>>0,w[R]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var I=new Uint8Array(g+(b-v)),N=g;v!==b;)I[N++]=w[v++];return I}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Sp=Ap,Rp=Sp,bu=Rp;var da=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Eu(this,e)}},ma=class{decoders;constructor(e){this.decoders=e}or(e){return Eu(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Eu(r,e){return new ma({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ga=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new da(e,t,n),this.decoder=new pa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function qr({name:r,prefix:e,encode:t,decode:n}){return new ga(r,e,t,n)}function Yt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=bu(t,r);return qr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function Ip(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Tp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return qr({prefix:e,name:r,encode(o){return Tp(o,n,t)},decode(o){return Ip(o,n,t,r)}})}var ae=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bp=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ba={};ve(ba,{identity:()=>It});var Cp=_u,xu=128,kp=127,Np=~kp,Lp=Math.pow(2,31);function _u(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Lp;)e[t++]=r&255|xu,r/=128;for(;r&Np;)e[t++]=r&255|xu,r>>>=7;return e[t]=r|0,_u.bytes=t-n+1,e}var Dp=wa,Pp=128,vu=127;function wa(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wa.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&vu)<<o:(i&vu)*Math.pow(2,o),o+=7}while(i>=Pp);return wa.bytes=s-n,t}var Op=Math.pow(2,7),Up=Math.pow(2,14),Mp=Math.pow(2,21),Fp=Math.pow(2,28),Vp=Math.pow(2,35),Kp=Math.pow(2,42),Hp=Math.pow(2,49),$p=Math.pow(2,56),qp=Math.pow(2,63),zp=function(r){return r<Op?1:r<Up?2:r<Mp?3:r<Fp?4:r<Vp?5:r<Kp?6:r<Hp?7:r<$p?8:r<qp?9:10},Gp={encode:Cp,decode:Dp,encodingLength:zp},Yp=Gp,On=Yp;function Un(r,e=0){return[On.decode(r,e),On.decode.bytes]}function zr(r,e,t=0){return On.encode(r,e,t),e}function Gr(r){return On.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=Gr(r),o=n+Gr(t),s=new Uint8Array(o+t);return zr(r,s,0),zr(t,s,n),s.set(e,o),new Yr(r,t,e,s)}function yr(r){let e=Rt(r),[t,n]=Un(e),[o,s]=Un(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yr(t,o,i,e)}function Au(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&mu(r.bytes,t.bytes)}}var Yr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Su=0,jp="identity",Ru=Rt;function Wp(r){return mt(Su,Ru(r))}var It={code:Su,name:jp,encode:Ru,digest:Wp};var va={};ve(va,{sha256:()=>Re,sha512:()=>Xp});function xa({name:r,code:e,encode:t}){return new Ea(r,e,t)}var Ea=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?mt(this.code,t):t.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Tu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=xa({name:"sha2-256",code:18,encode:Tu("SHA-256")}),Xp=xa({name:"sha2-512",code:19,encode:Tu("SHA-512")});function te(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function st(r=0){return new Uint8Array(r)}function Ne(r=0){return new Uint8Array(r)}function Ie(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ne(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var _a={};ve(_a,{base10:()=>Zp});var Zp=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var Aa={};ve(Aa,{base16:()=>Qp,base16upper:()=>Jp});var Qp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Sa={};ve(Sa,{base2:()=>em});var em=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ra={};ve(Ra,{base256emoji:()=>sm});var Bu=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}"),tm=Bu.reduce((r,e,t)=>(r[t]=e,r),[]),rm=Bu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function nm(r){return r.reduce((e,t)=>(e+=tm[t],e),"")}function om(r){let e=[];for(let t of r){let n=rm[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var sm=qr({prefix:"\u{1F680}",name:"base256emoji",encode:nm,decode:om});var Ia={};ve(Ia,{base32:()=>We,base32hex:()=>lm,base32hexpad:()=>fm,base32hexpadupper:()=>hm,base32hexupper:()=>um,base32pad:()=>am,base32padupper:()=>cm,base32upper:()=>im,base32z:()=>dm});var We=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),im=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),am=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lm=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),um=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),dm=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ta={};ve(Ta,{base36:()=>pm,base36upper:()=>mm});var pm=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mm=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ca={};ve(Ca,{base64:()=>Mn,base64pad:()=>gm,base64url:()=>Ba,base64urlpad:()=>ym});var Mn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ba=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ym=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ka={};ve(ka,{base8:()=>wm});var wm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Na={};ve(Na,{identity:()=>bm});var bm=qr({prefix:"\0",name:"identity",encode:r=>yu(r),decode:r=>gu(r)});var gE=new TextEncoder,yE=new TextDecoder;function Cu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _m(t,La(r),e??ae.encoder);default:return Am(t,La(r),e??We.encoder)}}var ku=new WeakMap;function La(r){let e=ku.get(r);if(e==null){let t=new Map;return ku.set(r,t),t}return e}var et=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Sm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=mt(e,t);return r.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 r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Au(e.multihash,n.multihash)}toString(e){return Cu(this,e)}toJSON(){return{"/":Cu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Nu(n,o,s.bytes))}else if(t[Rm]===!0){let{version:n,multihash:o,code:s}=t,i=yr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Nu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Rt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Yr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=Un(e.subarray(t));return t+=d,l},o=n(),s=Fn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=vm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return La(s).set(n,e),s}};function vm(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function _m(r,e,t){let{prefix:n}=t;if(n!==ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Am(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Fn=112,Sm=18;function Nu(r,e,t){let n=Gr(r),o=n+Gr(e),s=new Uint8Array(o+t.byteLength);return zr(r,s,0),zr(e,s,n),s.set(t,o),s}var Rm=Symbol.for("@ipld/js-cid/CID");var jt={...Na,...Sa,...ka,..._a,...Aa,...Ia,...Ta,...ya,...Ca,...Ra},LE={...va,...ba};function Du(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lu=Du("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Da=Du("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ne(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Im={utf8:Lu,"utf-8":Lu,hex:jt.base16,latin1:Da,ascii:Da,binary:Da,...jt},Uo=Im;function L(r,e="utf8"){let t=Uo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function tt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function jr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Tm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wr(r,...e){if(!Tm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Mo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");jr(r.outputLen),jr(r.blockLen)}function Xr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Pu(r,e){Wr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var br=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Qr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var YE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Bm=async()=>{};async function Ou(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Bm(),n+=s)}}function Uu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Wt(r){return typeof r=="string"&&(r=Uu(r)),Wr(r),r}function Pa(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Wr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Zr=class{clone(){return this._cloneInto()}},Cm={}.toString;function Mu(r,e){if(e!==void 0&&Cm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Fo(r){let e=n=>r().update(Wt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Jr(r=32){if(br&&typeof br.getRandomValues=="function")return br.getRandomValues(new Uint8Array(r));if(br&&typeof br.randomBytes=="function")return br.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function km(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Fu=(r,e,t)=>r&e^~r&t,Vu=(r,e,t)=>r&e^r&t^e&t,en=class extends Zr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Qr(this.buffer)}update(e){Xr(this);let{view:t,buffer:n,blockLen:o}=this;e=Wt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Qr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xr(this),Pu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;km(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Qr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Vo=BigInt(4294967295),Oa=BigInt(32);function Ku(r,e=!1){return e?{h:Number(r&Vo),l:Number(r>>Oa&Vo)}:{h:Number(r>>Oa&Vo)|0,l:Number(r&Vo)|0}}function Nm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Ku(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Lm=(r,e)=>BigInt(r>>>0)<<Oa|BigInt(e>>>0),Dm=(r,e,t)=>r>>>t,Pm=(r,e,t)=>r<<32-t|e>>>t,Om=(r,e,t)=>r>>>t|e<<32-t,Um=(r,e,t)=>r<<32-t|e>>>t,Mm=(r,e,t)=>r<<64-t|e>>>t-32,Fm=(r,e,t)=>r>>>t-32|e<<64-t,Vm=(r,e)=>e,Km=(r,e)=>r,Hm=(r,e,t)=>r<<t|e>>>32-t,$m=(r,e,t)=>e<<t|r>>>32-t,qm=(r,e,t)=>e<<t-32|r>>>64-t,zm=(r,e,t)=>r<<t-32|e>>>64-t;function Gm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ym=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Wm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Xm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Zm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Qm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Jm={fromBig:Ku,split:Nm,toBig:Lm,shrSH:Dm,shrSL:Pm,rotrSH:Om,rotrSL:Um,rotrBH:Mm,rotrBL:Fm,rotr32H:Vm,rotr32L:Km,rotlSH:Hm,rotlSL:$m,rotlBH:qm,rotlBL:zm,add:Gm,add3L:Ym,add3H:jm,add4L:Wm,add4H:Xm,add5H:Qm,add5L:Zm},F=Jm;var[eg,tg]=F.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Xt=new Uint32Array(80),Zt=new Uint32Array(80),Ua=class extends en{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)Xt[w]=e.getUint32(t),Zt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let E=Xt[w-15]|0,A=Zt[w-15]|0,R=F.rotrSH(E,A,1)^F.rotrSH(E,A,8)^F.shrSH(E,A,7),v=F.rotrSL(E,A,1)^F.rotrSL(E,A,8)^F.shrSL(E,A,7),I=Xt[w-2]|0,N=Zt[w-2]|0,ee=F.rotrSH(I,N,19)^F.rotrBH(I,N,61)^F.shrSH(I,N,6),H=F.rotrSL(I,N,19)^F.rotrBL(I,N,61)^F.shrSL(I,N,6),K=F.add4L(v,H,Zt[w-7],Zt[w-16]),O=F.add4H(K,R,ee,Xt[w-7],Xt[w-16]);Xt[w]=O|0,Zt[w]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let E=F.rotrSH(l,d,14)^F.rotrSH(l,d,18)^F.rotrBH(l,d,41),A=F.rotrSL(l,d,14)^F.rotrSL(l,d,18)^F.rotrBL(l,d,41),R=l&h^~l&m,v=d&p^~d&g,I=F.add5L(b,A,v,tg[w],Zt[w]),N=F.add5H(I,y,E,R,eg[w],Xt[w]),ee=I|0,H=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),K=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),O=n&s^n&a^s&a,B=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=F.add(u|0,f|0,N|0,ee|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=F.add3L(ee,K,B);n=F.add3H(D,N,H,O),o=D|0}({h:n,l:o}=F.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=F.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=F.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=F.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=F.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=F.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=F.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){Xt.fill(0),Zt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Vn=Fo(()=>new Ua);var Ho={};ve(Ho,{aInRange:()=>Ge,abool:()=>at,abytes:()=>tn,bitGet:()=>ag,bitLen:()=>Ha,bitMask:()=>Hn,bitSet:()=>cg,bytesToHex:()=>Bt,bytesToNumberBE:()=>Ct,bytesToNumberLE:()=>Jt,concatBytes:()=>kt,createHmacDrbg:()=>$a,ensureBytes:()=>le,equalBytes:()=>sg,hexToBytes:()=>xr,hexToNumber:()=>Ka,inRange:()=>Kn,isBytes:()=>Qt,memoized:()=>_r,notImplemented:()=>ug,numberToBytesBE:()=>er,numberToBytesLE:()=>vr,numberToHexUnpadded:()=>Er,numberToVarBytesBE:()=>og,utf8ToBytes:()=>ig,validateObject:()=>gt});var Va=BigInt(0),Ko=BigInt(1),rg=BigInt(2);function Qt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function tn(r){if(!Qt(r))throw new Error("Uint8Array expected")}function at(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var ng=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){tn(r);let e="";for(let t=0;t<r.length;t++)e+=ng[r[t]];return e}function Er(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ka(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var Tt={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Hu(r){if(r>=Tt._0&&r<=Tt._9)return r-Tt._0;if(r>=Tt._A&&r<=Tt._F)return r-(Tt._A-10);if(r>=Tt._a&&r<=Tt._f)return r-(Tt._a-10)}function xr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Hu(r.charCodeAt(s)),a=Hu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ct(r){return Ka(Bt(r))}function Jt(r){return tn(r),Ka(Bt(Uint8Array.from(r).reverse()))}function er(r,e){return xr(r.toString(16).padStart(e*2,"0"))}function vr(r,e){return er(r,e).reverse()}function og(r){return xr(Er(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=xr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Qt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function kt(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];tn(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function sg(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ig(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Ma=r=>typeof r=="bigint"&&Va<=r;function Kn(r,e,t){return Ma(r)&&Ma(e)&&Ma(t)&&e<=r&&r<t}function Ge(r,e,t,n){if(!Kn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function Ha(r){let e;for(e=0;r>Va;r>>=Ko,e+=1);return e}function ag(r,e){return r>>BigInt(e)&Ko}function cg(r,e,t){return r|(t?Ko:Va)<<BigInt(e)}var Hn=r=>(rg<<BigInt(r-1))-Ko,Fa=r=>new Uint8Array(r),$u=r=>Uint8Array.from(r);function $a(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Fa(r),o=Fa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Fa())=>{o=a($u([0]),l),n=a(),l.length!==0&&(o=a($u([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<e;){n=a();let h=n.slice();d.push(h),l+=n.length}return kt(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var lg={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Qt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function gt(r,e,t={}){let n=(o,s,i)=>{let a=lg[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ug=()=>{throw new Error("not implemented")};function _r(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),re=BigInt(1),Ar=BigInt(2),fg=BigInt(3),qa=BigInt(4),qu=BigInt(5),zu=BigInt(8),hg=BigInt(9),dg=BigInt(16);function Z(r,e){let t=r%e;return t>=ge?t:e+t}function pg(r,e,t){if(t<=ge||e<ge)throw new Error("Expected power/modulo > 0");if(t===re)return ge;let n=re;for(;e>ge;)e&re&&(n=n*r%t),r=r*r%t,e>>=re;return n}function ne(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function $o(r,e){if(r===ge||e<=ge)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Z(r,e),n=e,o=ge,s=re,i=re,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==re)throw new Error("invert: does not exist");return Z(o,e)}function mg(r){let e=(r-re)/Ar,t,n,o;for(t=r-re,n=0;t%Ar===ge;t/=Ar,n++);for(o=Ar;o<r&&pg(o,e,r)!==r-re;o++);if(n===1){let i=(r+re)/qa;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+re)/Ar;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,re<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function gg(r){if(r%qa===fg){let e=(r+re)/qa;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%zu===qu){let e=(r-qu)/zu;return function(n,o){let s=n.mul(o,Ar),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Ar),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%dg,mg(r)}var Gu=(r,e)=>(Z(r,e)&re)===re,yg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function za(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=yg.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function wg(r,e,t){if(t<ge)throw new Error("Expected power > 0");if(t===ge)return r.ONE;if(t===re)return e;let n=r.ONE,o=e;for(;t>ge;)t&re&&(n=r.mul(n,o)),o=r.sqr(o),t>>=re;return n}function bg(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Ga(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function tr(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ga(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=gg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Hn(o),ZERO:ge,ONE:re,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&re)===re,neg:c=>Z(-c,r),eql:(c,u)=>c===u,sqr:c=>Z(c*c,r),add:(c,u)=>Z(c+u,r),sub:(c,u)=>Z(c-u,r),mul:(c,u)=>Z(c*u,r),pow:(c,u)=>wg(a,c,u),div:(c,u)=>Z(c*$o(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>$o(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>bg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?vr(c,s):er(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Jt(c):Ct(c)}});return Object.freeze(a)}function Yu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Ya(r){let e=Yu(r);return e+Math.ceil(e/2)}function ju(r,e,t=!1){let n=r.length,o=Yu(e),s=Ya(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Ct(r):Jt(r),a=Z(i,e-re)+re;return t?vr(a,o):er(a,o)}var xg=BigInt(0),ja=BigInt(1),Wa=new WeakMap,Wu=new WeakMap;function qo(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>xg;)i&ja&&(a=a.add(c)),c=c.double(),i>>=ja;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=ja);let b=g,w=g+Math.abs(y)-1,E=m%2!==0,A=y<0;y===0?l=l.add(t(E,i[b])):f=f.add(t(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=Wu.get(s)||1,u=Wa.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Wa.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),Wu.set(s,i),Wa.delete(s)}}}function zo(r,e,t,n){if(!Array.isArray(t)||!Array.isArray(n)||n.length!==t.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!e.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),t.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Ha(BigInt(t.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((e.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(t[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function $n(r){return za(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ga(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),Ye=BigInt(1),Go=BigInt(2),vg=BigInt(8),_g={zip215:!0};function Ag(r){let e=$n(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Xu(r){let e=Ag(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Go<<BigInt(a*8)-Ye,f=t.create,l=tr(e.n,e.nBitLength),d=e.uvRatio||((S,_)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(_))}}catch{return{isValid:!1,value:ct}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,_,T)=>{if(at("phflag",T),_.length||T)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,_){Ge("coordinate "+S,_,ct,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=_r((S,_)=>{let{ex:T,ey:P,ez:U}=S,M=S.is0();_==null&&(_=M?vg:t.inv(U));let $=f(T*_),G=f(P*_),q=f(U*_);if(M)return{x:ct,y:Ye};if(q!==Ye)throw new Error("invZ was invalid");return{x:$,y:G}}),b=_r(S=>{let{a:_,d:T}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:P,ey:U,ez:M,et:$}=S,G=f(P*P),q=f(U*U),X=f(M*M),J=f(X*X),Ee=f(G*_),xe=f(X*f(Ee+q)),Se=f(J+f(T*f(G*q)));if(xe!==Se)throw new Error("bad point: equation left != right (1)");let Me=f(P*U),me=f(M*$);if(Me!==me)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(_,T,P,U){this.ex=_,this.ey=T,this.ez=P,this.et=U,m("x",_),m("y",T),m("z",P),m("t",U),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof w)throw new Error("extended point not allowed");let{x:T,y:P}=_||{};return m("x",T),m("y",P),new w(T,P,Ye,f(T*P))}static normalizeZ(_){let T=t.invertBatch(_.map(P=>P.ez));return _.map((P,U)=>P.toAffine(T[U])).map(w.fromAffine)}static msm(_,T){return zo(w,l,_,T)}_setWindowSize(_){R.setWindowSize(this,_)}assertValidity(){b(this)}equals(_){g(_);let{ex:T,ey:P,ez:U}=this,{ex:M,ey:$,ez:G}=_,q=f(T*G),X=f(M*U),J=f(P*G),Ee=f($*U);return q===X&&J===Ee}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:_}=e,{ex:T,ey:P,ez:U}=this,M=f(T*T),$=f(P*P),G=f(Go*f(U*U)),q=f(_*M),X=T+P,J=f(f(X*X)-M-$),Ee=q+$,xe=Ee-G,Se=q-$,Me=f(J*xe),me=f(Ee*Se),ze=f(J*Se),_t=f(xe*Ee);return new w(Me,me,_t,ze)}add(_){g(_);let{a:T,d:P}=e,{ex:U,ey:M,ez:$,et:G}=this,{ex:q,ey:X,ez:J,et:Ee}=_;if(T===BigInt(-1)){let ou=f((M-U)*(X+q)),su=f((M+U)*(X-q)),aa=f(su-ou);if(aa===ct)return this.double();let iu=f($*Go*Ee),au=f(G*Go*J),cu=au+iu,lu=su+ou,uu=au-iu,pp=f(cu*aa),mp=f(lu*uu),gp=f(cu*uu),yp=f(aa*lu);return new w(pp,mp,yp,gp)}let xe=f(U*q),Se=f(M*X),Me=f(G*P*Ee),me=f($*J),ze=f((U+M)*(q+X)-xe-Se),_t=me-Me,Ln=me+Me,Dn=f(Se-T*xe),up=f(ze*_t),fp=f(Ln*Dn),hp=f(ze*Dn),dp=f(_t*Ln);return new w(up,fp,dp,hp)}subtract(_){return this.add(_.negate())}wNAF(_){return R.wNAFCached(this,_,w.normalizeZ)}multiply(_){let T=_;Ge("scalar",T,Ye,n);let{p:P,f:U}=this.wNAF(T);return w.normalizeZ([P,U])[0]}multiplyUnsafe(_){let T=_;return Ge("scalar",T,ct,n),T===ct?A:this.equals(A)||T===Ye?this:this.equals(E)?this.wNAF(T).p:R.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(_){return y(this,_)}clearCofactor(){let{h:_}=e;return _===Ye?this:this.multiplyUnsafe(_)}static fromHex(_,T=!1){let{d:P,a:U}=e,M=t.BYTES;_=le("pointHex",_,M),at("zip215",T);let $=_.slice(),G=_[M-1];$[M-1]=G&-129;let q=Jt($),X=T?u:t.ORDER;Ge("pointHex.y",q,ct,X);let J=f(q*q),Ee=f(J-Ye),xe=f(P*J-U),{isValid:Se,value:Me}=d(Ee,xe);if(!Se)throw new Error("Point.fromHex: invalid y coordinate");let me=(Me&Ye)===Ye,ze=(G&128)!==0;if(!T&&Me===ct&&ze)throw new Error("Point.fromHex: x=0 and x_0=1");return ze!==me&&(Me=f(-Me)),w.fromAffine({x:Me,y:q})}static fromPrivateKey(_){return N(_).point}toRawBytes(){let{x:_,y:T}=this.toAffine(),P=vr(T,t.BYTES);return P[P.length-1]|=_&Ye?128:0,P}toHex(){return Bt(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Ye,f(e.Gx*e.Gy)),w.ZERO=new w(ct,Ye,Ye,ct);let{BASE:E,ZERO:A}=w,R=qo(w,a*8);function v(S){return Z(S,n)}function I(S){return v(Jt(S))}function N(S){let _=a;S=le("private key",S,_);let T=le("hashed private key",s(S),2*_),P=h(T.slice(0,_)),U=T.slice(_,2*_),M=I(P),$=E.multiply(M),G=$.toRawBytes();return{head:P,prefix:U,scalar:M,point:$,pointBytes:G}}function ee(S){return N(S).pointBytes}function H(S=new Uint8Array,..._){let T=kt(..._);return I(s(p(T,le("context",S),!!o)))}function K(S,_,T={}){S=le("message",S),o&&(S=o(S));let{prefix:P,scalar:U,pointBytes:M}=N(_),$=H(T.context,P,S),G=E.multiply($).toRawBytes(),q=H(T.context,G,M,S),X=v($+q*U);Ge("signature.s",X,ct,n);let J=kt(G,vr(X,t.BYTES));return le("result",J,a*2)}let O=_g;function B(S,_,T,P=O){let{context:U,zip215:M}=P,$=t.BYTES;S=le("signature",S,2*$),_=le("message",_),M!==void 0&&at("zip215",M),o&&(_=o(_));let G=Jt(S.slice($,2*$)),q,X,J;try{q=w.fromHex(T,M),X=w.fromHex(S.slice(0,$),M),J=E.multiplyUnsafe(G)}catch{return!1}if(!M&&q.isSmallOrder())return!1;let Ee=H(U,X.toRawBytes(),q.toRawBytes(),_);return X.add(q.multiplyUnsafe(Ee)).subtract(J).clearCofactor().equals(w.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:K,verify:B,ExtendedPoint:w,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,_=w.BASE){return _._setWindowSize(S),_.multiply(BigInt(3)),_}}}}var Xa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Zu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),gx=BigInt(0),Sg=BigInt(1),Qu=BigInt(2),yx=BigInt(3),Rg=BigInt(5),Ig=BigInt(8);function Tg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Xa,a=r*r%s*r%s,c=ne(a,Qu,s)*a%s,u=ne(c,Sg,s)*r%s,f=ne(u,Rg,s)*u%s,l=ne(f,e,s)*f%s,d=ne(l,t,s)*l%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,m=ne(p,o,s)*h%s,g=ne(m,e,s)*f%s;return{pow_p_5_8:ne(g,Qu,s)*r%s,b2:a}}function Bg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Cg(r,e){let t=Xa,n=Z(e*e*e,t),o=Z(n*n*e,t),s=Tg(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,u=Z(i*Zu,t),f=a===r,l=a===Z(-r,t),d=a===Z(-r*Zu,t);return f&&(i=c),(l||d)&&(i=u),Gu(i,t)&&(i=Z(-i,t)),{isValid:f||l,value:i}}var kg=tr(Xa,void 0,!0),Ng={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:kg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ig,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Vn,randomBytes:Jr,adjustScalarBytes:Bg,uvRatio:Cg},rn=Xu(Ng);var nn=32,Nt=64,Yo=32;function Ju(){let r=rn.utils.randomPrivateKey(),e=rn.getPublicKey(r);return{privateKey:nf(r,e),publicKey:e}}function ef(r){if(r.length!==Yo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=rn.getPublicKey(e);return{privateKey:nf(e,t),publicKey:t}}function tf(r,e){let t=r.subarray(0,Yo);return rn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function rf(r,e,t){return rn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function nf(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Yo;n++)t[n]=r[n],t[Yo+n]=e[n];return t}var Fe={get(r=globalThis){let e=r.crypto;if(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/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Za={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function of(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Fe.get();t*=8;async function c(l,d){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof d=="string"&&(d=L(d));let g;if(d.length===0){g=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,l);return Ie([h,m.iv,new Uint8Array(y)])}async function u(l,d){let h=l.subarray(0,s),p=l.subarray(s,s+n),m=l.subarray(s+n),g={name:e,iv:p};typeof d=="string"&&(d=L(d));let y;if(d.length===0)try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,E,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,E,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function on(r,e){let n=await of().encrypt(r,e);return Mn.encode(n)}var Pg=Math.pow(2,7),Og=Math.pow(2,14),Ug=Math.pow(2,21),Qa=Math.pow(2,28),Ja=Math.pow(2,35),ec=Math.pow(2,42),tc=Math.pow(2,49),j=128,Le=127;function de(r){if(r<Pg)return 1;if(r<Og)return 2;if(r<Ug)return 3;if(r<Qa)return 4;if(r<Ja)return 5;if(r<ec)return 6;if(r<tc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function rc(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Mg(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function nc(r,e){let t=r[e],n=0;if(n+=t&Le,t<j||(t=r[e+1],n+=(t&Le)<<7,t<j)||(t=r[e+2],n+=(t&Le)<<14,t<j)||(t=r[e+3],n+=(t&Le)<<21,t<j)||(t=r[e+4],n+=(t&Le)*Qa,t<j)||(t=r[e+5],n+=(t&Le)*Ja,t<j)||(t=r[e+6],n+=(t&Le)*ec,t<j)||(t=r[e+7],n+=(t&Le)*tc,t<j))return n;throw new RangeError("Could not decode varint")}function Fg(r,e){let t=r.get(e),n=0;if(n+=t&Le,t<j||(t=r.get(e+1),n+=(t&Le)<<7,t<j)||(t=r.get(e+2),n+=(t&Le)<<14,t<j)||(t=r.get(e+3),n+=(t&Le)<<21,t<j)||(t=r.get(e+4),n+=(t&Le)*Qa,t<j)||(t=r.get(e+5),n+=(t&Le)*Ja,t<j)||(t=r.get(e+6),n+=(t&Le)*ec,t<j)||(t=r.get(e+7),n+=(t&Le)*tc,t<j))return n;throw new RangeError("Could not decode varint")}function De(r,e,t=0){return e==null&&(e=Ne(de(r))),e instanceof Uint8Array?rc(r,e,t):Mg(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?nc(r,e):Fg(r,e)}var oc=new Float32Array([-0]),rr=new Uint8Array(oc.buffer);function sf(r,e,t){oc[0]=r,e[t]=rr[0],e[t+1]=rr[1],e[t+2]=rr[2],e[t+3]=rr[3]}function af(r,e){return rr[0]=r[e],rr[1]=r[e+1],rr[2]=r[e+2],rr[3]=r[e+3],oc[0]}var sc=new Float64Array([-0]),Pe=new Uint8Array(sc.buffer);function cf(r,e,t){sc[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function lf(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],sc[0]}var Vg=BigInt(Number.MAX_SAFE_INTEGER),Kg=BigInt(Number.MIN_SAFE_INTEGER),Xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Rr;if(e<Vg&&e>Kg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>uf&&(o=0n,++n>uf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Rr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Rr}},Rr=new Xe(0,0);Rr.toBigInt=function(){return 0n};Rr.zzEncode=Rr.zzDecode=function(){return this};Rr.length=function(){return 1};var uf=4294967296n;function ff(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function hf(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ic(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function jo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ac=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;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,ut(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ut(this,4);return jo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return jo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=af(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=lf(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return hf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ut(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ut(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ut(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ut(this,8);let e=jo(this.buf,this.pos+=4),t=jo(this.buf,this.pos+=4);return new Xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=nc(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function cc(r){return new ac(r instanceof Uint8Array?r:r.subarray())}function Ve(r,e,t){let n=cc(r);return e.decode(n,void 0,t)}function lc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ne(i);o+i>e&&(n=Ne(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Ir=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function uc(){}var hc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Hg=lc();function $g(r){return globalThis.Buffer!=null?Ne(r):Hg(r)}var zn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ir(uc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ir(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new dc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Wo,10,Xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Xe.fromBigInt(e);return this._push(Wo,t.length(),t)}uint64Number(e){return this._push(rc,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Xe.fromBigInt(e).zzEncode();return this._push(Wo,t.length(),t)}sint64Number(e){let t=Xe.fromNumber(e).zzEncode();return this._push(Wo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fc,1,e?1:0)}fixed32(e){return this._push(qn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Xe.fromBigInt(e);return this._push(qn,4,t.lo)._push(qn,4,t.hi)}fixed64Number(e){let t=Xe.fromNumber(e);return this._push(qn,4,t.lo)._push(qn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(sf,4,e)}double(e){return this._push(cf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fc,1,0):this.uint32(t)._push(zg,t,e)}string(e){let t=ff(e);return t!==0?this.uint32(t)._push(ic,t,e):this._push(fc,1,0)}fork(){return this.states=new hc(this),this.head=this.tail=new Ir(uc,0,0),this.len=0,this}reset(){return this.states!=null?(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 Ir(uc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=$g(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function fc(r,e,t){e[t]=r&255}function qg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var dc=class extends Ir{next;constructor(e,t){super(qg,e,t),this.next=void 0}};function Wo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function qn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function zg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(zn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Gg,e,r),this},zn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Yg,e,r),this});function Gg(r,e,t){e.set(r,t)}function Yg(r,e,t){r.length<40?ic(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function pc(){return new zn}function Ke(r,e){let t=pc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var sn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(sn||(sn={}));function Xo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function mc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Xo("enum",sn.VARINT,t,n)}function He(r,e){return Xo("message",sn.LENGTH_DELIMITED,r,e)}var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(oe||(oe={}));var gc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(gc||(gc={}));(function(r){r.codec=()=>mc(gc)})(oe||(oe={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(yt||(yt={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(wt||(wt={}));var Gn=class{_key;constructor(e){this._key=an(e,nn)}verify(e,t){return rf(this._key,t,e)}marshal(){return this._key}get bytes(){return yt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}},Tr=class{_key;_publicKey;constructor(e,t){this._key=an(e,Nt),this._publicKey=an(t,nn)}sign(e){return tf(this._key,e)}get public(){return new Gn(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return tt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=It.digest(this.public.bytes);return ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function jg(r){if(r.length>Nt){r=an(r,Nt+nn);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Tr(n,o)}r=an(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(nn);return new Tr(e,t)}function Wg(r){return r=an(r,nn),new Gn(r)}async function Xg(){let{privateKey:r,publicKey:e}=Ju();return new Tr(r,e)}async function pf(r){let{privateKey:e,publicKey:t}=ef(r);return new Tr(e,t)}function an(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new x(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function V(r,e="utf8"){let t=Uo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ic={};ve(Ic,{MAX_RSA_KEY_SIZE:()=>oo,RsaPrivateKey:()=>hn,RsaPublicKey:()=>no,fromJwk:()=>_0,generateKeyPair:()=>A0,unmarshalRsaPrivateKey:()=>Sc,unmarshalRsaPublicKey:()=>v0});function rt(r){if(isNaN(r)||r<=0)throw new x("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Jr(r)}var ir={};ve(ir,{exportToPem:()=>y0,importFromPem:()=>w0,jwkToPkcs1:()=>d0,jwkToPkix:()=>m0,pkcs1ToJwk:()=>h0,pkixToJwk:()=>p0});var Qo=class extends Zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Mo(e);let n=Wt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Xr(this),this.iHash.update(e),this}digestInto(e){Xr(this),Wr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Yn=(r,e,t)=>new Qo(r,e).update(t).digest();Yn.create=(r,e)=>new Qo(r,e);function Zg(r,e,t,n){Mo(r);let o=Mu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(jr(s),jr(i),jr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wt(e),u=Wt(t),f=new Uint8Array(i),l=Yn.create(r,c),d=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:d}}function Qg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function wc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Zg(r,e,t,n),f,l=new Uint8Array(4),d=Qr(l),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<s;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);d.setInt32(0,p,!1),(f=u._cloneInto(f)).update(l).digestInto(h),g.set(h.subarray(0,g.length)),await Ou(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let y=0;y<g.length;y++)g[y]^=h[y]})}return Qg(c,u,a,f,h)}var z=gr(mf());function Br(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function nr(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function ts(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Ec(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Br(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Br(s,8)-n}function gf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=nr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=nr(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function yf(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function je(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var S1=Math.log(2);function rs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function xc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ut(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Wn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xc(this.items)}},jn=[new Uint8Array([1])],wf="0123456789";var un="",ht=new ArrayBuffer(0),vc=new Uint8Array(0),Xn="EndOfContent",Ef="OCTET STRING",xf="BIT STRING";function Mt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?z.BufferSourceConverter.toUint8Array(s.valueHex):vc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ut(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ht)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:z.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Dt=class{constructor({blockLength:e=0,error:t=un,warnings:n=[],valueBeforeDecode:o=vc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=z.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:z.Convert.ToHex(this.valueBeforeDecodeView)}}};Dt.NAME="baseBlock";var Oe=class extends Dt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Oe.NAME="valueBlock";var ns=class extends Mt(Dt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?z.BufferSourceConverter.toUint8Array(e.valueHex):vc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ht}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=nr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Br(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ns.NAME="identificationBlock";var os=class extends Dt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Br(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=nr(this.length,8);if(o.byteLength>127)return this.error="Too big length",ht;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};os.NAME="lengthBlock";var C={},Te=class extends Dt{constructor({name:e=un,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ns(o),this.lenBlock=new os(o),this.valueBlock=s?new s(o):new Oe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Wn;t||vf(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ht:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():z.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return yf(t,n)}};Te.NAME="BaseBlock";function vf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)vf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ss=class extends Te{constructor({value:e=un,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ss.NAME="BaseStringBlock";var is=class extends Mt(Oe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};is.NAME="PrimitiveValueBlock";var _f,as=class extends Te{constructor(e={}){super(e,is),this.idBlock.isConstructed=!1}};_f=as;C.Primitive=_f;as.NAME="PRIMITIVE";function a0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Vs(r,e=0,t=r.length){let n=e,o=new Te({},Oe),s=new Dt;if(!Ut(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Te;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=a0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function fn(r){if(!r.byteLength){let e=new Te({},Oe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Vs(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function c0(r,e){return r?1:e}var bt=class extends Oe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;c0(this.isIndefiniteForm,n)>0;){let i=Vs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Xn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Wn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ht:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};bt.NAME="ConstructedValueBlock";var Af,or=class extends Te{constructor(e={}){super(e,bt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
3
3
  `).map(o=>` ${o}`).join(`
4
4
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
5
  ${e.join(`
6
- `)}`:`${t} :`}};vf=er;C.Constructed=vf;er.NAME="CONSTRUCTED";var is=class extends Pe{fromBER(e,t,n){return t}toBER(e){return ht}};is.override="EndOfContentValueBlock";var _f,as=class extends Ie{constructor(e={}){super(e,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_f=as;C.EndOfContent=_f;as.NAME=Gn;var Af,tr=class extends Ie{constructor(e={}){super(e,Pe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Af=tr;C.Null=Af;tr.NAME="NULL";var cs=class extends Ut(Pe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Ot(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="BooleanValueBlock";var Sf,ls=class extends Ie{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Sf=ls;C.Boolean=Sf;ls.NAME="BOOLEAN";var us=class extends Ut(bt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==wf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?bt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};us.NAME="OctetStringValueBlock";var Rf,Dt=class r extends Ie{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},us),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ms(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};Rf=Dt;C.OctetString=Rf;Dt.NAME=wf;var fs=class extends Ut(bt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==bf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ms(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return bt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ht;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};fs.NAME="BitStringValueBlock";var If,sn=class extends Ie{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},fs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return er.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};If=sn;C.BitString=If;sn.NAME=bf;var Tf;function a0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let p=f;p>=0;p--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=Jo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Jo(t,s)),s}function yf(r){if(r>=qn.length)for(let e=qn.length;e<=r;e++){let t=new Uint8Array([0]),n=qn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=Jo(t,n)),qn.push(n)}return qn[r]}function c0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Yn=class extends Ut(Pe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=yc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(pf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=c0(yf(n),t),i="-";break;default:t=a0(t,yf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=gf.charAt(t[c]));return a===!1&&(i+=gf.charAt(0)),i}};Tf=Yn;Yn.NAME="IntegerValueBlock";Object.defineProperty(Tf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Bf,pe=class r extends Ie{constructor(e={}){super(e,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return es(),BigInt(this.valueBlock.toString())}static fromBigInt(e){es();let t=BigInt(e),n=new zn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Bf=pe;C.Integer=Bf;pe.NAME="INTEGER";var Cf,hs=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Cf=hs;C.Enumerated=Cf;hs.NAME="ENUMERATED";var Wn=class extends Ut(Pe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){es();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Wn.NAME="sidBlock";var ds=class extends Pe{constructor({value:e=an,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ht;t.push(o)}return wc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Wn;if(o>Number.MAX_SAFE_INTEGER){es();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ds.NAME="ObjectIdentifierValueBlock";var kf,ft=class extends Ie{constructor(e={}){super(e,ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};kf=ft;C.ObjectIdentifier=kf;ft.NAME="OBJECT IDENTIFIER";var jn=class extends Ut(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var ps=class extends Pe{constructor({value:e=an,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ht;n.push(s)}return wc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ps.NAME="RelativeObjectIdentifierValueBlock";var Nf,ms=class extends Ie{constructor(e={}){super(e,ps),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Nf=ms;C.RelativeObjectIdentifier=Nf;ms.NAME="RelativeObjectIdentifier";var Lf,_e=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Lf=_e;C.Sequence=Lf;_e.NAME="SEQUENCE";var Df,gs=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Df=gs;C.Set=Df;gs.NAME="SET";var ys=class extends Ut(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=an}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="StringValueBlock";var ws=class extends ys{};ws.NAME="SimpleStringValueBlock";var Ke=class extends ns{constructor({...e}={}){super(e,ws)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Ke.NAME="SIMPLE STRING";var bs=class extends Ke{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};bs.NAME="Utf8StringValueBlock";var Pf,Pt=class extends bs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Pf=Pt;C.Utf8String=Pf;Pt.NAME="UTF8String";var Es=class extends Ke{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Es.NAME="BmpStringValueBlock";var Of,xs=class extends Es{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Of=xs;C.BmpString=Of;xs.NAME="BMPString";var vs=class extends Ke{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Jt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};vs.NAME="UniversalStringValueBlock";var Uf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Uf=_s;C.UniversalString=Uf;_s.NAME="UniversalString";var Mf,As=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Mf=As;C.NumericString=Mf;As.NAME="NumericString";var Ff,Ss=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Ff=Ss;C.PrintableString=Ff;Ss.NAME="PrintableString";var Vf,Rs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Vf=Rs;C.TeletexString=Vf;Rs.NAME="TeletexString";var Kf,Is=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Kf=Is;C.VideotexString=Kf;Is.NAME="VideotexString";var Hf,Ts=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Hf=Ts;C.IA5String=Hf;Ts.NAME="IA5String";var $f,Bs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};$f=Bs;C.GraphicString=$f;Bs.NAME="GraphicString";var qf,Xn=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};qf=Xn;C.VisibleString=qf;Xn.NAME="VisibleString";var zf,Cs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};zf=Cs;C.GeneralString=zf;Cs.NAME="GeneralString";var Gf,ks=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Gf=ks;C.CharacterString=Gf;ks.NAME="CharacterString";var Yf,Zn=class extends Xn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Ge(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Ge(this.month,2),t[2]=Ge(this.day,2),t[3]=Ge(this.hour,2),t[4]=Ge(this.minute,2),t[5]=Ge(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Yf=Zn;C.UTCTime=Yf;Zn.NAME="UTCTime";var Wf,Ns=class extends Zn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),l=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(h.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,h.length===4){if(d=parseInt(h.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Ge(this.year,4)),t.push(Ge(this.month,2)),t.push(Ge(this.day,2)),t.push(Ge(this.hour,2)),t.push(Ge(this.minute,2)),t.push(Ge(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Ge(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Wf=Ns;C.GeneralizedTime=Wf;Ns.NAME="GeneralizedTime";var jf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};jf=Ls;C.DATE=jf;Ls.NAME="DATE";var Xf,Ds=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Xf=Ds;C.TimeOfDay=Xf;Ds.NAME="TimeOfDay";var Zf,Ps=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Zf=Ps;C.DateTime=Zf;Ps.NAME="DateTime";var Qf,Os=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Qf=Os;C.Duration=Qf;Os.NAME="Duration";var Jf,Us=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Jf=Us;C.TIME=Jf;Us.NAME="TIME";function u0(r){let{result:e}=cn(r),t=e.valueBlock.value;return{n:F(Et(t[1].toBigInt()),"base64url"),e:F(Et(t[2].toBigInt()),"base64url"),d:F(Et(t[3].toBigInt()),"base64url"),p:F(Et(t[4].toBigInt()),"base64url"),q:F(Et(t[5].toBigInt()),"base64url"),dp:F(Et(t[6].toBigInt()),"base64url"),dq:F(Et(t[7].toBigInt()),"base64url"),qi:F(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function f0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new pe({value:0}),pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url"))),pe.fromBigInt(xt(L(r.d,"base64url"))),pe.fromBigInt(xt(L(r.p,"base64url"))),pe.fromBigInt(xt(L(r.q,"base64url"))),pe.fromBigInt(xt(L(r.dp,"base64url"))),pe.fromBigInt(xt(L(r.dq,"base64url"))),pe.fromBigInt(xt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function h0(r){let{result:e}=cn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:F(Et(t[0].toBigInt()),"base64url"),e:F(Et(t[1].toBigInt()),"base64url")}}function d0(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new tr]}),new sn({valueHex:new _e({value:[pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Et(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function xt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var p0=16,Ec=32,xc=1e4;async function m0(r,e){let t=Ue.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new tr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=et(p0),a=await mc(On,e,i,{c:xc,dkLen:Ec}),c=et(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new _e({value:[new Dt({valueHex:i}),new pe({value:xc}),new pe({value:Ec}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new tr]})]}),p=new _e({value:[new ft({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new ft({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new _e({value:[p,new Dt({valueHex:f})]}).toBER(),m=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...F(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function g0(r,e){let t=Ue.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=cn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=y0(s),l=await mc(On,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Qn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=cn(h);n=eh(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=cn(o);n=eh(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return vc(n)}function y0(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new E("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Qn(s.valueBlock.value[0].getValue()),a=xc,c=Ec;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new E("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new E("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Qn(u.valueBlock.value[1].getValue());return{cipherText:Qn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function eh(r){return Qn(r.valueBlock.value[2].getValue())}function Qn(r){return new Uint8Array(r,0,r.byteLength)}async function th(r){let e=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await oh(e);return{privateKey:t[0],publicKey:t[1]}}async function _c(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await w0(r)],n=await oh({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function rh(r,e){let t=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function nh(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function oh(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)])}async function w0(r){return Ue.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Fs(r){if(r.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return L(r.n,"base64url").length*8}var eo=8192,Jn=class{_key;constructor(e){this._key=e}verify(e,t){return nh(this._key,t,e)}marshal(){return rr.jwkToPkix(this._key)}get bytes(){return yt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},ln=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return et(16)}sign(e){return rh(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Jn(this._publicKey)}marshal(){return rr.jwkToPkcs1(this._key)}get bytes(){return wt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return rr.exportToPem(this,e);if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function vc(r){let e=rr.pkcs1ToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await _c(e);return new ln(t.privateKey,t.publicKey)}function E0(r){let e=rr.pkixToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Jn(e)}async function x0(r){if(Fs(r)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await _c(r);return new ln(e.privateKey,e.publicKey)}async function v0(r){if(r>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await th(r);return new ln(e.privateKey,e.publicKey)}var Bc={};ve(Bc,{Secp256k1PrivateKey:()=>ro,Secp256k1PublicKey:()=>to,generateKeyPair:()=>P0,unmarshalSecp256k1PrivateKey:()=>L0,unmarshalSecp256k1PublicKey:()=>D0});var _0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),Sc=class extends Zr{constructor(){super(64,32,8,!1),this.A=nr[0]|0,this.B=nr[1]|0,this.C=nr[2]|0,this.D=nr[3]|0,this.E=nr[4]|0,this.F=nr[5]|0,this.G=nr[6]|0,this.H=nr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=or[l-15],h=or[l-2],d=it(p,7)^it(p,18)^p>>>3,m=it(h,17)^it(h,19)^h>>>10;or[l]=m+or[l-7]+d+or[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let p=it(a,6)^it(a,11)^it(a,25),h=f+p+Ou(a,c,u)+_0[l]+or[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Uu(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var sh=Uo(()=>new Sc);function ih(r){r.lowS!==void 0&&at("lowS",r.lowS),r.prehash!==void 0&&at("prehash",r.prehash)}function A0(r){let e=Fn(r);gt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:S0,hexToBytes:R0}=Vo,Rr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Rr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:S0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?R0(r):r;Qr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(t.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},sr=BigInt(0),Ae=BigInt(1),j1=BigInt(2),ah=BigInt(3),X1=BigInt(4);function I0(r){let e=A0(r),{Fp:t}=e,n=e.toBytes||((d,m,w)=>{let g=m.toAffine();return Ct(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(d=>{let m=d.subarray(1),w=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:w,y:g}});function s(d){let{a:m,b:w}=e,g=t.sqr(d),y=t.mul(g,d);return t.add(t.add(y,t.mul(d,m)),w)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return Un(d,Ae,e.n)}function a(d){let{allowedPrivateKeyLengths:m,nByteLength:w,wrapPrivateKey:g,n:y}=e;if(m&&typeof d!="bigint"){if(jt(d)&&(d=Tt(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(w*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(le("private key",d,w))}catch{throw new Error(`private key must be ${w} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=X(b,y)),qe("private key",b,Ae,y),b}function c(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}let u=br((d,m)=>{let{px:w,py:g,pz:y}=d;if(t.eql(y,t.ONE))return{x:w,y:g};let b=d.is0();m==null&&(m=b?t.ONE:t.inv(y));let x=t.mul(w,m),A=t.mul(g,m),R=t.mul(y,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x,y:A}}),f=br(d=>{if(d.is0()){if(e.allowInfinityPoint&&!t.is0(d.py))return;throw new Error("bad point: ZERO")}let{x:m,y:w}=d.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not FE");let g=t.sqr(w),y=s(m);if(!t.eql(g,y))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class l{constructor(m,w,g){if(this.px=m,this.py=w,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required");Object.freeze(this)}static fromAffine(m){let{x:w,y:g}=m||{};if(!m||!t.isValid(w)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let y=b=>t.eql(b,t.ZERO);return y(w)&&y(g)?l.ZERO:new l(w,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let w=t.invertBatch(m.map(g=>g.pz));return m.map((g,y)=>g.toAffine(w[y])).map(l.fromAffine)}static fromHex(m){let w=l.fromAffine(o(le("pointHex",m)));return w.assertValidity(),w}static fromPrivateKey(m){return l.BASE.multiply(a(m))}_setWindowSize(m){h.setWindowSize(this,m)}assertValidity(){f(this)}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.eql(t.mul(w,A),t.mul(b,y)),_=t.eql(t.mul(g,A),t.mul(x,y));return R&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:w}=e,g=t.mul(w,ah),{px:y,py:b,pz:x}=this,A=t.ZERO,R=t.ZERO,_=t.ZERO,I=t.mul(y,y),$=t.mul(b,b),V=t.mul(x,x),K=t.mul(y,b);return K=t.add(K,K),_=t.mul(y,x),_=t.add(_,_),A=t.mul(m,_),R=t.mul(g,V),R=t.add(A,R),A=t.sub($,R),R=t.add($,R),R=t.mul(A,R),A=t.mul(K,A),_=t.mul(g,_),V=t.mul(m,V),K=t.sub(I,V),K=t.mul(m,K),K=t.add(K,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,V),I=t.mul(I,K),R=t.add(R,I),V=t.mul(b,x),V=t.add(V,V),I=t.mul(V,K),A=t.sub(A,I),_=t.mul(V,$),_=t.add(_,_),_=t.add(_,_),new l(A,R,_)}add(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.ZERO,_=t.ZERO,I=t.ZERO,$=e.a,V=t.mul(e.b,ah),K=t.mul(w,b),Q=t.mul(g,x),D=t.mul(y,A),N=t.add(w,g),S=t.add(b,x);N=t.mul(N,S),S=t.add(K,Q),N=t.sub(N,S),S=t.add(w,y);let v=t.add(b,A);return S=t.mul(S,v),v=t.add(K,D),S=t.sub(S,v),v=t.add(g,y),R=t.add(x,A),v=t.mul(v,R),R=t.add(Q,D),v=t.sub(v,R),I=t.mul($,S),R=t.mul(V,D),I=t.add(R,I),R=t.sub(Q,I),I=t.add(Q,I),_=t.mul(R,I),Q=t.add(K,K),Q=t.add(Q,K),D=t.mul($,D),S=t.mul(V,S),Q=t.add(Q,D),D=t.sub(K,D),D=t.mul($,D),S=t.add(S,D),K=t.mul(Q,S),_=t.add(_,K),K=t.mul(v,S),R=t.mul(N,R),R=t.sub(R,K),K=t.mul(N,Q),I=t.mul(v,I),I=t.add(I,K),new l(R,_,I)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,m,l.normalizeZ)}multiplyUnsafe(m){qe("scalar",m,sr,e.n);let w=l.ZERO;if(m===sr)return w;if(m===Ae)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:y,k1:b,k2neg:x,k2:A}=g.splitScalar(m),R=w,_=w,I=this;for(;b>sr||A>sr;)b&Ae&&(R=R.add(I)),A&Ae&&(_=_.add(I)),I=I.double(),b>>=Ae,A>>=Ae;return y&&(R=R.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),R.add(_)}multiply(m){let{endo:w,n:g}=e;qe("scalar",m,Ae,g);let y,b;if(w){let{k1neg:x,k1:A,k2neg:R,k2:_}=w.splitScalar(m),{p:I,f:$}=this.wNAF(A),{p:V,f:K}=this.wNAF(_);I=h.constTimeNegate(x,I),V=h.constTimeNegate(R,V),V=new l(t.mul(V.px,w.beta),V.py,V.pz),y=I.add(V),b=$.add(K)}else{let{p:x,f:A}=this.wNAF(m);y=x,b=A}return l.normalizeZ([y,b])[0]}multiplyAndAddUnsafe(m,w,g){let y=l.BASE,b=(A,R)=>R===sr||R===Ae||!A.equals(y)?A.multiplyUnsafe(R):A.multiply(R),x=b(this,w).add(b(m,g));return x.is0()?void 0:x}toAffine(m){return u(this,m)}isTorsionFree(){let{h:m,isTorsionFree:w}=e;if(m===Ae)return!0;if(w)return w(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:w}=e;return m===Ae?this:w?w(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return at("isCompressed",m),this.assertValidity(),n(l,this,m)}toHex(m=!0){return at("isCompressed",m),Tt(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=$o(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function T0(r){let e=Fn(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ch(r){let e=T0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(N){return X(N,n)}function a(N){return Ko(N,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=I0({...e,toBytes(N,S,v){let T=S.toAffine(),B=t.toBytes(T.x),P=Ct;return at("isCompressed",v),v?P(Uint8Array.from([S.hasEvenY()?2:3]),B):P(Uint8Array.from([4]),B,t.toBytes(T.y))},fromBytes(N){let S=N.length,v=N[0],T=N.subarray(1);if(S===o&&(v===2||v===3)){let B=Bt(T);if(!Un(B,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(B),O;try{O=t.sqrt(P)}catch(H){let G=H instanceof Error?": "+H.message:"";throw new Error("Point is not on curve"+G)}let U=(O&Ae)===Ae;return(v&1)===1!==U&&(O=t.neg(O)),{x:B,y:O}}else if(S===s&&v===4){let B=t.fromBytes(T.subarray(0,t.BYTES)),P=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:B,y:P}}else throw new Error(`Point of length ${S} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=N=>Tt(Zt(N,e.nByteLength));function h(N){let S=n>>Ae;return N>S}function d(N){return h(N)?i(-N):N}let m=(N,S,v)=>Bt(N.slice(S,v));class w{constructor(S,v,T){this.r=S,this.s=v,this.recovery=T,this.assertValidity()}static fromCompact(S){let v=e.nByteLength;return S=le("compactSignature",S,v*2),new w(m(S,0,v),m(S,v,2*v))}static fromDER(S){let{r:v,s:T}=Rr.toSig(le("DER",S));return new w(v,T)}assertValidity(){qe("r",this.r,Ae,n),qe("s",this.s,Ae,n)}addRecoveryBit(S){return new w(this.r,this.s,S)}recoverPublicKey(S){let{r:v,s:T,recovery:B}=this,P=R(le("msgHash",S));if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");let O=B===2||B===3?v+e.n:v;if(O>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=B&1?"03":"02",z=c.fromHex(U+p(O)),H=a(O),G=i(-P*H),oe=i(T*H),se=c.BASE.multiplyAndAddUnsafe(z,G,oe);if(!se)throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return yr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let g={isValidPrivateKey(N){try{return u(N),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let N=qa(e.n);return Gu(e.randomBytes(N),e.n)},precompute(N=8,S=c.BASE){return S._setWindowSize(N),S.multiply(BigInt(3)),S}};function y(N,S=!0){return c.fromPrivateKey(N).toRawBytes(S)}function b(N){let S=jt(N),v=typeof N=="string",T=(S||v)&&N.length;return S?T===o||T===s:v?T===2*o||T===2*s:N instanceof c}function x(N,S,v=!0){if(b(N))throw new Error("first arg must be private key");if(!b(S))throw new Error("second arg must be public key");return c.fromHex(S).multiply(u(N)).toRawBytes(v)}let A=e.bits2int||function(N){let S=Bt(N),v=N.length*8-e.nBitLength;return v>0?S>>BigInt(v):S},R=e.bits2int_modN||function(N){return i(A(N))},_=Mn(e.nBitLength);function I(N){return qe(`num < 2^${e.nBitLength}`,N,sr,_),Zt(N,e.nByteLength)}function $(N,S,v=V){if(["recovered","canonical"].some(Ee=>Ee in v))throw new Error("sign() legacy options not supported");let{hash:T,randomBytes:B}=e,{lowS:P,prehash:O,extraEntropy:U}=v;P==null&&(P=!0),N=le("msgHash",N),ih(v),O&&(N=le("prehashed msgHash",T(N)));let z=R(N),H=u(S),G=[I(H),I(z)];if(U!=null&&U!==!1){let Ee=U===!0?B(t.BYTES):U;G.push(le("extraEntropy",Ee))}let oe=Ct(...G),se=z;function $e(Ee){let me=A(Ee);if(!l(me))return;let nt=a(me),xe=c.BASE.multiply(me).toAffine(),ot=i(xe.x);if(ot===sr)return;let dr=i(nt*i(se+ot*H));if(dr===sr)return;let Cn=(xe.x===ot?0:2)|Number(xe.y&Ae),Io=dr;return P&&h(dr)&&(Io=d(dr),Cn^=1),new w(ot,Io,Cn)}return{seed:oe,k2sig:$e}}let V={lowS:e.lowS,prehash:!1},K={lowS:e.lowS,prehash:!1};function Q(N,S,v=V){let{seed:T,k2sig:B}=$(N,S,v),P=e;return Va(P.hash.outputLen,P.nByteLength,P.hmac)(T,B)}c.BASE._setWindowSize(8);function D(N,S,v,T=K){let B=N;if(S=le("msgHash",S),v=le("publicKey",v),"strict"in T)throw new Error("options.strict was renamed to lowS");ih(T);let{lowS:P,prehash:O}=T,U,z;try{if(typeof B=="string"||jt(B))try{U=w.fromDER(B)}catch(xe){if(!(xe instanceof Rr.Err))throw xe;U=w.fromCompact(B)}else if(typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint"){let{r:xe,s:ot}=B;U=new w(xe,ot)}else throw new Error("PARSE");z=c.fromHex(v)}catch(xe){if(xe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&U.hasHighS())return!1;O&&(S=e.hash(S));let{r:H,s:G}=U,oe=R(S),se=a(G),$e=i(oe*se),Ee=i(H*se),me=c.BASE.multiplyAndAddUnsafe(z,$e,Ee)?.toAffine();return me?i(me.x)===H:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:x,sign:Q,verify:D,ProjectivePoint:c,Signature:w,utils:g}}function B0(r){return{hash:r,hmac:(e,...t)=>$n(r,e,La(...t)),randomBytes:Xr}}function lh(r,e){let t=n=>ch({...r,...B0(n)});return Object.freeze({...t(e),create:t})}var hh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),C0=BigInt(1),Rc=BigInt(2),fh=(r,e)=>(r+e/Rc)/e;function k0(r){let e=hh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=te(f,t,e)*f%e,p=te(l,t,e)*f%e,h=te(p,Rc,e)*u%e,d=te(h,o,e)*h%e,m=te(d,s,e)*d%e,w=te(m,a,e)*m%e,g=te(w,c,e)*w%e,y=te(g,a,e)*m%e,b=te(y,t,e)*f%e,x=te(b,i,e)*d%e,A=te(x,n,e)*u%e,R=te(A,Rc,e);if(!Ic.eql(Ic.sqr(R),r))throw new Error("Cannot find square root");return R}var Ic=Ho(hh,void 0,void 0,{sqrt:k0}),dt=lh({a:BigInt(0),b:BigInt(7),Fp:Ic,n:uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=uh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-C0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=fh(s*r,e),c=fh(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,p=f>i;if(l&&(u=e-u),p&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},sh),sv=BigInt(0);var iv=dt.ProjectivePoint;function dh(){return dt.utils.randomPrivateKey()}function ph(r,e){let t=Se.digest(e instanceof Uint8Array?e:e.subarray());if(Je(t))return t.then(({digest:n})=>dt.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return dt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function mh(r,e,t){let n=Se.digest(t instanceof Uint8Array?t:t.subarray());if(Je(n))return n.then(({digest:o})=>dt.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return dt.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function gh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function yh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Tc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function wh(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var to=class{_key;constructor(e){Tc(e),this._key=e}verify(e,t){return mh(this._key,t,e)}marshal(){return gh(this._key)}get bytes(){return yt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}},ro=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??wh(e),yh(this._key),Tc(this._publicKey)}sign(e){return ph(this._key,e)}get public(){return new to(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function L0(r){return new ro(r)}function D0(r){return new to(r)}async function P0(){let r=dh();return new ro(r)}var ir={rsa:Ac,ed25519:pc,secp256k1:Bc};function Cc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function kc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw Cc(r)}async function bh(r,e){return kc(r).generateKeyPair(e??2048)}function no(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPublicKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PublicKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Cc(e.Type??"unknown")}}function Eh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}async function oo(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPrivateKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PrivateKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Cc(e.Type??"RSA")}}function xh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}function O0(r,e){try{if(typeof r=="string"&&r.length>0)return U0(r);if(typeof r=="number"&&isFinite(r))return e?.long?F0(r):M0(r);throw new Error("Value is not a string or number.")}catch(t){let n=V0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function U0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ks=O0;function M0(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function F0(r){let e=Math.abs(r);return e>=864e5?Vs(r,e,864e5,"day"):e>=36e5?Vs(r,e,36e5,"hour"):e>=6e4?Vs(r,e,6e4,"minute"):e>=1e3?Vs(r,e,1e3,"second"):`${r} ms`}function Vs(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function V0(r){return typeof r=="object"&&r!==null&&"message"in r}function Nc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Ks,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let p=0;p<f.length;p++)l=(l<<5)-l+f.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,p=null,h,d;function m(...w){if(!m.enabled)return;let g=m,y=Number(new Date),b=y-(l||y);g.diff=b,g.prev=l,g.curr=y,l=y,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let x=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(R,_)=>{if(R==="%%")return"%";x++;let I=t.formatters[_];if(typeof I=="function"){let $=w[x];R=I.call(g,$),w.splice(x,1),x--}return R}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,d=t.enabled(f)),d),set:w=>{p=w}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let p=t(this.namespace+(typeof l>"u"?":":l)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(l=0;l<h;l++)p[l]&&(f=p[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,p;for(l=0,p=t.skips.length;l<p;l++)if(t.skips[l].test(f))return!1;for(l=0,p=t.names.length;l<p;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}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 t.setupFormatters(t.formatters),t.enable(t.load()),t}var Hs=Y0(),K0=["#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 H0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function $0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ks(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var q0=console.debug??console.log??(()=>{});function z0(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function G0(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Y0(){try{return localStorage}catch{}}function W0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var vh=Nc({formatArgs:$0,save:z0,load:G0,useColors:H0,setupFormatters:W0,colors:K0,storage:Hs,log:q0});var je=vh;je.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);je.formatters.t=r=>r==null?"undefined":Ye.baseEncode(r);je.formatters.m=r=>r==null?"undefined":Dn.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function j0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function $s(){return{forComponent(r){return X0(r)}}}function X0(r){let e=j0(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=je(`${r}:trace`)),Object.assign(je(r),{error:je(`${r}:error`),trace:e})}var Ah=Symbol.for("nodejs.util.inspect.custom"),_h=Object.values(zt).map(r=>r.decoder).reduce((r,e)=>r.or(e),zt.identity.decoder),Sh=114,Pc=36,Oc=37,so=class{type;multihash;privateKey;publicKey;string;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()})`}[Bo]=!0;toString(){return this.string==null&&(this.string=ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Qe.createV1(Sh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return J(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Ah](){return`PeerId(${this.toString()})`}},Ir=class extends so{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends so{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends so{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Lc=2336,Dc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Rt.digest(L(this.url))}[Ah](){return`PeerId(${this.url})`}[Bo]=!0;toString(){return this.toCID().toString()}toCID(){return Qe.createV1(Lc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function Rh(r){if(r.type==="RSA")return new Ir(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Br(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??_h,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ae.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Ir({multihash:t})}return un(_h.decode(r))}function un(r){try{let e=mr(r);if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:e});if(e.digest.length===Oc)return new Br({multihash:e})}if(e.code===Se.code)return new Ir({multihash:e})}catch{return Z0(Qe.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Z0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Sh&&r.code!==Lc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Lc){let t=F(r.multihash.digest);return new Dc(new URL(t))}let e=r.multihash;if(e.code===Se.code)return new Ir({multihash:r.multihash});if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:r.multihash});if(e.digest.length===Oc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function fn(r,e){return r.length===Pc?new Tr({multihash:mt(Rt.code,r),privateKey:e}):r.length===Oc?new Br({multihash:mt(Rt.code,r),privateKey:e}):new Ir({multihash:await Se.digest(r),publicKey:r,privateKey:e})}function hn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return hn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return hn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var Mt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.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 hn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return hn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var kh=Symbol.for("@achingbrain/uint8arraylist");function Ch(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function zs(r){return!!r?.[kh]}var we=class r{bufs;length;[kh]=!0;constructor(...e){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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(zs(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(zs(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ch(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(zs(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:o}=this._subList(e,t);return Re(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Re(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!zs(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let p=u;p>=0;p--){let h=this.get(l+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!J(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Uc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Uc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=st(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?J(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var kr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=Cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Mc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Lh=new globalThis.TextEncoder;function Q0(r,e){let t=Mc[e],n=Nh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function J0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Mc[e],o=Nh[e],s=r;for(;s.length>0;){let i=Lh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Fc(r,{size:e=32,utf8Buffer:t}={}){if(!Mc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return J0(r,e,t);r=Lh.encode(r)}return Q0(r,e)}var ey=pr(Bh(),1);var ao={hash:r=>Number(Fc(r,{size:32})),hashV:(r,e)=>ty(ao.hash(r,e))};function ty(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var ry=500,co=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ao,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new kr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new kr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize));for(let a=0;a<ry;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ny={1:.5,2:.84,4:.95,8:.98};function oy(r=.001){return r>.002?2:r>1e-5?4:8}function Dh(r,e=.001){let t=oy(e),n=ny[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Uc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Gs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ao,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new co({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new co({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Vc(r,e=.001,t){return new Gs({...Dh(r,e),...t??{}})}var Ph=async()=>{let r=await bh("Ed25519"),e=await sy(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function sy(r){return fn(Eh(r.public),xh(r))}var Oh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var lo;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(lo||(lo={}));var dn=class r{static createFromProtobuf=async e=>{let t=lo.decode(e),n=await fn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Uh(n,o,s),c=await(await oo(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new E("envelope signature is not valid for the given domain",Oh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=lo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return J(this.marshal(),e.marshal())}async validate(e){let t=Uh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return no(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Uh=(r,e,t)=>{let n=L(r),o=Le(n.byteLength),s=Le(e.length),i=Le(t.length);return new we(o,n,s,e,i,t)};function Mh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ys=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Fh=45,iy=15,pn=new Ys;function Kc(r){if(!(r.length>iy))return pn.new(r).parseWith(()=>pn.readIPv4Addr())}function Hc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPv6Addr())}function Ws(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPAddr())}var sA=parseInt("0xFFFF",16),iA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function mn(r){return!!Kc(r)}function gn(r){return!!Hc(r)}function js(r){return!!Ws(r)}var Hh=mn,fy=gn,$c=function(r){let e=0;if(r=r.toString().trim(),Hh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(fy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Hh(t[n]),i;s&&(i=$c(t[n]),t[n]=F(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},$h=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var yn={},qc={},dy=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];dy.forEach(r=>{let e=py(...r);qc[e.code]=e,yn[e.name]=e});function py(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function j(r){if(typeof r=="number"){if(qc[r]!=null)return qc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yn[r]!=null)return yn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var $A=j("ip4"),qA=j("ip6"),zA=j("ipcidr");function Wc(r,e){switch(j(r).code){case 4:case 41:return gy(e);case 42:return Yc(e);case 6:case 273:case 33:case 132:return Gh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Yc(e);case 421:return Ey(e);case 444:return zh(e);case 445:return zh(e);case 466:return by(e);case 481:return globalThis.encodeURIComponent(Yc(e));default:return F(e,"base16")}}function jc(r,e){switch(j(r).code){case 4:return qh(e);case 41:return qh(e);case 42:return Gc(e);case 6:case 273:case 33:case 132:return Xc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gc(e);case 421:return yy(e);case 444:return xy(e);case 445:return vy(e);case 466:return wy(e);case 481:return Gc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var zc=Object.values(zt).map(r=>r.decoder),my=function(){let r=zc[0].or(zc[1]);return zc.slice(2).forEach(e=>r=r.or(e)),r}();function qh(r){if(!js(r))throw new Error("invalid ip address");return $c(r)}function gy(r){let e=$h(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!js(e))throw new Error("invalid ip address");return e}function Xc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Gh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gc(r){let e=L(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function Yc(r){let e=lt(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function yy(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ae.decode(`z${r}`)).bytes:e=Qe.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function wy(r){let e=my.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function by(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function Ey(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function xy(r){let e=r.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 t=Ye.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 o=Xc(n);return Re([t,o],t.length+o.length)}function vy(r){let e=r.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 t=Ye.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 o=Xc(n);return Re([t,o],t.length+o.length)}function zh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Gh(t);return`${n}:${o}`}function Yh(r){r=Zc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=j(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw jh("invalid address: "+r);if(a.path===!0){n=Zc(o.slice(s).join("/")),e.push([a.code,jc(a.code,n)]),t.push([a.code,n]);break}let c=jc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Wc(a.code,c)])}return{string:Wh(t),bytes:Jc(e),tuples:e,stringTuples:t,path:n}}function Qc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=de(s),a=j(s),c=_y(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw jh("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=Wc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Wh(t),tuples:e,stringTuples:t,path:n}}function Wh(r){let e=[];return r.map(t=>{let n=j(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Zc(e.join("/"))}function Jc(r){return Re(r.map(e=>{let t=j(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function _y(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=lt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function Zc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function jh(r){return new Error("Error parsing address: "+r)}var Ay=Symbol.for("nodejs.util.inspect.custom"),el=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Sy=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Xs=class r{bytes;#e;#t;#s;#a;[el]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Qc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Yh(e)}else if(ar(e))t=Qc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=j("tcp"),a=j("udp"),c=j("ip4"),u=j("ip6"),f=j("dns6"),l=j("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),Sy.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=j(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=j(h).name,n=`${d??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},j(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>j(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Jc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===yn.p2p.code&&e.push([n,o]),n===yn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?F(ae.decode(`z${n}`),"base58btc"):F(Qe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return J(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=wn.get(t.name);if(n==null)throw new E(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>ne(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 t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Ay](){return`Multiaddr(${this.#e})`}};var wn=new Map;function ar(r){return!!r?.[el]}function ne(r){return new Xs(r)}var Xh="libp2p-peer-record",Zh=Uint8Array.from([3,1]);var uo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ve((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;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})),o),n.encode=s=>Fe(s,n.codec()),n.decode=s=>Me(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ve((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){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(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Fe(n,r.codec()),r.decode=n=>Me(n,r.codec())})(uo||(uo={}));var Nr=class r{static createFromProtobuf=e=>{let t=uo.decode(e),n=un(t.peerId),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xh;static CODEC=Zh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=uo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Mh(this.multiaddrs,e.multiaddrs))}};function Ry(r){return r[Symbol.asyncIterator]!=null}function Iy(r){if(Ry(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var fo=Iy;var rl=pr(Jh(),1);var po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},nl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ed=r=>globalThis.DOMException===void 0?new nl(r):new DOMException(r),td=r=>{let e=r.reason===void 0?ed("This operation was aborted."):r.reason;return e instanceof Error?e:ed(e)};function mo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(td(p)),p.addEventListener("abort",()=>{f(td(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new po;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function ol(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var go=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=ol(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var cr=class extends rl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:go,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${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 \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#_(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}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})`);this.#u=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=mo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof po&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var lr={},bn=r=>{r.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)})};bn.addEventListener=(r,e)=>{lr[r]==null&&(lr[r]=[]),lr[r].push(e)};bn.removeEventListener=(r,e)=>{lr[r]!=null&&(lr[r]=lr[r].filter(t=>t===e))};bn.dispatchEvent=function(r,e,t){lr[r]!=null&&lr[r].forEach(n=>n(e,t))};var sl=bn;var il="lock:worker:request-read",al="lock:worker:release-read",cl="lock:master:grant-read",ll="lock:worker:request-write",ul="lock:worker:release-write",fl="lock:master:grant-write";var rd=(r=21)=>Math.random().toString().substring(2);var nd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},od=(r,e,t,n)=>async()=>{let o=rd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},Cy={singleProcess:!1},sd=r=>{if(r=Object.assign({},Cy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return sl.addEventListener("message",nd(t,"requestReadLock",il,al,cl)),sl.addEventListener("message",nd(t,"requestWriteLock",ll,ul,fl)),t}return{isWorker:!0,readLock:t=>od(t,il,cl,al),writeLock:t=>od(t,ll,fl,ul)}};var Lr={},ur;async function hl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var ky=(r,e)=>{if(ur.isWorker===!0)return{readLock:ur.readLock(r,e),writeLock:ur.writeLock(r,e)};let t=new cr({concurrency:1}),n;return{async readLock(){if(n!=null)return hl(n,e);n=new cr({concurrency:e.concurrency,autoStart:!1});let o=n,s=hl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,hl(t,e)}}},Ny={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function dl(r){let e=Object.assign({},Ny,r);return ur==null&&(ur=sd(e),ur.isWorker!==!0&&(ur.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ur.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=ky(e.name,e)),Lr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var En;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Js.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=Js.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ve((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Qs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Qs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Fe(o,r.codec()),r.decode=o=>Me(o,r.codec())})(En||(En={}));var Qs;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Qs||(Qs={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Js||(Js={}));function xn(r,e){let t=En.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Rh({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ne(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",id=new TextEncoder().encode(Ft),ei=id[0],Dr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ei)throw new Error("Invalid key")}toString(e="utf8"){return F(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=id),this._buf[0]!==ei){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ei,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ei;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return Ly(this.baseNamespace())}name(){return Dy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(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 r.withNamespaces([...this.namespaces(),...Py(e.map(t=>t.namespaces()))])}};function Ly(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Dy(r){let e=r.split(":");return e[e.length-1]}function Py(r){return[].concat(...r)}var pl="/peers/";function vn(r){if(!Co(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${pl}${e}`)}async function ad(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ne(o.multiaddr)),!ar(o.multiaddr))throw new E("Multiaddr was invalid",Te.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function ri(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!J(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",Te.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new E("peer id did not match existing peer id",Te.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ti(l,{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ti(l,{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,h]of l)h==null?a.delete(p):a.set(p,h);a=ti([...a.entries()],{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[h,d]of l)d==null?p.delete(h):p.set(h,d);c=ti([...p.entries()],{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await ad(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,p)=>l.localeCompare(p)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function ti(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function cd(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Te.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Te.ERR_INVALID_PARAMETERS)}function ld(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Te.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Te.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Te.ERR_INVALID_PARAMETERS)}}function ud(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function ni(r,e,t){let n=r.toString().split("/")[2],o=Ye.decode(n),s=un(o),i=t.get(s);if(i!=null)return i;let a=xn(s,e);return t.set(s,a),a}function Oy(r,e){return r==null?{}:{prefix:pl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ni(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ni(n.key,n.value,e),ni(o.key,o.value,e)))}}var oi=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=dl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(vn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(vn(e))}async load(e){let t=await this.datastore.get(vn(e));return xn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(Oy(e??{},t))){let s=ni(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(vn(e)),n=xn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=En.encode(t);return n!=null&&J(s,n)?{peer:xn(e,s),previous:o,updated:!1}:(await this.datastore.put(vn(e),s),{peer:xn(e,s),previous:o,updated:!0})}};var si=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new oi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await fo(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await dn.openAndCertify(e,Nr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Nr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await dn.createFromProtobuf(s.peerRecordEnvelope),a=Nr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Uy(r){return r[Symbol.asyncIterator]!=null}function My(r){if(Uy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ml=My;function Fy(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var fd=Fy;function Vy(r){return r[Symbol.asyncIterator]!=null}function Ky(r,e){let t=0;if(Vy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=fd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Pr=Ky;function Hy(r){return r[Symbol.asyncIterator]!=null}function $y(r,e){return Hy(r)?async function*(){yield*(await fo(r)).sort(e)}():function*(){yield*fo(r).sort(e)}()}var gl=$y;function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r,e){return qy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var yl=zy;var ii=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await ml(this.putMany(e,n)),e=[],await ml(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=yl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=yl(n,e.limit)),n}};var md=pr(pd(),1);function gd(r){return r=r??new Error("Not Found"),(0,md.default)(r,"ERR_NOT_FOUND")}var ai=class extends ii{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw gd();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Dr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Dr(e)}};function yd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Wy=r=>r;function wl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var ci=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Wy,this._updatePeerStoreAddresses=yd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>ne(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}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=wl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=wl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=wl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}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,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).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()}`))}};var bl=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=$s())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>fu(t)).map(async t=>{await t[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")}},jy=["metrics","connectionProtector","dns"],Xy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function wd(r={}){let e=new bl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Xy.includes(o)){let i=e.components[o];if(i==null&&!jy.includes(o))throw new E(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function bd(r){let e={};for(let t of Object.values(r.components))for(let n of Zy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Qy(t))if(e[n]!==!0)throw new E(`Service "${Jy(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function Zy(r){return Array.isArray(r?.[kn])?r[kn]:[]}function Qy(r){return Array.isArray(r?.[ua])?r[ua]:[]}function Jy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var xd=pr(Ed(),1),ew=["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"],tw=ew.map(r=>new xd.Netmask(r));function El(r){for(let e of tw)if(e.contains(r))return!0;return!1}function rw(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function nw(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return El(o)}function ow(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function sw(r){let e=r.split(":"),t=e[e.length-1];return El(t)}function iw(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function li(r){return mn(r)?El(r):rw(r)?nw(r):ow(r)?sw(r):gn(r)?iw(r):void 0}function vd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!li(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var aw=r=>r.toString().split("/").slice(1),wo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>wo(t=>t===r).match(e),pattern:r}),hi=()=>({match:r=>wo(e=>typeof e=="string").match(r),pattern:"{string}"}),di=()=>({match:r=>wo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Be=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ae.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ui=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ia.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),rt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=aw(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var vl=Z(Y("dns4"),hi()),_l=Z(Y("dns6"),hi()),Al=Z(Y("dnsaddr"),hi()),_d=Z(Y("dns"),hi()),gR=fe(vl),yR=fe(_l),wR=fe(Al),bR=fe(rt(_d,Al,vl,_l)),Ad=Z(Y("ip4"),wo(mn)),Sd=Z(Y("ip6"),wo(gn)),Rd=rt(Ad,Sd),vt=rt(Rd,_d,vl,_l,Al),ER=fe(vt),xR=fe(Ad),vR=fe(Sd),_R=fe(Rd),Sl=Z(vt,Y("tcp"),di()),bo=Z(vt,Y("udp"),di()),AR=fe(Sl),SR=fe(bo),Rl=Z(bo,Y("quic")),pi=Z(bo,Y("quic-v1")),cw=rt(Rl,pi),RR=fe(Rl),IR=fe(pi),xl=rt(vt,Sl,bo,Rl,pi),Id=rt(Z(xl,Y("ws"),be(Be()))),TR=fe(Id),Td=rt(Z(xl,Y("wss"),be(Be())),Z(xl,Y("tls"),Y("ws"),be(Be()))),BR=fe(Td),Bd=Z(bo,Y("webrtc-direct"),be(ui()),be(ui()),be(Be())),CR=fe(Bd),Cd=Z(pi,Y("webtransport"),be(ui()),be(ui()),be(Be())),kR=fe(Cd),fi=rt(Id,Td,Z(Sl,be(Be())),Z(cw,be(Be())),Z(vt,be(Be())),Bd,Cd,Be()),NR=fe(fi),lw=Z(fi,Y("p2p-circuit"),Be()),Eo=fe(lw),uw=rt(Z(fi,Y("p2p-circuit"),Y("webrtc"),be(Be())),Z(fi,Y("webrtc"),be(Be())),Y("webrtc")),LR=fe(uw),fw=rt(Z(vt,Y("tcp"),di(),Y("http"),be(Be())),Z(vt,Y("http"),be(Be()))),DR=fe(fw),hw=rt(Z(vt,Y("tcp"),rt(Z(Y("443"),Y("http")),Z(di(),Y("https"))),be(Be())),Z(vt,Y("tls"),Y("http"),be(Be())),Z(vt,Y("https"),be(Be()))),PR=fe(hw);function Il(r){try{let{address:e}=r.nodeAddress();return!!li(e)}catch{return!0}}function dw(r,e){let t=Il(r.multiaddr),n=Il(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function pw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function mw(r,e){let t=Eo.exactMatch(r.multiaddr),n=Eo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _n(r,e){let t=dw(r,e);if(t!==0)return t;let n=mw(r,e);return n!==0?n:pw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function mi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Tl=60;function gi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??Tl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var gw=4;function Bl(r,e={}){let t=new cr({concurrency:e.queryConcurrency??gw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mi(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gi(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function kd(){return[Bl("https://cloudflare-dns.com/dns-query"),Bl("https://dns.google/resolve")]}var Dd=pr(Ld(),1);var Cl=class{lru;constructor(e){this.lru=(0,Dd.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Tl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Pd(r){return new Cl(r)}var yw=1e3,yi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Pd(e.cacheSize??yw),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=kd())}async query(e,t={}){let n=mi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function Od(r={}){return new yi(r)}var ww=32,{code:bw}=j("dnsaddr"),Or=async function(e,t={}){let n=t.maxRecursiveDepth??ww;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===bw)??[],i=await(t?.dns??Od()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ne(f);if(f.startsWith("/dnsaddr")){let p=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...p.map(h=>h.toString()))}else c.push(l.toString())}return c};var zd=pr(qd(),1),Ei=zd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var k;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(k||(k={}));var Sw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Or},addressSorter:_n},transportManager:{faultTolerance:Ht.FATAL_ALL}};async function Gd(r){let e=Ei(Sw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,k.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await fn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",k.ERR_INVALID_KEY);return e}var Yd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rw=new WeakMap;function Iw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Yd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Yd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((p,h)=>{i=()=>{f(),p(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Rw.set(l,()=>{c(s),s=null,i()}),l}}var Tw=Iw(),Wd=Tw;var xi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Nl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new E("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Wd(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&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)}},Nl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function vi(r){if(Co(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!ar(n))throw new E("Invalid Multiaddr",k.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e?.equals(s)!==!0)throw new E("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _i=class{buffer;mask;top;btm;next;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}},Rn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new _i(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 t=this.head;this.head=t.next=new _i(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ll=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ai(r={}){return Bw(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Bw(r,e){e=e??{};let t=e.onEnd,n=new Rn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=y=>{s=null,n.push(y);try{w(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new Rn,s!=null?s({error:w}):(n.push({error:w}),o)),l=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},p=w=>i?o:(i=!0,w!=null?f(w):u({done:!0})),h=()=>(n=new Rn,p(),{done:!0}),d=w=>(p(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:d,push:l,end:p,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let y,b;g!=null&&(y=new Promise((x,A)=>{b=()=>{A(new Ll)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,y])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var Dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function In(r,e,t,n){let o=new Dl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(p){a(),i(p);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Si=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function fr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Si(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Si(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ri=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Cw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Cw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ie(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new $t),this.cleanup())}async join(e={}){let t=new Ri(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await fr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Tn=class extends At{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new Ii(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new $t)}),this.clear()}async onEmpty(e){this.size!==0&&await In(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await In(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await In(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ai({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new E("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ti=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Bi="last-dial-failure";var Ci=5,ki=100,Ni=50,Li=1e3*60*7;var Ur={minConnections:Ci,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Di=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Ur.minConnections,this.autoDialPriority=t.autoDialPriority??Ur.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Ur.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Ur.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Ur.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ur.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ti({concurrency:t.autoDialConcurrency??Ur.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Mt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,p=i.get(f.id)??0;return l>p?-1:l<p?1:0}).filter(u=>{let f=u.metadata.get(Bi);if(f==null)return!0;let l=parseInt(F(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Nw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Nw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Xd={maxConnections:ki,allow:[]},Pi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Xd.maxConnections,this.allow=t.allow??Xd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Xe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await jd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Oi=class extends Tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Mr(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function Zd(r,e){let t=!1;for(let o of wn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var xo={addressSorter:_n,maxParallelDials:Ni,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Or}},Ui=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??xo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??xo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??xo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??xo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))wn.set(n,o);this.queue=new Oi({concurrency:t.maxParallelDials??xo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=vi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new E("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let p of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new E("Peer had more than maxPeerAddrsToDial",k.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(p.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",p.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",p.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Bi]:L(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new E(h.message,No);l.push(h)}}throw l.length===1?l[0]:new ko(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Hl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Mr([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ie(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:ne(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new E("Tried to dial self",k.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",k.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:p})=>p.toString()))}catch(l){if(l.code!==k.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:p})=>p.toString())),o.push(...l.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(l){l.code!==k.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let p=await Zd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return p.length===1&&p[0].equals(l.multiaddr)?l:p.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(p=>p.multiaddr.protos().pop()?.path===!0?p:p.multiaddr.getPeerId()==null?{multiaddr:p.multiaddr.encapsulate(l),isCertified:p.isCertified}:p)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let p=l.multiaddr.getPeerId();return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let l of i){let p=l.multiaddr.toString(),h=a.get(p);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(p,l)}let c=[...a.values()];if(c.length===0)throw new E("The dial request has no valid addresses",k.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new E("The connection gater denied all addresses in the dial request",k.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!Eo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Hl=50,Kt={minConnections:Ci,maxConnections:ki,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Mi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kt.maxConnections;let n=t.minConnections??Kt.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",k.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),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=(t.allow??[]).map(o=>ne(o)),this.deny=(t.deny??[]).map(o=>ne(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new xi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Di({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Kt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Kt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Kt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Kt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Kt.autoDialMaxQueueLength}),this.connectionPruner=new Pi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ui(e,{addressSorter:t.addressSorter??_n,maxParallelDials:t.maxParallelDials??Ni,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Or},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(uu)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new E("Not started",k.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=vi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),t.onProgress?.(new he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Hl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>ne(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Bn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Pw=1.2,Ow=2,Uw=2e3,Fi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Bn(e.interval??5e3),this.failure=new Bn(e.interval??5e3),this.next=new Bn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Ow,this.timeoutMultiplier=e.timeoutMultiplier??Pw,this.minTimeout=e.minTimeout??Uw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Mr([e.signal,n]);return ie(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var $l=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await fr(this.readNext.promise,t?.signal,t)}};function Qd(){return new $l}var Vi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ql=class extends Error{code;constructor(e,t){super(e),this.code=t}},zl=class extends ql{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ki(r,e){let t=Qd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new zl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:p}=await Promise.race([n.next(),u]);return l===!0?new we:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Vi("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Mw=1e4,Fw="1.0.0",Vw="ping",Kw="ipfs",Jd=32,Hi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Kw}/${Vw}/${Fw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Mw,this.timeout=new Fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[kn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=Ki(o);t=Date.now(),await Promise.all([s.write(et(Jd),{signal:n}),s.read(Jd,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Hw(r){return r[Symbol.asyncIterator]!=null}function $w(...r){let e=[];for(let t of r)Hw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ai({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var vo=$w;var $i=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new E("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Mt;for await(let s of vo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var qi=globalThis.CustomEvent??Event;async function*Gl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ue(),a=ue(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=ue(),await i.promise),f)break;let m={done:!1};s.push(m),d().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new qi("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new qi("task-complete"))})}c=!0,o.dispatchEvent(new qi("task-complete"))}catch(d){u=d,o.dispatchEvent(new qi("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*p(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*h(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let m=s[d];if(s.splice(d,1),d--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=ue(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var zi=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",k.ERR_FIND_SELF);let n=this,o=vo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Vt.NOT_FOUND,k.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Vc(1024);for await(let s of Gl(async function*(){let i=vo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var Gi=class extends At{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Mr([this.shutdownController.signal,e?.signal]);ie(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await In(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ie(1/0,this.walkController.signal);let e=Mr([this.walkController.signal,this.shutdownController.signal]);ie(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=et(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await fr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Yl=32,Wl=64,Yi=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new E(`No handler registered for protocol ${e}`,k.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,k.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Ei.bind({ignoreUndefined:!0})({maxInboundStreams:Yl,maxOutboundStreams:Wl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new E("invalid topology",k.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==k.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var jl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new jl({name:e,metrics:t}):n=new Map,n}var Wi=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=ep({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ht.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new E("Transport must have a valid tag",k.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,k.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}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[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,k.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new he("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=k.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new E("Not started",k.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let p=l.findIndex(h=>h===f);l.splice(p,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ht.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,k.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ht.FATAL_ALL)throw new E(n,k.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ce="/multistream/1.0.0";var ji=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Xi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function _o(r,e={}){let t=Ki(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new ji("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Zi("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Xi("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var qw=L(`
8
- `);async function Fr(r,e,t){await r.write(e,t)}async function tp(r,e,t){await r.writeV(e,t)}async function zw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==qw[0])throw e.log.error("Invalid mss message - missing newline",t),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function hr(r,e){let t=await zw(r,e);return F(t.subarray())}async function Ao(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Gw(r,e[0],t);let n=_o(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Ce,o);let s=L(`${Ce}
6
+ `)}`:`${t} :`}};Af=or;C.Constructed=Af;or.NAME="CONSTRUCTED";var cs=class extends Oe{fromBER(e,t,n){return t}toBER(e){return ht}};cs.override="EndOfContentValueBlock";var Sf,ls=class extends Te{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Sf=ls;C.EndOfContent=Sf;ls.NAME=Xn;var Rf,sr=class extends Te{constructor(e={}){super(e,Oe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Rf=sr;C.Null=Rf;sr.NAME="NULL";var us=class extends Mt(Oe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=z.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);return Ut(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ec.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};us.NAME="BooleanValueBlock";var If,fs=class extends Te{constructor(e={}){super(e,us),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};If=fs;C.Boolean=If;fs.NAME="BOOLEAN";var hs=class extends Mt(bt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Ef)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?bt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};hs.NAME="OctetStringValueBlock";var Tf,Pt=class r extends Te{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},hs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Vs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?or.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return z.BufferSourceConverter.concat(e)}};Tf=Pt;C.OctetString=Tf;Pt.NAME=Ef;var ds=class extends Mt(bt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==xf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Vs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return bt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ht;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};ds.NAME="BitStringValueBlock";var Bf,ln=class extends Te{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return or.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Bf=ln;C.BitString=Bf;ln.NAME=xf;var Cf;function l0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=ts(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=ts(t,s)),s}function bf(r){if(r>=jn.length)for(let e=jn.length;e<=r;e++){let t=new Uint8Array([0]),n=jn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=ts(t,n)),jn.push(n)}return jn[r]}function u0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Zn=class extends Mt(Oe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ec.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=u0(bf(n),t),i="-";break;default:t=l0(t,bf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=wf.charAt(t[c]));return a===!1&&(i+=wf.charAt(0)),i}};Cf=Zn;Zn.NAME="IntegerValueBlock";Object.defineProperty(Cf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var kf,pe=class r extends Te{constructor(e={}){super(e,Zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return rs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){rs();let t=BigInt(e),n=new Wn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${z.Convert.ToHex(a)}`)+t,f=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};kf=pe;C.Integer=kf;pe.NAME="INTEGER";var Nf,ps=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Nf=ps;C.Enumerated=Nf;ps.NAME="ENUMERATED";var Qn=class extends Mt(Oe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){rs();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=nr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=z.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Qn.NAME="sidBlock";var ms=class extends Oe{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Qn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ht;t.push(o)}return xc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Qn;if(o>Number.MAX_SAFE_INTEGER){rs();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ms.NAME="ObjectIdentifierValueBlock";var Lf,ft=class extends Te{constructor(e={}){super(e,ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Lf=ft;C.ObjectIdentifier=Lf;ft.NAME="OBJECT IDENTIFIER";var Jn=class extends Mt(Dt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=nr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=z.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Jn.NAME="relativeSidBlock";var gs=class extends Oe{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ht;n.push(s)}return xc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};gs.NAME="RelativeObjectIdentifierValueBlock";var Df,ys=class extends Te{constructor(e={}){super(e,gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Df=ys;C.RelativeObjectIdentifier=Df;ys.NAME="RelativeObjectIdentifier";var Pf,_e=class extends or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Pf=_e;C.Sequence=Pf;_e.NAME="SEQUENCE";var Of,ws=class extends or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Of=ws;C.Set=Of;ws.NAME="SET";var bs=class extends Mt(Oe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=un}toJSON(){return{...super.toJSON(),value:this.value}}};bs.NAME="StringValueBlock";var Es=class extends bs{};Es.NAME="SimpleStringValueBlock";var $e=class extends ss{constructor({...e}={}){super(e,Es)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};$e.NAME="SIMPLE STRING";var xs=class extends $e{fromBuffer(e){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=z.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(e)),this.valueBlock.value=e}};xs.NAME="Utf8StringValueBlock";var Uf,Ot=class extends xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Uf=Ot;C.Utf8String=Uf;Ot.NAME="UTF8String";var vs=class extends $e{fromBuffer(e){this.valueBlock.value=z.Convert.ToUtf16String(e),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(e))}};vs.NAME="BmpStringValueBlock";var Mf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Mf=_s;C.BmpString=Mf;_s.NAME="BMPString";var As=class extends $e{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=nr(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};As.NAME="UniversalStringValueBlock";var Ff,Ss=class extends As{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Ff=Ss;C.UniversalString=Ff;Ss.NAME="UniversalString";var Vf,Rs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Vf=Rs;C.NumericString=Vf;Rs.NAME="NumericString";var Kf,Is=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Kf=Is;C.PrintableString=Kf;Is.NAME="PrintableString";var Hf,Ts=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Hf=Ts;C.TeletexString=Hf;Ts.NAME="TeletexString";var $f,Bs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};$f=Bs;C.VideotexString=$f;Bs.NAME="VideotexString";var qf,Cs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};qf=Cs;C.IA5String=qf;Cs.NAME="IA5String";var zf,ks=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};zf=ks;C.GraphicString=zf;ks.NAME="GraphicString";var Gf,eo=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gf=eo;C.VisibleString=Gf;eo.NAME="VisibleString";var Yf,Ns=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Yf=Ns;C.GeneralString=Yf;Ns.NAME="GeneralString";var jf,Ls=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};jf=Ls;C.CharacterString=jf;Ls.NAME="CharacterString";var Wf,to=class extends eo{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=je(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=je(this.month,2),t[2]=je(this.day,2),t[3]=je(this.hour,2),t[4]=je(this.minute,2),t[5]=je(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Wf=to;C.UTCTime=Wf;to.NAME="UTCTime";var Xf,Ds=class extends to{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(je(this.year,4)),t.push(je(this.month,2)),t.push(je(this.day,2)),t.push(je(this.hour,2)),t.push(je(this.minute,2)),t.push(je(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(je(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Xf=Ds;C.GeneralizedTime=Xf;Ds.NAME="GeneralizedTime";var Zf,Ps=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Zf=Ps;C.DATE=Zf;Ps.NAME="DATE";var Qf,Os=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Qf=Os;C.TimeOfDay=Qf;Os.NAME="TimeOfDay";var Jf,Us=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Jf=Us;C.DateTime=Jf;Us.NAME="DateTime";var eh,Ms=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};eh=Ms;C.Duration=eh;Ms.NAME="Duration";var th,Fs=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};th=Fs;C.TIME=th;Fs.NAME="TIME";function h0(r){let{result:e}=fn(r),t=e.valueBlock.value;return{n:V(Et(t[1].toBigInt()),"base64url"),e:V(Et(t[2].toBigInt()),"base64url"),d:V(Et(t[3].toBigInt()),"base64url"),p:V(Et(t[4].toBigInt()),"base64url"),q:V(Et(t[5].toBigInt()),"base64url"),dp:V(Et(t[6].toBigInt()),"base64url"),dq:V(Et(t[7].toBigInt()),"base64url"),qi:V(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function d0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new x("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new pe({value:0}),pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url"))),pe.fromBigInt(xt(L(r.d,"base64url"))),pe.fromBigInt(xt(L(r.p,"base64url"))),pe.fromBigInt(xt(L(r.q,"base64url"))),pe.fromBigInt(xt(L(r.dp,"base64url"))),pe.fromBigInt(xt(L(r.dq,"base64url"))),pe.fromBigInt(xt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function p0(r){let{result:e}=fn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:V(Et(t[0].toBigInt()),"base64url"),e:V(Et(t[1].toBigInt()),"base64url")}}function m0(r){if(r.n==null||r.e==null)throw new x("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new sr]}),new ln({valueHex:new _e({value:[pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Et(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function xt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var g0=16,_c=32,Ac=1e4;async function y0(r,e){let t=Fe.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new sr]}),new Pt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=rt(g0),a=await wc(Vn,e,i,{c:Ac,dkLen:_c}),c=rt(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new _e({value:[new Pt({valueHex:i}),new pe({value:Ac}),new pe({value:_c}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new sr]})]}),d=new _e({value:[new ft({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new ft({value:"2.16.840.1.101.3.4.1.42"}),new Pt({valueHex:c})]})]})]}),p=new _e({value:[d,new Pt({valueHex:f})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...V(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
+ `)}async function w0(r,e){let t=Fe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=fn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=b0(s),l=await wc(Vn,e,a,{c,dkLen:u}),d=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=ro(await t.subtle.decrypt({name:"AES-CBC",iv:i},d,f)),{result:p}=fn(h);n=rh(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=fn(o);n=rh(s)}else throw new x("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Sc(n)}function b0(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new x("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new x("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=ro(s.valueBlock.value[0].getValue()),a=Ac,c=_c;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new x("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new x("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=ro(u.valueBlock.value[1].getValue());return{cipherText:ro(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function rh(r){return ro(r.valueBlock.value[2].getValue())}function ro(r){return new Uint8Array(r,0,r.byteLength)}async function nh(r){let e=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await ih(e);return{privateKey:t[0],publicKey:t[1]}}async function Rc(r){let t=[await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await E0(r)],n=await ih({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function oh(r,e){let t=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function sh(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function ih(r){if(r.privateKey==null||r.publicKey==null)throw new x("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)])}async function E0(r){return Fe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ks(r){if(r.kty!=="RSA")throw new x("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new x("invalid key modulus","ERR_INVALID_KEY_MODULUS");return L(r.n,"base64url").length*8}var oo=8192,no=class{_key;constructor(e){this._key=e}verify(e,t){return sh(this._key,t,e)}marshal(){return ir.jwkToPkix(this._key)}get bytes(){return yt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}},hn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return rt(16)}sign(e){return oh(this._key,e)}get public(){if(this._publicKey==null)throw new x("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new no(this._publicKey)}marshal(){return ir.jwkToPkcs1(this._key)}get bytes(){return wt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return ir.exportToPem(this,e);if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Sc(r){let e=ir.pkcs1ToJwk(r);if(Ks(e)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Rc(e);return new hn(t.privateKey,t.publicKey)}function v0(r){let e=ir.pkixToJwk(r);if(Ks(e)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new no(e)}async function _0(r){if(Ks(r)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Rc(r);return new hn(e.privateKey,e.publicKey)}async function A0(r){if(r>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await nh(r);return new hn(e.privateKey,e.publicKey)}var Nc={};ve(Nc,{Secp256k1PrivateKey:()=>io,Secp256k1PublicKey:()=>so,generateKeyPair:()=>U0,unmarshalSecp256k1PrivateKey:()=>P0,unmarshalSecp256k1PublicKey:()=>O0});var S0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ar=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cr=new Uint32Array(64),Tc=class extends en{constructor(){super(64,32,8,!1),this.A=ar[0]|0,this.B=ar[1]|0,this.C=ar[2]|0,this.D=ar[3]|0,this.E=ar[4]|0,this.F=ar[5]|0,this.G=ar[6]|0,this.H=ar[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)cr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=cr[l-15],h=cr[l-2],p=it(d,7)^it(d,18)^d>>>3,m=it(h,17)^it(h,19)^h>>>10;cr[l]=m+cr[l-7]+p+cr[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=it(a,6)^it(a,11)^it(a,25),h=f+d+Fu(a,c,u)+S0[l]+cr[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Vu(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ah=Fo(()=>new Tc);function ch(r){r.lowS!==void 0&&at("lowS",r.lowS),r.prehash!==void 0&&at("prehash",r.prehash)}function R0(r){let e=$n(r);gt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:I0,hexToBytes:T0}=Ho,Ft={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Ft;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Er(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Er(o.length/2|128):"";return`${Er(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Ft,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ft;if(r<Vt)throw new e("integer: negative integers are not allowed");let t=Er(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Ft;if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return I0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ft,o=typeof r=="string"?T0(r):r;tn(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Ft,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Vt=BigInt(0),Ae=BigInt(1),Z1=BigInt(2),lh=BigInt(3),Q1=BigInt(4);function B0(r){let e=R0(r),{Fp:t}=e,n=tr(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return kt(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Kn(m,Ae,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(Qt(m)&&(m=Bt(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let E;try{E=typeof m=="bigint"?m:Ct(le("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(E=Z(E,w)),Ge("private key",E,Ae,w),E}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=_r((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let E=m.is0();g==null&&(g=E?t.ONE:t.inv(w));let A=t.mul(y,g),R=t.mul(b,g),v=t.mul(w,g);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:R}}),l=_r(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=E=>t.eql(E,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(le("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return zo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:E,py:A,pz:R}=g,v=t.eql(t.mul(y,R),t.mul(E,w)),I=t.eql(t.mul(b,R),t.mul(A,w));return v&&I}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,lh),{px:w,py:E,pz:A}=this,R=t.ZERO,v=t.ZERO,I=t.ZERO,N=t.mul(w,w),ee=t.mul(E,E),H=t.mul(A,A),K=t.mul(w,E);return K=t.add(K,K),I=t.mul(w,A),I=t.add(I,I),R=t.mul(g,I),v=t.mul(b,H),v=t.add(R,v),R=t.sub(ee,v),v=t.add(ee,v),v=t.mul(R,v),R=t.mul(K,R),I=t.mul(b,I),H=t.mul(g,H),K=t.sub(N,H),K=t.mul(g,K),K=t.add(K,I),I=t.add(N,N),N=t.add(I,N),N=t.add(N,H),N=t.mul(N,K),v=t.add(v,N),H=t.mul(E,A),H=t.add(H,H),N=t.mul(H,K),R=t.sub(R,N),I=t.mul(H,ee),I=t.add(I,I),I=t.add(I,I),new d(R,v,I)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:E,py:A,pz:R}=g,v=t.ZERO,I=t.ZERO,N=t.ZERO,ee=e.a,H=t.mul(e.b,lh),K=t.mul(y,E),O=t.mul(b,A),B=t.mul(w,R),D=t.add(y,b),S=t.add(E,A);D=t.mul(D,S),S=t.add(K,O),D=t.sub(D,S),S=t.add(y,w);let _=t.add(E,R);return S=t.mul(S,_),_=t.add(K,B),S=t.sub(S,_),_=t.add(b,w),v=t.add(A,R),_=t.mul(_,v),v=t.add(O,B),_=t.sub(_,v),N=t.mul(ee,S),v=t.mul(H,B),N=t.add(v,N),v=t.sub(O,N),N=t.add(O,N),I=t.mul(v,N),O=t.add(K,K),O=t.add(O,K),B=t.mul(ee,B),S=t.mul(H,S),O=t.add(O,B),B=t.sub(K,B),B=t.mul(ee,B),S=t.add(S,B),K=t.mul(O,S),I=t.add(I,K),K=t.mul(_,S),v=t.mul(D,v),v=t.sub(v,K),K=t.mul(D,O),N=t.mul(_,N),N=t.add(N,K),new d(v,I,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){Ge("scalar",g,Vt,e.n);let y=d.ZERO;if(g===Vt)return y;if(g===Ae)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:E,k2neg:A,k2:R}=b.splitScalar(g),v=y,I=y,N=this;for(;E>Vt||R>Vt;)E&Ae&&(v=v.add(N)),R&Ae&&(I=I.add(N)),N=N.double(),E>>=Ae,R>>=Ae;return w&&(v=v.negate()),A&&(I=I.negate()),I=new d(t.mul(I.px,b.beta),I.py,I.pz),v.add(I)}multiply(g){let{endo:y,n:b}=e;Ge("scalar",g,Ae,b);let w,E;if(y){let{k1neg:A,k1:R,k2neg:v,k2:I}=y.splitScalar(g),{p:N,f:ee}=this.wNAF(R),{p:H,f:K}=this.wNAF(I);N=p.constTimeNegate(A,N),H=p.constTimeNegate(v,H),H=new d(t.mul(H.px,y.beta),H.py,H.pz),w=N.add(H),E=ee.add(K)}else{let{p:A,f:R}=this.wNAF(g);w=A,E=R}return d.normalizeZ([w,E])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,E=(R,v)=>v===Vt||v===Ae||!R.equals(w)?R.multiplyUnsafe(v):R.multiply(v),A=E(this,y).add(E(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===Ae)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===Ae?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return at("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return at("isCompressed",g),Bt(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=qo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function C0(r){let e=$n(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function uh(r){let e=C0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(B){return Z(B,n)}function a(B){return $o(B,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=B0({...e,toBytes(B,D,S){let _=D.toAffine(),T=t.toBytes(_.x),P=kt;return at("isCompressed",S),S?P(Uint8Array.from([D.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,t.toBytes(_.y))},fromBytes(B){let D=B.length,S=B[0],_=B.subarray(1);if(D===o&&(S===2||S===3)){let T=Ct(_);if(!Kn(T,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(T),U;try{U=t.sqrt(P)}catch(G){let q=G instanceof Error?": "+G.message:"";throw new Error("Point is not on curve"+q)}let M=(U&Ae)===Ae;return(S&1)===1!==M&&(U=t.neg(U)),{x:T,y:U}}else if(D===s&&S===4){let T=t.fromBytes(_.subarray(0,t.BYTES)),P=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:T,y:P}}else throw new Error(`Point of length ${D} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=B=>Bt(er(B,e.nByteLength));function h(B){let D=n>>Ae;return B>D}function p(B){return h(B)?i(-B):B}let m=(B,D,S)=>Ct(B.slice(D,S));class g{constructor(D,S,_){this.r=D,this.s=S,this.recovery=_,this.assertValidity()}static fromCompact(D){let S=e.nByteLength;return D=le("compactSignature",D,S*2),new g(m(D,0,S),m(D,S,2*S))}static fromDER(D){let{r:S,s:_}=Ft.toSig(le("DER",D));return new g(S,_)}assertValidity(){Ge("r",this.r,Ae,n),Ge("s",this.s,Ae,n)}addRecoveryBit(D){return new g(this.r,this.s,D)}recoverPublicKey(D){let{r:S,s:_,recovery:T}=this,P=R(le("msgHash",D));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");let U=T===2||T===3?S+e.n:S;if(U>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=T&1?"03":"02",$=c.fromHex(M+d(U)),G=a(U),q=i(-P*G),X=i(_*G),J=c.BASE.multiplyAndAddUnsafe($,q,X);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return xr(this.toDERHex())}toDERHex(){return Ft.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return xr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(B){try{return u(B),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let B=Ya(e.n);return ju(e.randomBytes(B),e.n)},precompute(B=8,D=c.BASE){return D._setWindowSize(B),D.multiply(BigInt(3)),D}};function b(B,D=!0){return c.fromPrivateKey(B).toRawBytes(D)}function w(B){let D=Qt(B),S=typeof B=="string",_=(D||S)&&B.length;return D?_===o||_===s:S?_===2*o||_===2*s:B instanceof c}function E(B,D,S=!0){if(w(B))throw new Error("first arg must be private key");if(!w(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(u(B)).toRawBytes(S)}let A=e.bits2int||function(B){let D=Ct(B),S=B.length*8-e.nBitLength;return S>0?D>>BigInt(S):D},R=e.bits2int_modN||function(B){return i(A(B))},v=Hn(e.nBitLength);function I(B){return Ge(`num < 2^${e.nBitLength}`,B,Vt,v),er(B,e.nByteLength)}function N(B,D,S=ee){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:T}=e,{lowS:P,prehash:U,extraEntropy:M}=S;P==null&&(P=!0),B=le("msgHash",B),ch(S),U&&(B=le("prehashed msgHash",_(B)));let $=R(B),G=u(D),q=[I(G),I($)];if(M!=null&&M!==!1){let xe=M===!0?T(t.BYTES):M;q.push(le("extraEntropy",xe))}let X=kt(...q),J=$;function Ee(xe){let Se=A(xe);if(!l(Se))return;let Me=a(Se),me=c.BASE.multiply(Se).toAffine(),ze=i(me.x);if(ze===Vt)return;let _t=i(Me*i(J+ze*G));if(_t===Vt)return;let Ln=(me.x===ze?0:2)|Number(me.y&Ae),Dn=_t;return P&&h(_t)&&(Dn=p(_t),Ln^=1),new g(ze,Dn,Ln)}return{seed:X,k2sig:Ee}}let ee={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function K(B,D,S=ee){let{seed:_,k2sig:T}=N(B,D,S),P=e;return $a(P.hash.outputLen,P.nByteLength,P.hmac)(_,T)}c.BASE._setWindowSize(8);function O(B,D,S,_=H){let T=B;if(D=le("msgHash",D),S=le("publicKey",S),"strict"in _)throw new Error("options.strict was renamed to lowS");ch(_);let{lowS:P,prehash:U}=_,M,$;try{if(typeof T=="string"||Qt(T))try{M=g.fromDER(T)}catch(me){if(!(me instanceof Ft.Err))throw me;M=g.fromCompact(T)}else if(typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint"){let{r:me,s:ze}=T;M=new g(me,ze)}else throw new Error("PARSE");$=c.fromHex(S)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&M.hasHighS())return!1;U&&(D=e.hash(D));let{r:G,s:q}=M,X=R(D),J=a(q),Ee=i(X*J),xe=i(G*J),Se=c.BASE.multiplyAndAddUnsafe($,Ee,xe)?.toAffine();return Se?i(Se.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:E,sign:K,verify:O,ProjectivePoint:c,Signature:g,utils:y}}function k0(r){return{hash:r,hmac:(e,...t)=>Yn(r,e,Pa(...t)),randomBytes:Jr}}function fh(r,e){let t=n=>uh({...r,...k0(n)});return Object.freeze({...t(e),create:t})}var ph=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),hh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),N0=BigInt(1),Bc=BigInt(2),dh=(r,e)=>(r+e/Bc)/e;function L0(r){let e=ph,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ne(f,t,e)*f%e,d=ne(l,t,e)*f%e,h=ne(d,Bc,e)*u%e,p=ne(h,o,e)*h%e,m=ne(p,s,e)*p%e,g=ne(m,a,e)*m%e,y=ne(g,c,e)*g%e,b=ne(y,a,e)*m%e,w=ne(b,t,e)*f%e,E=ne(w,i,e)*p%e,A=ne(E,n,e)*u%e,R=ne(A,Bc,e);if(!Cc.eql(Cc.sqr(R),r))throw new Error("Cannot find square root");return R}var Cc=tr(ph,void 0,void 0,{sqrt:L0}),dt=fh({a:BigInt(0),b:BigInt(7),Fp:Cc,n:hh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=hh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-N0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=dh(s*r,e),c=dh(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},ah),av=BigInt(0);var cv=dt.ProjectivePoint;function mh(){return dt.utils.randomPrivateKey()}function gh(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(tt(t))return t.then(({digest:n})=>dt.sign(n,r).toDERRawBytes()).catch(n=>{throw new x(String(n),"ERR_INVALID_INPUT")});try{return dt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new x(String(n),"ERR_INVALID_INPUT")}}function yh(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(tt(n))return n.then(({digest:o})=>dt.verify(e,o,r)).catch(o=>{throw new x(String(o),"ERR_INVALID_INPUT")});try{return dt.verify(e,n.digest,r)}catch(o){throw new x(String(o),"ERR_INVALID_INPUT")}}function wh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function bh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new x(String(e),"ERR_INVALID_PRIVATE_KEY")}}function kc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new x(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Eh(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new x(String(e),"ERR_INVALID_PRIVATE_KEY")}}var so=class{_key;constructor(e){kc(e),this._key=e}verify(e,t){return yh(this._key,t,e)}marshal(){return wh(this._key)}get bytes(){return yt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return tt(e)?{bytes:t}=await e:t=e.bytes,t}},io=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Eh(e),bh(this._key),kc(this._publicKey)}sign(e){return gh(this._key,e)}get public(){return new so(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function P0(r){return new io(r)}function O0(r){return new so(r)}async function U0(){let r=mh();return new io(r)}var lr={rsa:Ic,ed25519:yc,secp256k1:Nc};function Lc(r){let e=Object.keys(lr).join(" / ");return new x(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Dc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return lr[r];throw Lc(r)}async function xh(r,e){return Dc(r).generateKeyPair(e??2048)}function ao(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return lr.rsa.unmarshalRsaPublicKey(t);case oe.Ed25519:return lr.ed25519.unmarshalEd25519PublicKey(t);case oe.Secp256k1:return lr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Lc(e.Type??"unknown")}}function vh(r,e){return e=(e??"rsa").toLowerCase(),Dc(e),r.bytes}async function co(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return lr.rsa.unmarshalRsaPrivateKey(t);case oe.Ed25519:return lr.ed25519.unmarshalEd25519PrivateKey(t);case oe.Secp256k1:return lr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Lc(e.Type??"RSA")}}function _h(r,e){return e=(e??"rsa").toLowerCase(),Dc(e),r.bytes}function M0(r,e){try{if(typeof r=="string"&&r.length>0)return F0(r);if(typeof r=="number"&&isFinite(r))return e?.long?K0(r):V0(r);throw new Error("Value is not a string or number.")}catch(t){let n=H0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function F0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var $s=M0;function V0(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function K0(r){let e=Math.abs(r);return e>=864e5?Hs(r,e,864e5,"day"):e>=36e5?Hs(r,e,36e5,"hour"):e>=6e4?Hs(r,e,6e4,"minute"):e>=1e3?Hs(r,e,1e3,"second"):`${r} ms`}function Hs(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function H0(r){return typeof r=="object"&&r!==null&&"message"in r}function Pc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=$s,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let E=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(R,v)=>{if(R==="%%")return"%";E++;let I=t.formatters[v];if(typeof I=="function"){let N=g[E];R=I.call(y,N),g.splice(E,1),E--}return R}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}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 t.setupFormatters(t.formatters),t.enable(t.load()),t}var qs=W0(),$0=["#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 q0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function z0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+$s(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var G0=console.debug??console.log??(()=>{});function Y0(r){try{r?qs?.setItem("debug",r):qs?.removeItem("debug")}catch{}}function j0(){let r;try{r=qs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function W0(){try{return localStorage}catch{}}function X0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Ah=Pc({formatArgs:z0,save:Y0,load:j0,useColors:q0,setupFormatters:X0,colors:$0,storage:qs,log:G0});var Ze=Ah;Ze.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);Ze.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ze.formatters.m=r=>r==null?"undefined":Mn.baseEncode(r);Ze.formatters.p=r=>r==null?"undefined":r.toString();Ze.formatters.c=r=>r==null?"undefined":r.toString();Ze.formatters.k=r=>r==null?"undefined":r.toString();Ze.formatters.a=r=>r==null?"undefined":r.toString();function Z0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function zs(){return{forComponent(r){return Q0(r)}}}function Q0(r){let e=Z0(`${r}:trace`);return Ze.enabled(`${r}:trace`)&&Ze.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Ze(`${r}:trace`)),Object.assign(Ze(r),{error:Ze(`${r}:error`),trace:e})}var Rh=Symbol.for("nodejs.util.inspect.custom"),Sh=Object.values(jt).map(r=>r.decoder).reduce((r,e)=>r.or(e),jt.identity.decoder),Ih=114,Mc=36,Fc=37,lo=class{type;multihash;privateKey;publicKey;string;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()})`}[No]=!0;toString(){return this.string==null&&(this.string=ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return et.createV1(Ih,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Rh](){return`PeerId(${this.toString()})`}},Cr=class extends lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},kr=class extends lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Nr=class extends lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Oc=2336,Uc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=It.digest(L(this.url))}[Rh](){return`PeerId(${this.url})`}[No]=!0;toString(){return this.toCID().toString()}toCID(){return et.createV1(Oc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};function Th(r){if(r.type==="RSA")return new Cr(r);if(r.type==="Ed25519")return new kr(r);if(r.type==="secp256k1")return new Nr(r);throw new x("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??Sh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=yr(ae.decode(`z${r}`));return r.startsWith("12D")?new kr({multihash:t}):r.startsWith("16U")?new Nr({multihash:t}):new Cr({multihash:t})}return dn(Sh.decode(r))}function dn(r){try{let e=yr(r);if(e.code===It.code){if(e.digest.length===Mc)return new kr({multihash:e});if(e.digest.length===Fc)return new Nr({multihash:e})}if(e.code===Re.code)return new Cr({multihash:e})}catch{return J0(et.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function J0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ih&&r.code!==Oc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Oc){let t=V(r.multihash.digest);return new Uc(new URL(t))}let e=r.multihash;if(e.code===Re.code)return new Cr({multihash:r.multihash});if(e.code===It.code){if(e.digest.length===Mc)return new kr({multihash:r.multihash});if(e.digest.length===Fc)return new Nr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function pn(r,e){return r.length===Mc?new kr({multihash:mt(It.code,r),privateKey:e}):r.length===Fc?new Nr({multihash:mt(It.code,r),privateKey:e}):new Cr({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function mn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Qe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return mn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var Kt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.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 mn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Lh=Symbol.for("@achingbrain/uint8arraylist");function Nh(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ys(r){return!!r?.[Lh]}var we=class r{bufs;length;[Lh]=!0;constructor(...e){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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ys(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ys(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Nh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Nh(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ys(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:o}=this._subList(e,t);return Ie(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ie(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ys(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Vc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Vc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=st(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function Lr(r,e){return Math.floor(Math.random()*(e-r))+r}var Dr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=Lr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Kc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Dh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ph=new globalThis.TextEncoder;function ey(r,e){let t=Kc[e],n=Dh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ty(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Kc[e],o=Dh[e],s=r;for(;s.length>0;){let i=Ph.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Hc(r,{size:e=32,utf8Buffer:t}={}){if(!Kc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return ty(r,e,t);r=Ph.encode(r)}return ey(r,e)}var ry=gr(kh(),1);var fo={hash:r=>Number(Hc(r,{size:32})),hashV:(r,e)=>ny(fo.hash(r,e))};function ny(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var oy=500,ho=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??fo,this.seed=e.seed??Lr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Dr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Dr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Lr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Dr(this.bucketSize));for(let a=0;a<oy;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Dr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},sy={1:.5,2:.84,4:.95,8:.98};function iy(r=.001){return r>.002?2:r>1e-5?4:8}function Oh(r,e=.001){let t=iy(e),n=sy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Vc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var js=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??fo,this.seed=e.seed??Lr(0,Math.pow(2,10)),this.filterSeries=[new ho({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ho({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function $c(r,e=.001,t){return new js({...Oh(r,e),...t??{}})}var Uh=async()=>{let r=await xh("Ed25519"),e=await ay(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function ay(r){return pn(vh(r.public),_h(r))}var Mh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var po;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(po||(po={}));var gn=class r{static createFromProtobuf=async e=>{let t=po.decode(e),n=await pn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Fh(n,o,s),c=await(await co(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new x("envelope signature is not valid for the given domain",Mh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=po.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return te(this.marshal(),e.marshal())}async validate(e){let t=Fh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return ao(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Fh=(r,e,t)=>{let n=L(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new we(o,n,s,e,i,t)};function Vh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ws=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Kh=45,cy=15,yn=new Ws;function qc(r){if(!(r.length>cy))return yn.new(r).parseWith(()=>yn.readIPv4Addr())}function zc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Kh))return yn.new(r).parseWith(()=>yn.readIPv6Addr())}function Xs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Kh))return yn.new(r).parseWith(()=>yn.readIPAddr())}var aA=parseInt("0xFFFF",16),cA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function wn(r){return!!qc(r)}function bn(r){return!!zc(r)}function Zs(r){return!!Xs(r)}var qh=wn,dy=bn,Gc=function(r){let e=0;if(r=r.toString().trim(),qh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(dy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=qh(t[n]),i;s&&(i=Gc(t[n]),t[n]=V(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,V(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},zh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var En={},Yc={},my=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];my.forEach(r=>{let e=gy(...r);Yc[e.code]=e,En[e.name]=e});function gy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Yc[r]!=null)return Yc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(En[r]!=null)return En[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var zA=W("ip4"),GA=W("ip6"),YA=W("ipcidr");function Zc(r,e){switch(W(r).code){case 4:case 41:return wy(e);case 42:return Xc(e);case 6:case 273:case 33:case 132:return jh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Xc(e);case 421:return vy(e);case 444:return Yh(e);case 445:return Yh(e);case 466:return xy(e);case 481:return globalThis.encodeURIComponent(Xc(e));default:return V(e,"base16")}}function Qc(r,e){switch(W(r).code){case 4:return Gh(e);case 41:return Gh(e);case 42:return Wc(e);case 6:case 273:case 33:case 132:return Jc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wc(e);case 421:return by(e);case 444:return _y(e);case 445:return Ay(e);case 466:return Ey(e);case 481:return Wc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var jc=Object.values(jt).map(r=>r.decoder),yy=function(){let r=jc[0].or(jc[1]);return jc.slice(2).forEach(e=>r=r.or(e)),r}();function Gh(r){if(!Zs(r))throw new Error("invalid ip address");return Gc(r)}function wy(r){let e=zh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Zs(e))throw new Error("invalid ip address");return e}function Jc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function jh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wc(r){let e=L(r),t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function Xc(r){let e=lt(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function by(r){let e;r[0]==="Q"||r[0]==="1"?e=yr(ae.decode(`z${r}`)).bytes:e=et.parse(r).multihash.bytes;let t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function Ey(r){let e=yy.decode(r),t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function xy(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function vy(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function _y(r){let e=r.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 t=We.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 o=Jc(n);return Ie([t,o],t.length+o.length)}function Ay(r){let e=r.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 t=We.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 o=Jc(n);return Ie([t,o],t.length+o.length)}function Yh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=jh(t);return`${n}:${o}`}function Wh(r){r=el(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Zh("invalid address: "+r);if(a.path===!0){n=el(o.slice(s).join("/")),e.push([a.code,Qc(a.code,n)]),t.push([a.code,n]);break}let c=Qc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Zc(a.code,c)])}return{string:Xh(t),bytes:rl(e),tuples:e,stringTuples:t,path:n}}function tl(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=de(s),a=W(s),c=Sy(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Zh("Invalid address Uint8Array: "+V(r,"base16"));e.push([s,u]);let f=Zc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Xh(t),tuples:e,stringTuples:t,path:n}}function Xh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),el(e.join("/"))}function rl(r){return Ie(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(De(t.code));return e.length>1&&e[1]!=null&&(n=Ie([n,e[1]])),n}))}function Sy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=lt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function el(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Zh(r){return new Error("Error parsing address: "+r)}var Ry=Symbol.for("nodejs.util.inspect.custom"),nl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Iy=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Qs=class r{bytes;#e;#t;#s;#a;[nl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=tl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Wh(e)}else if(ur(e))t=tl(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),Iy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=W(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(rl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===En.p2p.code&&e.push([n,o]),n===En["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ae.decode(`z${n}`),"base58btc"):V(et.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=xn.get(t.name);if(n==null)throw new x(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>se(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 t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Ry](){return`Multiaddr(${this.#e})`}};var xn=new Map;function ur(r){return!!r?.[nl]}function se(r){return new Qs(r)}var Qh="libp2p-peer-record",Jh=Uint8Array.from([3,1]);var mo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;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})),o),n.encode=s=>Ke(s,n.codec()),n.decode=s=>Ve(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=He((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){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(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Ke(n,r.codec()),r.decode=n=>Ve(n,r.codec())})(mo||(mo={}));var Pr=class r{static createFromProtobuf=e=>{let t=mo.decode(e),n=dn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Qh;static CODEC=Jh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=mo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Vh(this.multiaddrs,e.multiaddrs))}};function Ty(r){return r[Symbol.asyncIterator]!=null}function By(r){if(Ty(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var go=By;var sl=gr(td(),1);var wo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},rd=r=>globalThis.DOMException===void 0?new il(r):new DOMException(r),nd=r=>{let e=r.reason===void 0?rd("This operation was aborted."):r.reason;return e instanceof Error?e:rd(e)};function bo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&f(nd(d)),d.addEventListener("abort",()=>{f(nd(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new wo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function al(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Eo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=al(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var fr=class extends sl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Eo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${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 \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#_(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}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})`);this.#u=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=bo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof wo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var hr={},vn=r=>{r.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)})};vn.addEventListener=(r,e)=>{hr[r]==null&&(hr[r]=[]),hr[r].push(e)};vn.removeEventListener=(r,e)=>{hr[r]!=null&&(hr[r]=hr[r].filter(t=>t===e))};vn.dispatchEvent=function(r,e,t){hr[r]!=null&&hr[r].forEach(n=>n(e,t))};var cl=vn;var ll="lock:worker:request-read",ul="lock:worker:release-read",fl="lock:master:grant-read",hl="lock:worker:request-write",dl="lock:worker:release-write",pl="lock:master:grant-write";var od=(r=21)=>Math.random().toString().substring(2);var sd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},id=(r,e,t,n)=>async()=>{let o=od();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},Ny={singleProcess:!1},ad=r=>{if(r=Object.assign({},Ny,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return cl.addEventListener("message",sd(t,"requestReadLock",ll,ul,fl)),cl.addEventListener("message",sd(t,"requestWriteLock",hl,dl,pl)),t}return{isWorker:!0,readLock:t=>id(t,ll,fl,ul),writeLock:t=>id(t,hl,pl,dl)}};var Or={},dr;async function ml(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>bo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Ly=(r,e)=>{if(dr.isWorker===!0)return{readLock:dr.readLock(r,e),writeLock:dr.writeLock(r,e)};let t=new fr({concurrency:1}),n;return{async readLock(){if(n!=null)return ml(n,e);n=new fr({concurrency:e.concurrency,autoStart:!1});let o=n,s=ml(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,ml(t,e)}}},Dy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function gl(r){let e=Object.assign({},Dy,r);return dr==null&&(dr=ad(e),dr.isWorker!==!0&&(dr.addEventListener("requestReadLock",t=>{Or[t.data.name]!=null&&Or[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),dr.addEventListener("requestWriteLock",async t=>{Or[t.data.name]!=null&&Or[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Or[e.name]==null&&(Or[e.name]=Ly(e.name,e)),Or[e.name]}var Be={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var _n;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=He((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=He((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),ti.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=ti.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=He((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ei.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(ei.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ke(o,r.codec()),r.decode=o=>Ve(o,r.codec())})(_n||(_n={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(ei||(ei={}));var ti;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(ti||(ti={}));function An(r,e){let t=_n.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Th({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ht="/",cd=new TextEncoder().encode(Ht),ri=cd[0],Ur=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ri)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ht))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=cd),this._buf[0]!==ri){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ri,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ri;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ht).slice(1)}type(){return Py(this.baseNamespace())}name(){return Oy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ht)||(e+=Ht),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ht):new r(e.slice(0,-1).join(Ht))}child(e){return this.toString()===Ht?e:e.toString()===Ht?this:new r(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 r.withNamespaces([...this.namespaces(),...Uy(e.map(t=>t.namespaces()))])}};function Py(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Oy(r){let e=r.split(":");return e[e.length-1]}function Uy(r){return[].concat(...r)}var yl="/peers/";function Sn(r){if(!Lo(r)||r.type==null)throw new x("Invalid PeerId",Be.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Ur(`${yl}${e}`)}async function ld(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!ur(o.multiaddr))throw new x("Multiaddr was invalid",Be.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function oi(r,e,t,n){if(e==null)throw new x("Invalid PeerData",Be.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(e.publicKey,r.publicKey))throw new x("publicKey bytes do not match peer id publicKey bytes",Be.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new x("peer id did not match existing peer id",Be.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ni(l,{validate:ud})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ni(l,{validate:fd,map:hd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[d,h]of l)h==null?a.delete(d):a.set(d,h);a=ni([...a.entries()],{validate:ud})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),d=new Map(c);for(let[h,p]of l)p==null?d.delete(h):d.set(h,p);c=ni([...d.entries()],{validate:fd,map:hd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await ld(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,d)=>l.localeCompare(d)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function ni(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function ud(r,e){if(typeof r!="string")throw new x("Metadata key must be a string",Be.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new x("Metadata value must be a Uint8Array",Be.ERR_INVALID_PARAMETERS)}function fd(r,e){if(typeof r!="string")throw new x("Tag name must be a string",Be.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new x("Tag value must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new x("Tag value must be between 0-100",Be.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new x("Tag ttl must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new x("Tag ttl must be between greater than 0",Be.ERR_INVALID_PARAMETERS)}}function hd(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function si(r,e,t){let n=r.toString().split("/")[2],o=We.decode(n),s=dn(o),i=t.get(s);if(i!=null)return i;let a=An(s,e);return t.set(s,a),a}function My(r,e){return r==null?{}:{prefix:yl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(si(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(si(n.key,n.value,e),si(o.key,o.value,e)))}}var ii=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=gl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new x("Cannot delete self peer",Be.ERR_INVALID_PARAMETERS);await this.datastore.delete(Sn(e))}async load(e){let t=await this.datastore.get(Sn(e));return An(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Qe;for await(let{key:n,value:o}of this.datastore.query(My(e??{},t))){let s=si(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Sn(e)),n=An(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=_n.encode(t);return n!=null&&te(s,n)?{peer:An(e,s),previous:o,updated:!1}:(await this.datastore.put(Sn(e),s),{peer:An(e,s),previous:o,updated:!0})}};var ai=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new ii(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await go(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await gn.openAndCertify(e,Pr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Pr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await gn.createFromProtobuf(s.peerRecordEnvelope),a=Pr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Fy(r){return r[Symbol.asyncIterator]!=null}function Vy(r){if(Fy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var wl=Vy;function Ky(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var dd=Ky;function Hy(r){return r[Symbol.asyncIterator]!=null}function $y(r,e){let t=0;if(Hy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=dd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Mr=$y;function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r,e){return qy(r)?async function*(){yield*(await go(r)).sort(e)}():function*(){yield*go(r).sort(e)}()}var bl=zy;function Gy(r){return r[Symbol.asyncIterator]!=null}function Yy(r,e){return Gy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var El=Yy;var ci=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await wl(this.putMany(e,n)),e=[],await wl(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>bl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Mr(n,()=>o++>=s)}return e.limit!=null&&(n=El(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>bl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Mr(n,()=>s++>=o)}return e.limit!=null&&(n=El(n,e.limit)),n}};var yd=gr(gd(),1);function wd(r){return r=r??new Error("Not Found"),(0,yd.default)(r,"ERR_NOT_FOUND")}var li=class extends ci{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw wd();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Ur(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Ur(e)}};function bd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Xy=r=>r;function xl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var ui=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Xy,this._updatePeerStoreAddresses=bd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}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,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var vl=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=zs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>pu(t)).map(async t=>{await t[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")}},Zy=["metrics","connectionProtector","dns"],Qy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ed(r={}){let e=new vl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Qy.includes(o)){let i=e.components[o];if(i==null&&!Zy.includes(o))throw new x(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function xd(r){let e={};for(let t of Object.values(r.components))for(let n of Jy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of ew(t))if(e[n]!==!0)throw new x(`Service "${tw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function Jy(r){return Array.isArray(r?.[Pn])?r[Pn]:[]}function ew(r){return Array.isArray(r?.[ha])?r[ha]:[]}function tw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var _d=gr(vd(),1),rw=["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"],nw=rw.map(r=>new _d.Netmask(r));function _l(r){for(let e of nw)if(e.contains(r))return!0;return!1}function ow(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sw(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return _l(o)}function iw(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aw(r){let e=r.split(":"),t=e[e.length-1];return _l(t)}function cw(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function fi(r){return wn(r)?_l(r):ow(r)?sw(r):iw(r)?aw(r):bn(r)?cw(r):void 0}function Ad(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!fi(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var lw=r=>r.toString().split("/").slice(1),vo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>vo(t=>t===r).match(e),pattern:r}),pi=()=>({match:r=>vo(e=>typeof e=="string").match(r),pattern:"{string}"}),mi=()=>({match:r=>vo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ce=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ae.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),hi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ba.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),ot=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=lw(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var Sl=Q(Y("dns4"),pi()),Rl=Q(Y("dns6"),pi()),Il=Q(Y("dnsaddr"),pi()),Sd=Q(Y("dns"),pi()),wR=fe(Sl),bR=fe(Rl),ER=fe(Il),xR=fe(ot(Sd,Il,Sl,Rl)),Rd=Q(Y("ip4"),vo(wn)),Id=Q(Y("ip6"),vo(bn)),Td=ot(Rd,Id),vt=ot(Td,Sd,Sl,Rl,Il),vR=fe(vt),_R=fe(Rd),AR=fe(Id),SR=fe(Td),Tl=Q(vt,Y("tcp"),mi()),_o=Q(vt,Y("udp"),mi()),RR=fe(Tl),IR=fe(_o),Bl=Q(_o,Y("quic")),gi=Q(_o,Y("quic-v1")),uw=ot(Bl,gi),TR=fe(Bl),BR=fe(gi),Al=ot(vt,Tl,_o,Bl,gi),Bd=ot(Q(Al,Y("ws"),be(Ce()))),CR=fe(Bd),Cd=ot(Q(Al,Y("wss"),be(Ce())),Q(Al,Y("tls"),Y("ws"),be(Ce()))),kR=fe(Cd),kd=Q(_o,Y("webrtc-direct"),be(hi()),be(hi()),be(Ce())),NR=fe(kd),Nd=Q(gi,Y("webtransport"),be(hi()),be(hi()),be(Ce())),LR=fe(Nd),di=ot(Bd,Cd,Q(Tl,be(Ce())),Q(uw,be(Ce())),Q(vt,be(Ce())),kd,Nd,Ce()),DR=fe(di),fw=Q(di,Y("p2p-circuit"),Ce()),Ao=fe(fw),hw=ot(Q(di,Y("p2p-circuit"),Y("webrtc"),be(Ce())),Q(di,Y("webrtc"),be(Ce())),Y("webrtc")),PR=fe(hw),dw=ot(Q(vt,Y("tcp"),mi(),Y("http"),be(Ce())),Q(vt,Y("http"),be(Ce()))),OR=fe(dw),pw=ot(Q(vt,Y("tcp"),ot(Q(Y("443"),Y("http")),Q(mi(),Y("https"))),be(Ce())),Q(vt,Y("tls"),Y("http"),be(Ce())),Q(vt,Y("https"),be(Ce()))),UR=fe(pw);function Cl(r){try{let{address:e}=r.nodeAddress();return!!fi(e)}catch{return!0}}function mw(r,e){let t=Cl(r.multiaddr),n=Cl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function gw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function yw(r,e){let t=Ao.exactMatch(r.multiaddr),n=Ao.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rn(r,e){let t=mw(r,e);if(t!==0)return t;let n=yw(r,e);return n!==0?n:gw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function yi(r){let e=[Je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var kl=60;function wi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Je[e.type],TTL:e.TTL??e.ttl??kl,data:e.data instanceof Uint8Array?V(e.data):e.data}))}}var ww=4;function Nl(r,e={}){let t=new fr({concurrency:e.queryConcurrency??ww});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),yi(o.types).forEach(a=>{s.append("type",Je[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wi(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ld(){return[Nl("https://cloudflare-dns.com/dns-query"),Nl("https://dns.google/resolve")]}var Od=gr(Pd(),1);var Ll=class{lru;constructor(e){this.lru=(0,Od.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return wi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Je[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??kl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Ud(r){return new Ll(r)}var bw=1e3,bi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Ud(e.cacheSize??bw),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ld())}async query(e,t={}){let n=yi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Je||(Je={}));function Md(r={}){return new bi(r)}var Ew=32,{code:xw}=W("dnsaddr"),Fr=async function(e,t={}){let n=t.maxRecursiveDepth??Ew;if(n===0)throw new x("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===xw)??[],i=await(t?.dns??Md()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Je.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Yd=gr(Gd(),1),vi=Yd.default;var $t;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})($t||($t={}));var k;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(k||(k={}));var Iw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Fr},addressSorter:Rn},transportManager:{faultTolerance:zt.FATAL_ALL}};async function jd(r){let e=vi(Iw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new x($t.ERR_PROTECTOR_REQUIRED,k.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await pn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new x("Private key doesn't match peer id",k.ERR_INVALID_KEY);return e}var Wd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Tw=new WeakMap;function Bw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Wd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Wd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Tw.set(l,()=>{c(s),s=null,i()}),l}}var Cw=Bw(),Xd=Cw;var _i=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Pl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new x("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Xd(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&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)}},Pl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function Ai(r){if(Lo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!ur(n))throw new x("Invalid Multiaddr",k.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new x("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e?.equals(s)!==!0)throw new x("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Si=class{buffer;mask;top;btm;next;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}},Bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Si(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 t=this.head;this.head=t.next=new Si(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ol=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ri(r={}){return kw(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function kw(r,e){e=e??{};let t=e.onEnd,n=new Bn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new Bn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new Bn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((E,A)=>{w=()=>{A(new Ol)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Ul=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Cn(r,e,t,n){let o=new Ul(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Ii=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function pr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Ii(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Ii(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ti=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Bi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Nw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ie(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Gt),this.cleanup())}async join(e={}){let t=new Ti(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await pr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var kn=class extends St{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new Bi(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Gt)}),this.clear()}async onEmpty(e){this.size!==0&&await Cn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Cn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Cn(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ri({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new x("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ci=class extends kn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ki="last-dial-failure";var Ni=5,Li=100,Di=50,Pi=1e3*60*7;var Vr={minConnections:Ni,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Pi,autoDialDiscoveredPeersDebounce:10},Oi=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Vr.minConnections,this.autoDialPriority=t.autoDialPriority??Vr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Vr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Vr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Vr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Vr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ci({concurrency:t.autoDialConcurrency??Vr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Kt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Qe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,d=i.get(f.id)??0;return l>d?-1:l<d?1:0}).filter(u=>{let f=u.metadata.get(ki);if(f==null)return!0;let l=parseInt(V(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Dw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Zd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Dw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Qd={maxConnections:Li,allow:[]},Ui=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Qd.maxConnections,this.allow=t.allow??Qd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Qe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await Zd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Mi=class extends kn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Kr(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function Jd(r,e){let t=!1;for(let o of xn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var So={addressSorter:Rn,maxParallelDials:Di,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Fr}},Fi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??So.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??So.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??So.maxDialQueueLength,this.dialTimeout=t.dialTimeout??So.dialTimeout,this.connections=t.connections??new Qe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))xn.set(n,o);this.queue=new Mi({concurrency:t.maxParallelDials??So.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ai(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new x("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new x("Peer had more than maxPeerAddrsToDial",k.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",d.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[ki]:L(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new x(h.message,Po);l.push(h)}}throw l.length===1?l[0]:new Do(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??zl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Kr([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ie(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new x("Tried to dial self",k.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new x("The dial request is blocked by gater.allowDialPeer",k.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.code!==k.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.code!==k.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await Jd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new x("The dial request has no valid addresses",k.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new x("The connection gater denied all addresses in the dial request",k.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!Ao.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var zl=50,qt={minConnections:Ni,maxConnections:Li,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Pi,autoDialDiscoveredPeersDebounce:10},Vi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??qt.maxConnections;let n=t.minConnections??qt.minConnections;if(this.maxConnections<n)throw new x("Connection Manager maxConnections must be greater than minConnections",k.ERR_INVALID_PARAMETERS);this.connections=new Qe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),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=(t.allow??[]).map(o=>se(o)),this.deny=(t.deny??[]).map(o=>se(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??qt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new _i({points:t.inboundConnectionThreshold??qt.inboundConnectionThreshold,duration:1}),this.autoDial=new Oi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??qt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??qt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??qt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??qt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??qt.autoDialMaxQueueLength}),this.connectionPruner=new Ui({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Fi(e,{addressSorter:t.addressSorter??Rn,maxParallelDials:t.maxParallelDials??Di,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Fr},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(du)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new x("Not started",k.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=Ai(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),t.onProgress?.(new he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??zl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>se(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Nn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Uw=1.2,Mw=2,Fw=2e3,Ki=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Nn(e.interval??5e3),this.failure=new Nn(e.interval??5e3),this.next=new Nn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Mw,this.timeoutMultiplier=e.timeoutMultiplier??Uw,this.minTimeout=e.minTimeout??Fw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Kr([e.signal,n]);return ie(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Gl=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await pr(this.readNext.promise,t?.signal,t)}};function ep(){return new Gl}var Hi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Yl=class extends Error{code;constructor(e,t){super(e),this.code=t}},jl=class extends Yl{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function $i(r,e){let t=ep();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new jl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new we:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new Hi("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Vw=1e4,Kw="1.0.0",Hw="ping",$w="ipfs",tp=32,qi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??$w}/${Hw}/${Kw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Vw,this.timeout=new Ki({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Pn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=$i(o);t=Date.now(),await Promise.all([s.write(rt(tp),{signal:n}),s.read(tp,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function qw(r){return r[Symbol.asyncIterator]!=null}function zw(...r){let e=[];for(let t of r)qw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ri({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Ro=zw;var zi=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new x("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Kt;for await(let s of Ro(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new x("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new x($t.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new x($t.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Gi=globalThis.CustomEvent??Event;async function*Wl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ue(),a=ue(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ue(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new Gi("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new Gi("task-complete"))})}c=!0,o.dispatchEvent(new Gi("task-complete"))}catch(p){u=p,o.dispatchEvent(new Gi("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=ue(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var Yi=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new x("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new x("Should not try to find self",k.ERR_FIND_SELF);let n=this,o=Ro(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new x($t.NOT_FOUND,k.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new x("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=$c(1024);for await(let s of Wl(async function*(){let i=Ro(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var ji=class extends St{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Kr([this.shutdownController.signal,e?.signal]);ie(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Cn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ie(1/0,this.walkController.signal);let e=Kr([this.walkController.signal,this.shutdownController.signal]);ie(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=rt(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await pr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Xl=32,Zl=64,Wi=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new x(`No handler registered for protocol ${e}`,k.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new x(`Handler already registered for protocol ${e}`,k.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=vi.bind({ignoreUndefined:!0})({maxInboundStreams:Xl,maxOutboundStreams:Zl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new x("invalid topology",k.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==k.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Ql=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function rp(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ql({name:e,metrics:t}):n=new Map,n}var Xi=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=rp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??zt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new x("Transport must have a valid tag",k.ERR_INVALID_KEY);if(this.transports.has(t))throw new x(`There is already a transport with the tag ${t}`,k.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}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[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new x(`No transport available for address ${String(e)}`,k.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new he("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=k.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new x("Not started",k.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==zt.NO_FATAL)throw new x(`Transport (${n}) could not listen on any available address`,k.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===zt.FATAL_ALL)throw new x(n,k.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var ke="/multistream/1.0.0";var Zi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,e={}){let t=$i(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Zi("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ji("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Qi("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Gw=L(`
8
+ `);async function Hr(r,e,t){await r.write(e,t)}async function np(r,e,t){await r.writeV(e,t)}async function Yw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Gw[0])throw e.log.error("Invalid mss message - missing newline",t),new x("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function mr(r,e){let t=await Yw(r,e);return V(t.subarray())}async function To(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return jw(r,e[0],t);let n=Io(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',ke,o);let s=L(`${ke}
9
9
  `),i=L(`${o}
10
- `);await tp(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await hr(n,t);if(t.log.trace('select: read "%s"',a),a===Ce&&(t.log.trace("select: reading protocol response"),a=await hr(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Fr(n,L(`${c}
11
- `),t),t.log.trace("select: reading protocol response");let u=await hr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Gw(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ue(),c=!1,u=!1,f=ue(),l=!1,p=!1,h=ue(),d=_o({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async y=>{let{sink:b}=d.unwrap();await b(async function*(){let x=!1;for await(let A of y){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ce,e,A.byteLength);let R=`${e}
12
- `;yield new we(Uint8Array.from([19]),L(`${Ce}
13
- `),Le(R.length),L(R),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ce,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(_=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,_)})}x=!0}x||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await w()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await g())}finally{i=!1,s=!0,a.resolve()}}async function w(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Ce,e),await d.writeV([L(`${Ce}
10
+ `);await np(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await mr(n,t);if(t.log.trace('select: read "%s"',a),a===ke&&(t.log.trace("select: reading protocol response"),a=await mr(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Hr(n,L(`${c}
11
+ `),t),t.log.trace("select: reading protocol response");let u=await mr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new x("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function jw(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ue(),c=!1,u=!1,f=ue(),l=!1,d=!1,h=ue(),p=Io({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let E=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',ke,e,A.byteLength);let R=`${e}
12
+ `;yield new we(Uint8Array.from([19]),L(`${ke}
13
+ `),De(R.length),L(R),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',ke,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,v)})}E=!0}E||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',ke,e),await p.writeV([L(`${ke}
14
14
  `),L(`${e}
15
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ce,e)}finally{c=!0,u=!1,f.resolve()}}async function g(){if(p){await h.promise;return}p=!0;try{t.log.trace("optimistic: reading multistream select header");let y=await hr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',y),y===Ce&&(y=await hr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',y,e),y!==e)throw new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,p=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*d.unwrap().source}(),r.closeRead!=null){let y=r.closeRead.bind(r);r.closeRead=async b=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await y(b)}}if(r.closeWrite!=null){let y=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await y(b)}}if(r.close!=null){let y=r.close.bind(r);r.close=async b=>{let x=[];u&&x.push(f.promise),p&&x.push(h.promise),x.length>0?await fr(Promise.all(x),b?.signal):(s=!0,i=!1,a.resolve()),await y(b)}}return{stream:r,protocol:e}}function Qi(r){return r[Symbol.asyncIterator]!=null}var Ji=r=>{let e=de(r),t=ke(e);return Le(r,t),Ji.bytes=e,t};Ji.bytes=0;function ea(r,e){e=e??{};let t=e.lengthEncoder??Ji;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Qi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}ea.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ji;return new we(t(r.byteLength),r)};var ta=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ra=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},na=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},So=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Yw=8,Ww=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Ql=r=>{let e=lt(r);return Ql.bytes=de(e),e};Ql.bytes=0;function Zl(r,e){let t=new we,n=Vr.LENGTH,o=-1,s=e?.lengthDecoder??Ql,i=e?.maxLengthLength??Yw,a=e?.maxDataLength??Ww;function*c(){for(;t.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(t),o<0)throw new ta("Invalid message length");if(o>a)throw new ra("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Vr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new na("Message length length too long");break}throw u}if(n===Vr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Vr.LENGTH}}}return Qi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")}()}Zl.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Zl(n,{...e??{},onLength:s=>{t=s}})};async function Ro(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=_o(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await hr(n,t);if(t.log.trace('handle: read "%s"',o),o===Ce){t.log.trace('handle: respond with "%s" for "%s"',Ce,o),await Fr(n,L(`${Ce}
16
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Ce,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Fr(n,L(`${o}
17
- `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new we(...e.map(i=>ea.single(L(`${i}
15
+ `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',ke,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await mr(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===ke&&(b=await mr(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new x("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(E=>{t.log.error("could not negotiate protocol before close read",E)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(E=>{t.log.error("could not negotiate protocol before close write",E)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let E=[];u&&E.push(f.promise),d&&E.push(h.promise),E.length>0?await pr(Promise.all(E),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:e}}function ea(r){return r[Symbol.asyncIterator]!=null}var ta=r=>{let e=de(r),t=Ne(e);return De(r,t),ta.bytes=e,t};ta.bytes=0;function ra(r,e){e=e??{};let t=e.lengthEncoder??ta;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return ea(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}ra.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ta;return new we(t(r.byteLength),r)};var na=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},oa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},sa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ww=8,Xw=1024*1024*4,$r;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})($r||($r={}));var tu=r=>{let e=lt(r);return tu.bytes=de(e),e};tu.bytes=0;function eu(r,e){let t=new we,n=$r.LENGTH,o=-1,s=e?.lengthDecoder??tu,i=e?.maxLengthLength??Ww,a=e?.maxDataLength??Xw;function*c(){for(;t.byteLength>0;){if(n===$r.LENGTH)try{if(o=s(t),o<0)throw new na("Invalid message length");if(o>a)throw new oa("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=$r.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new sa("Message length length too long");break}throw u}if(n===$r.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=$r.LENGTH}}}return ea(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Bo("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Bo("Unexpected end of input")}()}eu.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return eu(n,{...e??{},onLength:s=>{t=s}})};async function Co(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Io(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await mr(n,t);if(t.log.trace('handle: read "%s"',o),o===ke){t.log.trace('handle: respond with "%s" for "%s"',ke,o),await Hr(n,L(`${ke}
16
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',ke,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Hr(n,L(`${o}
17
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new we(...e.map(i=>ra.single(L(`${i}
18
18
  `))),L(`
19
- `));t.log.trace('handle: respond with "%s" for %s',e,o),await Fr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Fr(n,L(`na
20
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var Xw=500,Jl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[lu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new E("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new E("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Xw);ie(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function np(r){return new Jl(r)}var Zw=3e4;function Qw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Yl}function Jw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Wl}function op(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var oa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new E(`The multiaddr connection is blocked by gater.${n}`,k.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",k.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",No))};u.addEventListener("abort",f,{once:!0}),ie(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",k.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),l=await p.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new he("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let p={...l,...o};await this.shouldBlockConnection(s,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new E("inbound connection that skipped encryption must have a peer id",k.ERR_INVALID_MULTIADDR);let h=ye(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new he("upgrader:multiplex-inbound-connection"));let p=await this._multiplexInbound({...l,...o},this.muxers);a=p.muxerFactory,i=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new E("Encryption was skipped but no peer id was passed",k.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:w,protocol:g}=await Ro(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let y=Qw(g,this.components.registrar);if(op(g,"inbound",l)===y){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,k.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=w.source,d.sink=w.sink,d.protocol=g,w.closeWrite!=null&&(d.closeWrite=w.closeWrite),w.closeRead!=null&&(d.closeRead=w.closeRead),w.close!=null&&(d.close=w.close),await this.components.peerStore.merge(i,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(async m=>{l.log.error("error handling incoming stream id %s",d.id,m.message,m.code,m.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,m={})=>{if(u==null)throw new E("Stream is not multiplexed",k.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let w=await u.newStream();l.log.trace("started new stream %s for protocols %s",w.id,d);try{if(m.signal==null){w.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let A=AbortSignal.timeout(Zw);ie(1/0,A),m={...m,signal:A}}w.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:y}=await Ao(w,d,{...m,log:w.log,yieldBytes:!0});w.log("selected protocol %s",y);let b=Jw(y,this.components.registrar,m),x=op(y,"outbound",l);if(x>=b){let A=new E(`Too many outbound protocol streams for protocol "${y}" - ${x}/${b}`,k.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw w.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[y]}),w.source=g.source,w.sink=g.sink,w.protocol=y,g.closeWrite!=null&&(w.closeWrite=g.closeWrite),g.closeRead!=null&&(w.closeRead=g.closeRead),g.close!=null&&(w.close=g.close),this.components.metrics?.trackProtocolStream(w,l),w}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),w.timeline.close==null&&w.abort(g),g.code!=null?g:new E(String(g),k.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let p=o.timeline;o.timeline=new Proxy(p,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&p.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",k.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Ro(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new E(n.message,k.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Ao(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new E(o.message,k.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Ao(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new E(String(o),k.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Ro(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),k.ERR_MUXER_UNAVAILABLE)}}};var sp="1.9.3-1675adee2",ip="libp2p";var eu=class extends At{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new At,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new la(a.type,{detail:a.detail}));return c||u},ie(1/0,t),this.peerId=e.peerId,this.logger=e.logger??$s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=wd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:ip,version:sp},logger:this.logger,events:t,datastore:e.datastore??new ai,connectionGater:vd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new si(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new oa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Wi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Mi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Hi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Yi(this.components)),this.configureComponent("addressManager",new ci(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zi(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new $i(this.components,{routers:i})),this.configureComponent("randomWalk",new Gi(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[ia]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ia])),u[ca]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ca])),u[aa]!=null&&(this.log("registering service %s for peer discovery",a),u[aa].addEventListener?.("peer",f=>{this.#e(f)}))}bd(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Mt;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new E("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ar(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==k.ERR_NOT_FOUND)throw s}let n=Re([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return no(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(k.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function ap(r={}){let e=r.peerId??=await Ph();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await oo(e.privateKey),new eu(await Gd(r))}async function tb(r={}){let e=await ap(r);return r.start!==!1&&await e.start(),e}return Ep(rb);})();
19
+ `));t.log.trace('handle: respond with "%s" for %s',e,o),await Hr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Hr(n,L(`na
20
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var Qw=500,ru=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[hu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new x("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new x("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new x("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Qw);ie(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function sp(r){return new ru(r)}var Jw=3e4;function eb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Xl}function tb(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Zl}function ip(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var ia=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new x(`The multiaddr connection is blocked by gater.${n}`,k.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new x("connection denied",k.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new x("inbound upgrade timeout",Po))};u.addEventListener("abort",f,{once:!0}),ie(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new x("The multiaddr connection is blocked by gater.acceptConnection",k.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the inbound connection"),l=await d.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new he("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new x("inbound connection that skipped encryption must have a peer id",k.ERR_INVALID_MULTIADDR);let h=ye(d);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new he("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.muxers);a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new x("Encryption was skipped but no peer id was passed",k.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await Co(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=eb(y,this.components.registrar);if(ip(y,"inbound",l)===b){let E=new x(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`,k.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(E),E}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new x("Stream is not multiplexed",k.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(Jw);ie(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await To(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=tb(b,this.components.registrar,m),E=ip(b,"outbound",l);if(E>=w){let A=new x(`Too many outbound protocol streams for protocol "${b}" - ${E}/${w}`,k.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y.code!=null?y:new x(String(y),k.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new x("connection is not multiplexed",k.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=sp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new x("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Co(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new x(n.message,k.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await To(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new x(o.message,k.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await To(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new x(String(o),k.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Co(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new x(String(o),k.ERR_MUXER_UNAVAILABLE)}}};var ap="1.9.3-2265e59ba",cp="libp2p";var nu=class extends St{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new St,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new fa(a.type,{detail:a.detail}));return c||u},ie(1/0,t),this.peerId=e.peerId,this.logger=e.logger??zs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Ed({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:cp,version:ap},logger:this.logger,events:t,datastore:e.datastore??new li,connectionGater:Ad(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new ai(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new ia(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Xi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Vi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new qi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Wi(this.components)),this.configureComponent("addressManager",new ui(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Yi(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new zi(this.components,{routers:i})),this.configureComponent("randomWalk",new ji(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[ca]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ca])),u[ua]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ua])),u[la]!=null&&(this.log("registering service %s for peer discovery",a),u[la].addEventListener?.("peer",f=>{this.#e(f)}))}xd(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Kt;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new x("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new x("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ur(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==k.ERR_NOT_FOUND)throw s}let n=Ie([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return ao(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(k.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function lp(r={}){let e=r.peerId??=await Uh();if(e.privateKey==null)throw new x("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await co(e.privateKey),new nu(await jd(r))}async function nb(r={}){let e=await lp(r);return r.start!==!1&&await e.start(),e}return _p(ob);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  pvtsutils/build/index.js: