libp2p 1.7.0 → 1.8.0-ce6da9896

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 up=Object.create;var To=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var hp=Object.getOwnPropertyNames;var dp=Object.getPrototypeOf,pp=Object.prototype.hasOwnProperty;var Je=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xe=(r,e)=>{for(var t in e)To(r,t,{get:e[t],enumerable:!0})},eu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of hp(e))!pp.call(r,o)&&o!==t&&To(r,o,{get:()=>e[o],enumerable:!(n=fp(e,o))||n.enumerable});return r};var At=(r,e,t)=>(t=r!=null?up(dp(r)):{},eu(e||!r||!r.__esModule?To(t,"default",{value:r,enumerable:!0}):t,r)),mp=r=>eu(To({},"__esModule",{value:!0}),r);var sf=Je(an=>{"use strict";var zg="[object ArrayBuffer]",Lt=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}},fc="string",Gg=/^[0-9a-f]+$/i,Yg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Wg=/^[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))}},tt=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===fc&&Gg.test(e)}static isBase64(e){return typeof e===fc&&Yg.test(e)}static isBase64Url(e){return typeof e===fc&&Wg.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 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=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 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 Jo.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=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 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,"")||""}};es.DEFAULT_UTF8_ENCODING="utf8";function jg(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 Xg(...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 Zg(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}an.BufferSourceConverter=Lt;an.Convert=es;an.assign=jg;an.combine=Xg;an.isEqual=Zg});var mh=Je((pv,ph)=>{var hn=1e3,dn=hn*60,pn=dn*60,Br=pn*24,C0=Br*7,k0=Br*365.25;ph.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return N0(r);if(t==="number"&&isFinite(r))return e.long?D0(r):L0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function N0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*k0;case"weeks":case"week":case"w":return t*C0;case"days":case"day":case"d":return t*Br;case"hours":case"hour":case"hrs":case"hr":case"h":return t*pn;case"minutes":case"minute":case"mins":case"min":case"m":return t*dn;case"seconds":case"second":case"secs":case"sec":case"s":return t*hn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function L0(r){var e=Math.abs(r);return e>=Br?Math.round(r/Br)+"d":e>=pn?Math.round(r/pn)+"h":e>=dn?Math.round(r/dn)+"m":e>=hn?Math.round(r/hn)+"s":r+"ms"}function D0(r){var e=Math.abs(r);return e>=Br?Hs(r,e,Br,"day"):e>=pn?Hs(r,e,pn,"hour"):e>=dn?Hs(r,e,dn,"minute"):e>=hn?Hs(r,e,hn,"second"):r+" ms"}function Hs(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var yh=Je((mv,gh)=>{function P0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=mh(),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(...y){if(!m.enabled)return;let g=m,w=Number(new Date),b=w-(l||w);g.diff=b,g.prev=l,g.curr=w,l=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(S,_)=>{if(S==="%%")return"%";x++;let R=t.formatters[_];if(typeof R=="function"){let q=y[x];S=R.call(g,q),y.splice(x,1),x--}return S}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}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:y=>{p=y}}),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.slice(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.enable(t.load()),t}gh.exports=P0});var wh=Je((We,qs)=>{We.formatArgs=U0;We.save=M0;We.load=F0;We.useColors=O0;We.storage=V0();We.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();We.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function O0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function U0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+qs.exports.humanize(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)}We.log=console.debug||console.log||(()=>{});function M0(r){try{r?We.storage.setItem("debug",r):We.storage.removeItem("debug")}catch{}}function F0(){let r;try{r=We.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function V0(){try{return localStorage}catch{}}qs.exports=yh()(We);var{formatters:K0}=qs.exports;K0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var vh=Je((co,zs)=>{(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,y=h.length-m,g=d,w=0,b=3432918353,x=461845907,v=0;v<y;v=v+4)w=h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24,w=o(w,b),w=s(w,15),w=o(w,x),g^=w,g=s(g,13),g=o(g,5)+3864292196;switch(w=0,m){case 3:w^=h[v+2]<<16;case 2:w^=h[v+1]<<8;case 1:w^=h[v],w=o(w,b),w=s(w,15),w=o(w,x),g^=w}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,y=h.length-m,g=d,w=d,b=d,x=d,v=0,S=0,_=0,R=0,q=597399067,$=2869860233,U=951274213,ee=2716044179,D=0;D<y;D=D+16)v=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,S=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,R=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,v=o(v,q),v=s(v,15),v=o(v,$),g^=v,g=s(g,19),g+=w,g=o(g,5)+1444728091,S=o(S,$),S=s(S,16),S=o(S,U),w^=S,w=s(w,17),w+=b,w=o(w,5)+197830471,_=o(_,U),_=s(_,17),_=o(_,ee),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,R=o(R,ee),R=s(R,18),R=o(R,q),x^=R,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(v=0,S=0,_=0,R=0,m){case 15:R^=h[D+14]<<16;case 14:R^=h[D+13]<<8;case 13:R^=h[D+12],R=o(R,ee),R=s(R,18),R=o(R,q),x^=R;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,U),_=s(_,17),_=o(_,ee),b^=_;case 8:S^=h[D+7]<<24;case 7:S^=h[D+6]<<16;case 6:S^=h[D+5]<<8;case 5:S^=h[D+4],S=o(S,$),S=s(S,16),S=o(S,U),w^=S;case 4:v^=h[D+3]<<24;case 3:v^=h[D+2]<<16;case 2:v^=h[D+1]<<8;case 1:v^=h[D],v=o(v,q),v=s(v,15),v=o(v,$),g^=v}return g^=h.length,w^=h.length,b^=h.length,x^=h.length,g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,g=i(g),w=i(w),b=i(b),x=i(x),g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>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,y=h.length-m,g=[0,d],w=[0,d],b=[0,0],x=[0,0],v=[2277735313,289559509],S=[1291169091,658871167],_=0;_<y;_=_+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,v),b=u(b,31),b=c(b,S),g=l(g,b),g=u(g,27),g=a(g,w),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,S),x=u(x,33),x=c(x,v),w=l(w,x),w=u(w,31),w=a(w,g),w=a(c(w,[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,S),x=u(x,33),x=c(x,v),w=l(w,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,v),b=u(b,31),b=c(b,S),g=l(g,b)}return g=l(g,[0,h.length]),w=l(w,[0,h.length]),g=a(g,w),w=a(w,g),g=p(g),w=p(w),g=a(g,w),w=a(w,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)},typeof co<"u"?(typeof zs<"u"&&zs.exports&&(co=zs.exports=t),co.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)})(co)});var Ah=Je((Mv,_h)=>{_h.exports=vh()});var Wh=Je((p2,Yc)=>{"use strict";var vy=Object.prototype.hasOwnProperty,qe="~";function mo(){}Object.create&&(mo.prototype=Object.create(null),new mo().__proto__||(qe=!1));function _y(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Yh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new _y(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 Qs(r,e){--r._eventsCount===0?r._events=new mo:delete r._events[e]}function Ue(){this._events=new mo,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)vy.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 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};Ue.prototype.on=function(e,t,n){return Yh(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return Yh(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 Qs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Qs(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:Qs(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Qs(this,t)):(this._events=new mo,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=qe;Ue.EventEmitter=Ue;typeof Yc<"u"&&(Yc.exports=Ue)});var ul=Je((LS,cd)=>{"use strict";function ad(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Vy(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 ad(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),ad(new o,t)}}cd.exports=Vy});var pd=Je(bo=>{(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}(),bo.ip2long=i,bo.long2ip=a,bo.Netmask=r}).call(bo)});var Id=Je((KR,Rd)=>{Rd.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 Nd=Je((sI,kd)=>{"use strict";kd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Md=Je((Od,Ud)=>{"use strict";var bi=Nd(),{hasOwnProperty:Dd}=Object.prototype,{propertyIsEnumerable:fw}=Object,Tn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),hw=Od,Ld={concatArrays:!1,ignoreUndefined:!1},Ei=r=>{let e=[];for(let t in r)Dd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)fw.call(r,n)&&e.push(n)}return e};function Cn(r){return Array.isArray(r)?dw(r):bi(r)?pw(r):r}function dw(r){let e=r.slice(0,0);return Ei(r).forEach(t=>{Tn(e,t,Cn(r[t]))}),e}function pw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ei(r).forEach(t=>{Tn(e,t,Cn(r[t]))}),e}var Pd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Tn(r,o,_l(r[o],e[o],n)):Tn(r,o,Cn(e[o])))}),r),mw=(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++)Dd.call(s,a)&&(i.push(String(a)),s===r?Tn(n,o++,s[a]):Tn(n,o++,Cn(s[a])));n=Pd(n,s,Ei(s).filter(a=>!i.includes(a)),t)}),n};function _l(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?mw(r,e,t):!bi(e)||!bi(r)?Cn(e):Pd(r,e,Ei(e),t)}Ud.exports=function(...r){let e=_l(Cn(Ld),this!==hw&&this||{},Ld),t={_:{}};for(let n of r)if(n!==void 0){if(!bi(n))throw new TypeError("`"+n+"` is not an Option Object");t=_l(t,{_:n},e)}return t._}});var Vw={};xe(Vw,{createLibp2p:()=>Fw});var tu=Symbol.for("@libp2p/connection");var Ji=Symbol.for("@libp2p/content-routing");var ea=Symbol.for("@libp2p/peer-discovery");var ta=Symbol.for("@libp2p/peer-id");function Co(r){return r!=null&&!!r[ta]}var ra=Symbol.for("@libp2p/peer-routing");var ru="keep-alive";var Ww=Symbol.for("@libp2p/transport");var $t;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})($t||($t={}));var zt=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 fe=(r,...e)=>{try{[...e]}catch{}};var St=class extends EventTarget{#e=new Map;constructor(){super(),fe(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 oa(e,t))}},na=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},oa=globalThis.CustomEvent??na;function nu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var sa=Symbol.for("@libp2p/service-capabilities"),ia=Symbol.for("@libp2p/service-dependencies");var lc={};xe(lc,{Ed25519PrivateKey:()=>Sr,Ed25519PublicKey:()=>$n,generateKeyPair:()=>Hg,generateKeyPairFromSeed:()=>of,unmarshalEd25519PrivateKey:()=>Vg,unmarshalEd25519PublicKey:()=>Kg});var fa={};xe(fa,{base58btc:()=>ie,base58flickr:()=>xp});var Ab=new Uint8Array(0);function ou(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 su(r){return new TextEncoder().encode(r)}function iu(r){return new TextDecoder().decode(r)}function gp(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,y=0,g=0,w=d.length;g!==w&&d[g]===0;)g++,m++;for(var b=(w-g)*f+1>>>0,x=new Uint8Array(b);g!==w;){for(var v=d[g],S=0,_=b-1;(v!==0||S<y)&&_!==-1;_--,S++)v+=256*x[_]>>>0,x[_]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=S,g++}for(var R=b-y;R!==b&&x[R]===0;)R++;for(var q=c.repeat(m);R<b;++R)q+=r.charAt(x[R]);return q}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 y=0,g=0;d[m]===c;)y++,m++;for(var w=(d.length-m)*u+1>>>0,b=new Uint8Array(w);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=w-1;(x!==0||v<g)&&S!==-1;S--,v++)x+=a*b[S]>>>0,b[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,m++}if(d[m]!==" "){for(var _=w-g;_!==w&&b[_]===0;)_++;for(var R=new Uint8Array(y+(w-_)),q=y;_!==w;)R[q++]=b[_++];return R}}}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 yp=gp,wp=yp,cu=wp;var aa=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")}},ca=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 lu(this,e)}},la=class{decoders;constructor(e){this.decoders=e}or(e){return lu(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 lu(r,e){return new la({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ua=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 aa(e,t,n),this.decoder=new ca(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Hr({name:r,prefix:e,encode:t,decode:n}){return new ua(r,e,t,n)}function Gt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=cu(t,r);return Hr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function bp(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 Ep(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 Hr({prefix:e,name:r,encode(o){return Ep(o,n,t)},decode(o){return bp(o,n,t,r)}})}var ie=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xp=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var da={};xe(da,{identity:()=>Yt});var vp=hu,uu=128,_p=127,Ap=~_p,Sp=Math.pow(2,31);function hu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Sp;)e[t++]=r&255|uu,r/=128;for(;r&Ap;)e[t++]=r&255|uu,r>>>=7;return e[t]=r|0,hu.bytes=t-n+1,e}var Rp=ha,Ip=128,fu=127;function ha(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ha.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&fu)<<o:(i&fu)*Math.pow(2,o),o+=7}while(i>=Ip);return ha.bytes=s-n,t}var Bp=Math.pow(2,7),Tp=Math.pow(2,14),Cp=Math.pow(2,21),kp=Math.pow(2,28),Np=Math.pow(2,35),Lp=Math.pow(2,42),Dp=Math.pow(2,49),Pp=Math.pow(2,56),Op=Math.pow(2,63),Up=function(r){return r<Bp?1:r<Tp?2:r<Cp?3:r<kp?4:r<Np?5:r<Lp?6:r<Dp?7:r<Pp?8:r<Op?9:10},Mp={encode:vp,decode:Rp,encodingLength:Up},Fp=Mp,On=Fp;function Un(r,e=0){return[On.decode(r,e),On.decode.bytes]}function qr(r,e,t=0){return On.encode(r,e,t),e}function $r(r){return On.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=$r(r),o=n+$r(t),s=new Uint8Array(o+t);return qr(r,s,0),qr(t,s,n),s.set(e,o),new zr(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 zr(t,o,i,e)}function du(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ou(r.bytes,t.bytes)}}var zr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var pu=0,Vp="identity",mu=Rt;function Kp(r){return pt(pu,mu(r))}var Yt={code:pu,name:Vp,encode:mu,digest:Kp};var ga={};xe(ga,{sha256:()=>Se,sha512:()=>Hp});function ma({name:r,code:e,encode:t}){return new pa(r,e,t)}var pa=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?pt(this.code,t):t.then(n=>pt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function yu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Se=ma({name:"sha2-256",code:18,encode:yu("SHA-256")}),Hp=ma({name:"sha2-512",code:19,encode:yu("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 ot(r=0){return new Uint8Array(r)}function Ne(r=0){return new Uint8Array(r)}function Re(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 ya={};xe(ya,{base10:()=>qp});var qp=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var wa={};xe(wa,{base16:()=>$p,base16upper:()=>zp});var $p=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ba={};xe(ba,{base2:()=>Gp});var Gp=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ea={};xe(Ea,{base256emoji:()=>Zp});var wu=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}"),Yp=wu.reduce((r,e,t)=>(r[t]=e,r),[]),Wp=wu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function jp(r){return r.reduce((e,t)=>(e+=Yp[t],e),"")}function Xp(r){let e=[];for(let t of r){let n=Wp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Zp=Hr({prefix:"\u{1F680}",name:"base256emoji",encode:jp,decode:Xp});var xa={};xe(xa,{base32:()=>ze,base32hex:()=>tm,base32hexpad:()=>nm,base32hexpadupper:()=>om,base32hexupper:()=>rm,base32pad:()=>Jp,base32padupper:()=>em,base32upper:()=>Qp,base32z:()=>sm});var ze=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qp=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Jp=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),em=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),tm=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rm=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),nm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),om=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sm=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var va={};xe(va,{base36:()=>im,base36upper:()=>am});var im=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),am=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Aa={};xe(Aa,{base64:()=>Mn,base64pad:()=>cm,base64url:()=>_a,base64urlpad:()=>lm});var Mn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_a=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lm=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Sa={};xe(Sa,{base8:()=>um});var um=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ra={};xe(Ra,{identity:()=>fm});var fm=Hr({prefix:"\0",name:"identity",encode:r=>iu(r),decode:r=>su(r)});var Qb=new TextEncoder,Jb=new TextDecoder;function bu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return mm(t,Ia(r),e??ie.encoder);default:return gm(t,Ia(r),e??ze.encoder)}}var Eu=new WeakMap;function Ia(r){let e=Eu.get(r);if(e==null){let t=new Map;return Eu.set(r,t),t}return e}var st=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!==ym)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=pt(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&&du(e.multihash,n.multihash)}toString(e){return bu(this,e)}toJSON(){return{"/":bu(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??xu(n,o,s.bytes))}else if(t[wm]===!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=xu(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 zr(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]=Un(e.subarray(t));return t+=p,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]=pm(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 Ia(s).set(n,e),s}};function pm(r,e){switch(r[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${r}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.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 mm(r,e,t){let{prefix:n}=t;if(n!==ie.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 gm(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,ym=18;function xu(r,e,t){let n=$r(r),o=n+$r(e),s=new Uint8Array(o+t.byteLength);return qr(r,s,0),qr(e,s,n),s.set(t,o),s}var wm=Symbol.for("@ipld/js-cid/CID");var Wt={...Ra,...ba,...Sa,...ya,...wa,...xa,...va,...fa,...Aa,...Ea},mE={...ga,...da};function _u(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vu=_u("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ba=_u("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}),bm={utf8:vu,"utf-8":vu,hex:Wt.base16,latin1:Ba,ascii:Ba,binary:Ba,...Wt},Do=bm;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 et(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Gr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Em(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Yr(r,...e){if(!Em(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");Gr(r.outputLen),Gr(r.blockLen)}function Wr(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 Au(r,e){Yr(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 Xr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var TE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var xm=async()=>{};async function Su(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 xm(),n+=s)}}function Ta(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function jt(r){return typeof r=="string"&&(r=Ta(r)),Yr(r),r}function Uo(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Yr(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 jr=class{clone(){return this._cloneInto()}},vm={}.toString;function Ru(r,e){if(e!==void 0&&vm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Mo(r){let e=n=>r().update(jt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Zr(r=32){if(Oo&&typeof Oo.getRandomValues=="function")return Oo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function _m(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 Iu=(r,e,t)=>r&e^~r&t,Bu=(r,e,t)=>r&e^r&t^e&t,Qr=class extends jr{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=Xr(this.buffer)}update(e){Wr(this);let{view:t,buffer:n,blockLen:o}=this;e=jt(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=Xr(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){Wr(this),Au(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;_m(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Xr(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 Fo=BigInt(4294967295),Ca=BigInt(32);function Tu(r,e=!1){return e?{h:Number(r&Fo),l:Number(r>>Ca&Fo)}:{h:Number(r>>Ca&Fo)|0,l:Number(r&Fo)|0}}function Am(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}=Tu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Sm=(r,e)=>BigInt(r>>>0)<<Ca|BigInt(e>>>0),Rm=(r,e,t)=>r>>>t,Im=(r,e,t)=>r<<32-t|e>>>t,Bm=(r,e,t)=>r>>>t|e<<32-t,Tm=(r,e,t)=>r<<32-t|e>>>t,Cm=(r,e,t)=>r<<64-t|e>>>t-32,km=(r,e,t)=>r>>>t-32|e<<64-t,Nm=(r,e)=>e,Lm=(r,e)=>r,Dm=(r,e,t)=>r<<t|e>>>32-t,Pm=(r,e,t)=>e<<t|r>>>32-t,Om=(r,e,t)=>e<<t-32|r>>>64-t,Um=(r,e,t)=>r<<t-32|e>>>64-t;function Mm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Fm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Vm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Km=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Hm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,qm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),$m=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var zm={fromBig:Tu,split:Am,toBig:Sm,shrSH:Rm,shrSL:Im,rotrSH:Bm,rotrSL:Tm,rotrBH:Cm,rotrBL:km,rotr32H:Nm,rotr32L:Lm,rotlSH:Dm,rotlSL:Pm,rotlBH:Om,rotlBL:Um,add:Mm,add3L:Fm,add3H:Vm,add4L:Km,add4H:Hm,add5H:$m,add5L:qm},M=zm;var[Gm,Ym]=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))),Xt=new Uint32Array(80),Zt=new Uint32Array(80),ka=class extends Qr{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:y}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y){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=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)Xt[b]=e.getUint32(t),Zt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Xt[b-15]|0,v=Zt[b-15]|0,S=M.rotrSH(x,v,1)^M.rotrSH(x,v,8)^M.shrSH(x,v,7),_=M.rotrSL(x,v,1)^M.rotrSL(x,v,8)^M.shrSL(x,v,7),R=Xt[b-2]|0,q=Zt[b-2]|0,$=M.rotrSH(R,q,19)^M.rotrBH(R,q,61)^M.shrSH(R,q,6),U=M.rotrSL(R,q,19)^M.rotrBL(R,q,61)^M.shrSL(R,q,6),ee=M.add4L(_,U,Zt[b-7],Zt[b-16]),D=M.add4H(ee,S,$,Xt[b-7],Xt[b-16]);Xt[b]=D|0,Zt[b]=ee|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:y,Hh:g,Hl:w}=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),v=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),S=l&h^~l&m,_=p&d^~p&y,R=M.add5L(w,v,_,Ym[b],Zt[b]),q=M.add5H(R,g,x,S,Gm[b],Xt[b]),$=R|0,U=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),ee=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,Qe=o&i^o&c^i&c;g=m|0,w=y|0,m=h|0,y=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,q|0,$|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let I=M.add3L($,ee,Qe);n=M.add3H(I,q,U,D),o=I|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:y}=M.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:g,l:w}=M.add(this.Hh|0,this.Hl|0,g|0,w|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,y,g,w)}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 Jr=Mo(()=>new ka);var Ko={};xe(Ko,{abytes:()=>en,bitGet:()=>eg,bitLen:()=>Jm,bitMask:()=>Vn,bitSet:()=>tg,bytesToHex:()=>Bt,bytesToNumberBE:()=>Tt,bytesToNumberLE:()=>Jt,concatBytes:()=>Ct,createHmacDrbg:()=>Da,ensureBytes:()=>le,equalBytes:()=>Zm,hexToBytes:()=>br,hexToNumber:()=>La,isBytes:()=>Qt,numberToBytesBE:()=>er,numberToBytesLE:()=>Er,numberToHexUnpadded:()=>Lu,numberToVarBytesBE:()=>Xm,utf8ToBytes:()=>Qm,validateObject:()=>mt});var Nu=BigInt(0),Vo=BigInt(1),Wm=BigInt(2);function Qt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function en(r){if(!Qt(r))throw new Error("Uint8Array expected")}var jm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){en(r);let e="";for(let t=0;t<r.length;t++)e+=jm[r[t]];return e}function Lu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function La(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 Cu(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 br(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=Cu(r.charCodeAt(s)),a=Cu(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 Tt(r){return La(Bt(r))}function Jt(r){return en(r),La(Bt(Uint8Array.from(r).reverse()))}function er(r,e){return br(r.toString(16).padStart(e*2,"0"))}function Er(r,e){return er(r,e).reverse()}function Xm(r){return br(Lu(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=br(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 Ct(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];en(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 Zm(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 Qm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Jm(r){let e;for(e=0;r>Nu;r>>=Vo,e+=1);return e}function eg(r,e){return r>>BigInt(e)&Vo}function tg(r,e,t){return r|(t?Vo:Nu)<<BigInt(e)}var Vn=r=>(Wm<<BigInt(r-1))-Vo,Na=r=>new Uint8Array(r),ku=r=>Uint8Array.from(r);function Da(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=Na(r),o=Na(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Na())=>{o=a(ku([0]),l),n=a(),l.length!==0&&(o=a(ku([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 rg={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 mt(r,e,t={}){let n=(o,s,i)=>{let a=rg[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 ye=BigInt(0),re=BigInt(1),xr=BigInt(2),ng=BigInt(3),Pa=BigInt(4),Du=BigInt(5),Pu=BigInt(8),og=BigInt(9),sg=BigInt(16);function Q(r,e){let t=r%e;return t>=ye?t:e+t}function ig(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===re)return ye;let n=re;for(;e>ye;)e&re&&(n=n*r%t),r=r*r%t,e>>=re;return n}function ne(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function Ho(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Q(r,e),n=e,o=ye,s=re,i=re,a=ye;for(;t!==ye;){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!==re)throw new Error("invert: does not exist");return Q(o,e)}function ag(r){let e=(r-re)/xr,t,n,o;for(t=r-re,n=0;t%xr===ye;t/=xr,n++);for(o=xr;o<r&&ig(o,e,r)!==r-re;o++);if(n===1){let i=(r+re)/Pa;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)/xr;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,re<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function cg(r){if(r%Pa===ng){let e=(r+re)/Pa;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%Pu===Du){let e=(r-Du)/Pu;return function(n,o){let s=n.mul(o,xr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,xr),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%sg,ag(r)}var Ou=(r,e)=>(Q(r,e)&re)===re,lg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oa(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=lg.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function ug(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===re)return e;let n=r.ONE,o=e;for(;t>ye;)t&re&&(n=r.mul(n,o)),o=r.sqr(o),t>>=re;return n}function fg(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 Ua(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function qo(r,e,t=!1,n={}){if(r<=ye)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ua(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=cg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Vn(o),ZERO:ye,ONE:re,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ye<=c&&c<r},is0:c=>c===ye,isOdd:c=>(c&re)===re,neg:c=>Q(-c,r),eql:(c,u)=>c===u,sqr:c=>Q(c*c,r),add:(c,u)=>Q(c+u,r),sub:(c,u)=>Q(c-u,r),mul:(c,u)=>Q(c*u,r),pow:(c,u)=>ug(a,c,u),div:(c,u)=>Q(c*Ho(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ho(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>fg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?Er(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):Tt(c)}});return Object.freeze(a)}function Uu(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Mu(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 Ma(r){let e=Mu(r);return e+Math.ceil(e/2)}function Fu(r,e,t=!1){let n=r.length,o=Mu(e),s=Ma(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Tt(r):Jt(r),a=Q(i,e-re)+re;return t?Er(a,o):er(a,o)}var dg=BigInt(0),Fa=BigInt(1);function $o(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>dg;)s&Fa&&(i=i.add(a)),a=a.double(),s>>=Fa;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let p=1;p<a;p++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let d=0;d<a;d++){let m=d*c,y=Number(i&l);i>>=h,y>c&&(y-=p,i+=Fa);let g=m,w=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?f=f.add(t(b,s[g])):u=u.add(t(x,s[w]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Kn(r){return Oa(r.Fp),mt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ua(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var at=BigInt(0),Ge=BigInt(1),zo=BigInt(2),pg=BigInt(8),mg={zip215:!0};function gg(r){let e=Kn(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Go(r){let e=gg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=zo<<BigInt(a*8)-Ge,f=t.create,l=e.uvRatio||((B,A)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(A))}}catch{return{isValid:!1,value:at}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,A,k)=>{if(A.length||k)throw new Error("Contexts/pre-hash are not supported");return B}),d=B=>typeof B=="bigint"&&at<B,m=(B,A)=>d(B)&&d(A)&&B<A,y=B=>B===at||m(B,u);function g(B,A){if(m(B,A))return B;throw new Error(`Expected valid scalar < ${A}, got ${typeof B} ${B}`)}function w(B){return B===at?B:g(B,n)}let b=new Map;function x(B){if(!(B instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(A,k,P,O){if(this.ex=A,this.ey=k,this.ez=P,this.et=O,!y(A))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(P))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof v)throw new Error("extended point not allowed");let{x:k,y:P}=A||{};if(!y(k)||!y(P))throw new Error("invalid affine point");return new v(k,P,Ge,f(k*P))}static normalizeZ(A){let k=t.invertBatch(A.map(P=>P.ez));return A.map((P,O)=>P.toAffine(k[O])).map(v.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,b.delete(this)}assertValidity(){let{a:A,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:O,ez:V,et:K}=this,W=f(P*P),G=f(O*O),Y=f(V*V),de=f(Y*Y),ae=f(W*A),_e=f(Y*f(ae+G)),Ae=f(de+f(k*f(W*G)));if(_e!==Ae)throw new Error("bad point: equation left != right (1)");let ge=f(P*O),ke=f(V*K);if(ge!==ke)throw new Error("bad point: equation left != right (2)")}equals(A){x(A);let{ex:k,ey:P,ez:O}=this,{ex:V,ey:K,ez:W}=A,G=f(k*W),Y=f(V*O),de=f(P*W),ae=f(K*O);return G===Y&&de===ae}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:A}=e,{ex:k,ey:P,ez:O}=this,V=f(k*k),K=f(P*P),W=f(zo*f(O*O)),G=f(A*V),Y=k+P,de=f(f(Y*Y)-V-K),ae=G+K,_e=ae-W,Ae=G-K,ge=f(de*_e),ke=f(ae*Ae),_t=f(de*Ae),gr=f(_e*ae);return new v(ge,ke,gr,_t)}add(A){x(A);let{a:k,d:P}=e,{ex:O,ey:V,ez:K,et:W}=this,{ex:G,ey:Y,ez:de,et:ae}=A;if(k===BigInt(-1)){let Yl=f((V-O)*(Y+G)),Wl=f((V+O)*(Y-G)),Qi=f(Wl-Yl);if(Qi===at)return this.double();let jl=f(K*zo*ae),Xl=f(W*zo*de),Zl=Xl+jl,Ql=Wl+Yl,Jl=Xl-jl,ip=f(Zl*Qi),ap=f(Ql*Jl),cp=f(Zl*Jl),lp=f(Qi*Ql);return new v(ip,ap,lp,cp)}let _e=f(O*G),Ae=f(V*Y),ge=f(W*P*ae),ke=f(K*de),_t=f((O+V)*(G+Y)-_e-Ae),gr=ke-ge,Pn=ke+ge,Gl=f(Ae-k*_e),rp=f(_t*gr),np=f(Pn*Gl),op=f(_t*Gl),sp=f(gr*Pn);return new v(rp,np,sp,op)}subtract(A){return this.add(A.negate())}wNAF(A){return R.wNAFCached(this,b,A,v.normalizeZ)}multiply(A){let{p:k,f:P}=this.wNAF(g(A,n));return v.normalizeZ([k,P])[0]}multiplyUnsafe(A){let k=w(A);return k===at?_:this.equals(_)||k===Ge?this:this.equals(S)?this.wNAF(k).p:R.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(A){let{ex:k,ey:P,ez:O}=this,V=this.is0();A==null&&(A=V?pg:t.inv(O));let K=f(k*A),W=f(P*A),G=f(O*A);if(V)return{x:at,y:Ge};if(G!==Ge)throw new Error("invZ was invalid");return{x:K,y:W}}clearCofactor(){let{h:A}=e;return A===Ge?this:this.multiplyUnsafe(A)}static fromHex(A,k=!1){let{d:P,a:O}=e,V=t.BYTES;A=le("pointHex",A,V);let K=A.slice(),W=A[V-1];K[V-1]=W&-129;let G=Jt(K);G===at||(k?g(G,u):g(G,t.ORDER));let Y=f(G*G),de=f(Y-Ge),ae=f(P*Y-O),{isValid:_e,value:Ae}=l(de,ae);if(!_e)throw new Error("Point.fromHex: invalid y coordinate");let ge=(Ae&Ge)===Ge,ke=(W&128)!==0;if(!k&&Ae===at&&ke)throw new Error("Point.fromHex: x=0 and x_0=1");return ke!==ge&&(Ae=f(-Ae)),v.fromAffine({x:Ae,y:G})}static fromPrivateKey(A){return U(A).point}toRawBytes(){let{x:A,y:k}=this.toAffine(),P=Er(k,t.BYTES);return P[P.length-1]|=A&Ge?128:0,P}toHex(){return Bt(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ge,f(e.Gx*e.Gy)),v.ZERO=new v(at,Ge,Ge,at);let{BASE:S,ZERO:_}=v,R=$o(v,a*8);function q(B){return Q(B,n)}function $(B){return q(Jt(B))}function U(B){let A=a;B=le("private key",B,A);let k=le("hashed private key",s(B),2*A),P=p(k.slice(0,A)),O=k.slice(A,2*A),V=$(P),K=S.multiply(V),W=K.toRawBytes();return{head:P,prefix:O,scalar:V,point:K,pointBytes:W}}function ee(B){return U(B).pointBytes}function D(B=new Uint8Array,...A){let k=Ct(...A);return $(s(h(k,le("context",B),!!o)))}function Qe(B,A,k={}){B=le("message",B),o&&(B=o(B));let{prefix:P,scalar:O,pointBytes:V}=U(A),K=D(k.context,P,B),W=S.multiply(K).toRawBytes(),G=D(k.context,W,V,B),Y=q(K+G*O);w(Y);let de=Ct(W,Er(Y,t.BYTES));return le("result",de,a*2)}let I=mg;function N(B,A,k,P=I){let{context:O,zip215:V}=P,K=t.BYTES;B=le("signature",B,2*K),A=le("message",A),o&&(A=o(A));let W=Jt(B.slice(K,2*K)),G,Y,de;try{G=v.fromHex(k,V),Y=v.fromHex(B.slice(0,K),V),de=S.multiplyUnsafe(W)}catch{return!1}if(!V&&G.isSmallOrder())return!1;let ae=D(O,Y.toRawBytes(),G.toRawBytes(),A);return Y.add(G.multiplyUnsafe(ae)).subtract(de).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:Qe,verify:N,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(B=8,A=v.BASE){return A._setWindowSize(B),A.multiply(BigInt(3)),A}}}}var Ka=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Vu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ZE=BigInt(0),yg=BigInt(1),Va=BigInt(2),wg=BigInt(5),Ku=BigInt(10),bg=BigInt(20),Eg=BigInt(40),Hu=BigInt(80);function xg(r){let e=Ka,n=r*r%e*r%e,o=ne(n,Va,e)*n%e,s=ne(o,yg,e)*r%e,i=ne(s,wg,e)*s%e,a=ne(i,Ku,e)*i%e,c=ne(a,bg,e)*a%e,u=ne(c,Eg,e)*c%e,f=ne(u,Hu,e)*u%e,l=ne(f,Hu,e)*u%e,p=ne(l,Ku,e)*i%e;return{pow_p_5_8:ne(p,Va,e)*r%e,b2:n}}function vg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function _g(r,e){let t=Ka,n=Q(e*e*e,t),o=Q(n*n*e,t),s=xg(r*o).pow_p_5_8,i=Q(r*n*s,t),a=Q(e*i*i,t),c=i,u=Q(i*Vu,t),f=a===r,l=a===Q(-r,t),p=a===Q(-r*Vu,t);return f&&(i=c),(l||p)&&(i=u),Ou(i,t)&&(i=Q(-i,t)),{isValid:f||l,value:i}}var kt=qo(Ka,void 0,!0),Ha={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:kt,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Jr,randomBytes:Zr,adjustScalarBytes:vg,uvRatio:_g},tn=Go(Ha);function qu(r,e,t){if(e.length>255)throw new Error("Context is too big");return Uo(Ta("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var QE=Go({...Ha,domain:qu}),JE=Go({...Ha,domain:qu,prehash:Jr});var Ag=(kt.ORDER+BigInt(3))/BigInt(8),ex=kt.pow(Va,Ag),tx=kt.sqrt(kt.neg(kt.ONE)),rx=(kt.ORDER-BigInt(5))/BigInt(8),nx=BigInt(486662);var ox=Uu(kt,kt.neg(BigInt(486664)));var sx=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ix=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ax=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),cx=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var lx=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var rn=32,Nt=64,Yo=32;function $u(){let r=tn.utils.randomPrivateKey(),e=tn.getPublicKey(r);return{privateKey:Wu(r,e),publicKey:e}}function zu(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=tn.getPublicKey(e);return{privateKey:Wu(e,t),publicKey:t}}function Gu(r,e){let t=r.subarray(0,Yo);return tn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Yu(r,e,t){return tn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Wu(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 Me={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var qa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function ju(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=Me.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 y;if(p.length===0){y=await a.subtle.importKey("jwk",qa,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",qa,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,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),y={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",qa,{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 w=await a.subtle.decrypt(y,g,m);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function nn(r,e){let n=await ju().encrypt(r,e);return Mn.encode(n)}var Ig=Math.pow(2,7),Bg=Math.pow(2,14),Tg=Math.pow(2,21),$a=Math.pow(2,28),za=Math.pow(2,35),Ga=Math.pow(2,42),Ya=Math.pow(2,49),X=128,Le=127;function pe(r){if(r<Ig)return 1;if(r<Bg)return 2;if(r<Tg)return 3;if(r<$a)return 4;if(r<za)return 5;if(r<Ga)return 6;if(r<Ya)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wa(r,e,t=0){switch(pe(r)){case 8:e[t++]=r&255|X,r/=128;case 7:e[t++]=r&255|X,r/=128;case 6:e[t++]=r&255|X,r/=128;case 5:e[t++]=r&255|X,r/=128;case 4:e[t++]=r&255|X,r>>>=7;case 3:e[t++]=r&255|X,r>>>=7;case 2:e[t++]=r&255|X,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Cg(r,e,t=0){switch(pe(r)){case 8:e.set(t++,r&255|X),r/=128;case 7:e.set(t++,r&255|X),r/=128;case 6:e.set(t++,r&255|X),r/=128;case 5:e.set(t++,r&255|X),r/=128;case 4:e.set(t++,r&255|X),r>>>=7;case 3:e.set(t++,r&255|X),r>>>=7;case 2:e.set(t++,r&255|X),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ja(r,e){let t=r[e],n=0;if(n+=t&Le,t<X||(t=r[e+1],n+=(t&Le)<<7,t<X)||(t=r[e+2],n+=(t&Le)<<14,t<X)||(t=r[e+3],n+=(t&Le)<<21,t<X)||(t=r[e+4],n+=(t&Le)*$a,t<X)||(t=r[e+5],n+=(t&Le)*za,t<X)||(t=r[e+6],n+=(t&Le)*Ga,t<X)||(t=r[e+7],n+=(t&Le)*Ya,t<X))return n;throw new RangeError("Could not decode varint")}function kg(r,e){let t=r.get(e),n=0;if(n+=t&Le,t<X||(t=r.get(e+1),n+=(t&Le)<<7,t<X)||(t=r.get(e+2),n+=(t&Le)<<14,t<X)||(t=r.get(e+3),n+=(t&Le)<<21,t<X)||(t=r.get(e+4),n+=(t&Le)*$a,t<X)||(t=r.get(e+5),n+=(t&Le)*za,t<X)||(t=r.get(e+6),n+=(t&Le)*Ga,t<X)||(t=r.get(e+7),n+=(t&Le)*Ya,t<X))return n;throw new RangeError("Could not decode varint")}function De(r,e,t=0){return e==null&&(e=Ne(pe(r))),e instanceof Uint8Array?Wa(r,e,t):Cg(r,e,t)}function ct(r,e=0){return r instanceof Uint8Array?ja(r,e):kg(r,e)}var Xa=new Float32Array([-0]),tr=new Uint8Array(Xa.buffer);function Xu(r,e,t){Xa[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3]}function Zu(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],Xa[0]}var Za=new Float64Array([-0]),Pe=new Uint8Array(Za.buffer);function Qu(r,e,t){Za[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 Ju(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],Za[0]}var Ng=BigInt(Number.MAX_SAFE_INTEGER),Lg=BigInt(Number.MIN_SAFE_INTEGER),Ye=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 _r;if(e<Ng&&e>Lg)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>ef&&(o=0n,++n>ef&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return _r;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):_r}},_r=new Ye(0,0);_r.toBigInt=function(){return 0n};_r.zzEncode=_r.zzDecode=function(){return this};_r.length=function(){return 1};var ef=4294967296n;function tf(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 rf(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 Qa(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 lt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Wo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ja=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,lt(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 lt(this,4);return Wo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw lt(this,4);return Wo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw lt(this,4);let e=Zu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw lt(this,4);let e=Ju(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 lt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return rf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw lt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw lt(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 Ye(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 lt(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 lt(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 lt(this,8);let e=Wo(this.buf,this.pos+=4),t=Wo(this.buf,this.pos+=4);return new Ye(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=ja(this.buf,this.pos);return this.pos+=pe(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 ec(r){return new Ja(r instanceof Uint8Array?r:r.subarray())}function Fe(r,e,t){let n=ec(r);return e.decode(n,void 0,t)}function tc(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 Ar=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function rc(){}var oc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Dg=tc();function Pg(r){return globalThis.Buffer!=null?Ne(r):Dg(r)}var qn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ar(rc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ar(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new sc((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(jo,10,Ye.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ye.fromBigInt(e);return this._push(jo,t.length(),t)}uint64Number(e){return this._push(Wa,pe(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=Ye.fromBigInt(e).zzEncode();return this._push(jo,t.length(),t)}sint64Number(e){let t=Ye.fromNumber(e).zzEncode();return this._push(jo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nc,1,e?1:0)}fixed32(e){return this._push(Hn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ye.fromBigInt(e);return this._push(Hn,4,t.lo)._push(Hn,4,t.hi)}fixed64Number(e){let t=Ye.fromNumber(e);return this._push(Hn,4,t.lo)._push(Hn,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(Xu,4,e)}double(e){return this._push(Qu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(nc,1,0):this.uint32(t)._push(Ug,t,e)}string(e){let t=tf(e);return t!==0?this.uint32(t)._push(Qa,t,e):this._push(nc,1,0)}fork(){return this.states=new oc(this),this.head=this.tail=new Ar(rc,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 Ar(rc,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=Pg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function nc(r,e,t){e[t]=r&255}function Og(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var sc=class extends Ar{next;constructor(e,t){super(Og,e,t),this.next=void 0}};function jo(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 Hn(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 Ug(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(qn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Mg,e,r),this},qn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Fg,e,r),this});function Mg(r,e,t){e.set(r,t)}function Fg(r,e,t){r.length<40?Qa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function ic(){return new qn}function Ve(r,e){let t=ic();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var on;(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"})(on||(on={}));function Xo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function ac(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",on.VARINT,t,n)}function Ke(r,e){return Xo("message",on.LENGTH_DELIMITED,r,e)}var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(oe||(oe={}));var cc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(cc||(cc={}));(function(r){r.codec=()=>ac(cc)})(oe||(oe={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(gt||(gt={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(yt||(yt={}));var $n=class{_key;constructor(e){this._key=sn(e,rn)}verify(e,t){return Yu(this._key,t,e)}marshal(){return this._key}get bytes(){return gt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},Sr=class{_key;_publicKey;constructor(e,t){this._key=sn(e,Nt),this._publicKey=sn(t,rn)}sign(e){return Gu(this._key,e)}get public(){return new $n(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Yt.digest(this.public.bytes);return ie.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return nn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Vg(r){if(r.length>Nt){r=sn(r,Nt+rn);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Sr(n,o)}r=sn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(rn);return new Sr(e,t)}function Kg(r){return r=sn(r,rn),new $n(r)}async function Hg(){let{privateKey:r,publicKey:e}=$u();return new Sr(r,e)}async function of(r){let{privateKey:e,publicKey:t}=zu(r);return new Sr(e,t)}function sn(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 H(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bc={};xe(bc,{MAX_RSA_KEY_SIZE:()=>ro,RsaPrivateKey:()=>fn,RsaPublicKey:()=>to,fromJwk:()=>m0,generateKeyPair:()=>g0,unmarshalRsaPrivateKey:()=>yc,unmarshalRsaPublicKey:()=>p0});function wt(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Zr(r)}var sr={};xe(sr,{exportToPem:()=>l0,importFromPem:()=>u0,jwkToPkcs1:()=>s0,jwkToPkix:()=>a0,pkcs1ToJwk:()=>o0,pkixToJwk:()=>i0});var Qo=class extends jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Po(e);let n=jt(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 Wr(this),this.iHash.update(e),this}digestInto(e){Wr(this),Yr(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()}},zn=(r,e,t)=>new Qo(r,e).update(t).digest();zn.create=(r,e)=>new Qo(r,e);function qg(r,e,t,n){Po(r);let o=Ru({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Gr(s),Gr(i),Gr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=jt(e),u=jt(t),f=new Uint8Array(i),l=zn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function $g(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function uc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=qg(r,e,t,n),f,l=new Uint8Array(4),p=Xr(l),h=new Uint8Array(c.outputLen);for(let d=1,m=0;m<s;d++,m+=c.outputLen){let y=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),y.set(h.subarray(0,y.length)),await Su(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<y.length;g++)y[g]^=h[g]})}return $g(c,u,a,f,h)}var z=At(sf());function Rr(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 rr(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 hc(){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=Rr(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,Rr(s,8)-n}function af(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=rr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=rr(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 cf(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 $e(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 y1=Math.log(2);function rs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function dc(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 Yn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return dc(this.items)}},Gn=[new Uint8Array([1])],lf="0123456789";var ln="",ft=new ArrayBuffer(0),pc=new Uint8Array(0),Wn="EndOfContent",ff="OCTET STRING",hf="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):pc}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",ft)}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=ln,warnings:n=[],valueBeforeDecode:o=pc}={}){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):pc,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",ft}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=rr(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 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=Rr(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=Rr(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=rr(this.length,8);if(o.byteLength>127)return this.error="Too big length",ft;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 T={},Ie=class extends Dt{constructor({name:e=ln,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 Yn;t||df(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?ft: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 cf(t,n)}};Ie.NAME="BaseBlock";function df(r){if(r instanceof T.Constructed)for(let e of r.valueBlock.value)df(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ss=class extends Ie{constructor({value:e=ln,...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 pf,as=class extends Ie{constructor(e={}){super(e,is),this.idBlock.isConstructed=!1}};pf=as;T.Primitive=pf;as.NAME="PRIMITIVE";function Jg(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 Ie({},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=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=T.EndOfContent;break;case 1:c=T.Boolean;break;case 2:c=T.Integer;break;case 3:c=T.BitString;break;case 4:c=T.OctetString;break;case 5:c=T.Null;break;case 6:c=T.ObjectIdentifier;break;case 10:c=T.Enumerated;break;case 12:c=T.Utf8String;break;case 13:c=T.RelativeObjectIdentifier;break;case 14:c=T.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=T.Sequence;break;case 17:c=T.Set;break;case 18:c=T.NumericString;break;case 19:c=T.PrintableString;break;case 20:c=T.TeletexString;break;case 21:c=T.VideotexString;break;case 22:c=T.IA5String;break;case 23:c=T.UTCTime;break;case 24:c=T.GeneralizedTime;break;case 25:c=T.GraphicString;break;case 26:c=T.VisibleString;break;case 27:c=T.GeneralString;break;case 28:c=T.UniversalString;break;case 29:c=T.CharacterString;break;case 30:c=T.BmpString;break;case 31:c=T.DATE;break;case 32:c=T.TimeOfDay;break;case 33:c=T.DateTime;break;case 34:c=T.Duration;break;default:{let u=o.idBlock.isConstructed?new T.Constructed:new T.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?T.Constructed:T.Primitive}return o=Jg(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 un(r){if(!r.byteLength){let e=new Ie({},Oe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Vs(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function e0(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(;e0(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===Wn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Wn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Yn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ft: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 mf,nr=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 ap=Object.create;var Bo=Object.defineProperty;var cp=Object.getOwnPropertyDescriptor;var lp=Object.getOwnPropertyNames;var up=Object.getPrototypeOf,fp=Object.prototype.hasOwnProperty;var et=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)Bo(r,t,{get:e[t],enumerable:!0})},Zl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lp(e))!fp.call(r,o)&&o!==t&&Bo(r,o,{get:()=>e[o],enumerable:!(n=cp(e,o))||n.enumerable});return r};var St=(r,e,t)=>(t=r!=null?ap(up(r)):{},Zl(e||!r||!r.__esModule?Bo(t,"default",{value:r,enumerable:!0}):t,r)),hp=r=>Zl(Bo({},"__esModule",{value:!0}),r);var tf=et(on=>{"use strict";var Hg="[object ArrayBuffer]",Dt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Hg}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}},ic="string",qg=/^[0-9a-f]+$/i,$g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,zg=/^[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=Dt.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=Dt.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===ic&&qg.test(e)}static isBase64(e){return typeof e===ic&&$g.test(e)}static isBase64Url(e){return typeof e===ic&&zg.test(e)}static ToString(e,t="utf8"){let n=Dt.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=Dt.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 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 Zo.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=Dt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Dt.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,"")||""}};Qo.DEFAULT_UTF8_ENCODING="utf8";function Gg(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 Yg(...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 Wg(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=Dt;on.Convert=Qo;on.assign=Gg;on.combine=Yg;on.isEqual=Wg});var fh=et((ev,uh)=>{var un=1e3,fn=un*60,hn=fn*60,Ir=hn*24,I0=Ir*7,B0=Ir*365.25;uh.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return T0(r);if(t==="number"&&isFinite(r))return e.long?k0(r):C0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function T0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*B0;case"weeks":case"week":case"w":return t*I0;case"days":case"day":case"d":return t*Ir;case"hours":case"hour":case"hrs":case"hr":case"h":return t*hn;case"minutes":case"minute":case"mins":case"min":case"m":return t*fn;case"seconds":case"second":case"secs":case"sec":case"s":return t*un;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function C0(r){var e=Math.abs(r);return e>=Ir?Math.round(r/Ir)+"d":e>=hn?Math.round(r/hn)+"h":e>=fn?Math.round(r/fn)+"m":e>=un?Math.round(r/un)+"s":r+"ms"}function k0(r){var e=Math.abs(r);return e>=Ir?Vs(r,e,Ir,"day"):e>=hn?Vs(r,e,hn,"hour"):e>=fn?Vs(r,e,fn,"minute"):e>=un?Vs(r,e,un,"second"):r+" ms"}function Vs(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var dh=et((tv,hh)=>{function N0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=fh(),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(...y){if(!m.enabled)return;let g=m,w=Number(new Date),b=w-(l||w);g.diff=b,g.prev=l,g.curr=w,l=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(S,_)=>{if(S==="%%")return"%";x++;let R=t.formatters[_];if(typeof R=="function"){let q=y[x];S=R.call(g,q),y.splice(x,1),x--}return S}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}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:y=>{p=y}}),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.slice(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.enable(t.load()),t}hh.exports=N0});var ph=et((je,Ks)=>{je.formatArgs=D0;je.save=P0;je.load=O0;je.useColors=L0;je.storage=U0();je.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();je.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function L0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function D0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ks.exports.humanize(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)}je.log=console.debug||console.log||(()=>{});function P0(r){try{r?je.storage.setItem("debug",r):je.storage.removeItem("debug")}catch{}}function O0(){let r;try{r=je.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function U0(){try{return localStorage}catch{}}Ks.exports=dh()(je);var{formatters:M0}=Ks.exports;M0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var bh=et((ao,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,y=h.length-m,g=d,w=0,b=3432918353,x=461845907,v=0;v<y;v=v+4)w=h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24,w=o(w,b),w=s(w,15),w=o(w,x),g^=w,g=s(g,13),g=o(g,5)+3864292196;switch(w=0,m){case 3:w^=h[v+2]<<16;case 2:w^=h[v+1]<<8;case 1:w^=h[v],w=o(w,b),w=s(w,15),w=o(w,x),g^=w}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,y=h.length-m,g=d,w=d,b=d,x=d,v=0,S=0,_=0,R=0,q=597399067,$=2869860233,U=951274213,ee=2716044179,D=0;D<y;D=D+16)v=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,S=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,R=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,v=o(v,q),v=s(v,15),v=o(v,$),g^=v,g=s(g,19),g+=w,g=o(g,5)+1444728091,S=o(S,$),S=s(S,16),S=o(S,U),w^=S,w=s(w,17),w+=b,w=o(w,5)+197830471,_=o(_,U),_=s(_,17),_=o(_,ee),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,R=o(R,ee),R=s(R,18),R=o(R,q),x^=R,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(v=0,S=0,_=0,R=0,m){case 15:R^=h[D+14]<<16;case 14:R^=h[D+13]<<8;case 13:R^=h[D+12],R=o(R,ee),R=s(R,18),R=o(R,q),x^=R;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,U),_=s(_,17),_=o(_,ee),b^=_;case 8:S^=h[D+7]<<24;case 7:S^=h[D+6]<<16;case 6:S^=h[D+5]<<8;case 5:S^=h[D+4],S=o(S,$),S=s(S,16),S=o(S,U),w^=S;case 4:v^=h[D+3]<<24;case 3:v^=h[D+2]<<16;case 2:v^=h[D+1]<<8;case 1:v^=h[D],v=o(v,q),v=s(v,15),v=o(v,$),g^=v}return g^=h.length,w^=h.length,b^=h.length,x^=h.length,g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,g=i(g),w=i(w),b=i(b),x=i(x),g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>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,y=h.length-m,g=[0,d],w=[0,d],b=[0,0],x=[0,0],v=[2277735313,289559509],S=[1291169091,658871167],_=0;_<y;_=_+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,v),b=u(b,31),b=c(b,S),g=l(g,b),g=u(g,27),g=a(g,w),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,S),x=u(x,33),x=c(x,v),w=l(w,x),w=u(w,31),w=a(w,g),w=a(c(w,[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,S),x=u(x,33),x=c(x,v),w=l(w,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,v),b=u(b,31),b=c(b,S),g=l(g,b)}return g=l(g,[0,h.length]),w=l(w,[0,h.length]),g=a(g,w),w=a(w,g),g=p(g),w=p(w),g=a(g,w),w=a(w,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)},typeof ao<"u"?(typeof qs<"u"&&qs.exports&&(ao=qs.exports=t),ao.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)})(ao)});var xh=et((Rv,Eh)=>{Eh.exports=bh()});var zh=et((r2,$c)=>{"use strict";var wy=Object.prototype.hasOwnProperty,$e="~";function po(){}Object.create&&(po.prototype=Object.create(null),new po().__proto__||($e=!1));function by(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function $h(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=$e?$e+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 Xs(r,e){--r._eventsCount===0?r._events=new po:delete r._events[e]}function Me(){this._events=new po,this._eventsCount=0}Me.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)wy.call(t,n)&&e.push($e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Me.prototype.listeners=function(e){var t=$e?$e+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};Me.prototype.listenerCount=function(e){var t=$e?$e+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Me.prototype.emit=function(e,t,n,o,s,i){var a=$e?$e+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};Me.prototype.on=function(e,t,n){return $h(this,e,t,n,!1)};Me.prototype.once=function(e,t,n){return $h(this,e,t,n,!0)};Me.prototype.removeListener=function(e,t,n,o){var s=$e?$e+e:e;if(!this._events[s])return this;if(!t)return Xs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Xs(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:Xs(this,s)}return this};Me.prototype.removeAllListeners=function(e){var t;return e?(t=$e?$e+e:e,this._events[t]&&Xs(this,t)):(this._events=new po,this._eventsCount=0),this};Me.prototype.off=Me.prototype.removeListener;Me.prototype.addListener=Me.prototype.on;Me.prefixed=$e;Me.EventEmitter=Me;typeof $c<"u"&&($c.exports=Me)});var al=et((xS,sd)=>{"use strict";function od(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Oy(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 od(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),od(new o,t)}}sd.exports=Oy});var fd=et(wo=>{(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}(),wo.ip2long=i,wo.long2ip=a,wo.Netmask=r}).call(wo)});var Ad=et((TR,_d)=>{_d.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 Td=et((YR,Bd)=>{"use strict";Bd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Pd=et((Ld,Dd)=>{"use strict";var yi=Td(),{hasOwnProperty:kd}=Object.prototype,{propertyIsEnumerable:aw}=Object,In=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),cw=Ld,Cd={concatArrays:!1,ignoreUndefined:!1},wi=r=>{let e=[];for(let t in r)kd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)aw.call(r,n)&&e.push(n)}return e};function Bn(r){return Array.isArray(r)?lw(r):yi(r)?uw(r):r}function lw(r){let e=r.slice(0,0);return wi(r).forEach(t=>{In(e,t,Bn(r[t]))}),e}function uw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return wi(r).forEach(t=>{In(e,t,Bn(r[t]))}),e}var Nd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?In(r,o,El(r[o],e[o],n)):In(r,o,Bn(e[o])))}),r),fw=(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++)kd.call(s,a)&&(i.push(String(a)),s===r?In(n,o++,s[a]):In(n,o++,Bn(s[a])));n=Nd(n,s,wi(s).filter(a=>!i.includes(a)),t)}),n};function El(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?fw(r,e,t):!yi(e)||!yi(r)?Bn(e):Nd(r,e,wi(e),t)}Dd.exports=function(...r){let e=El(Bn(Cd),this!==cw&&this||{},Cd),t={_:{}};for(let n of r)if(n!==void 0){if(!yi(n))throw new TypeError("`"+n+"` is not an Option Object");t=El(t,{_:n},e)}return t._}});var Ow={};ve(Ow,{createLibp2p:()=>Pw});var Ql=Symbol.for("@libp2p/connection");var Zi=Symbol.for("@libp2p/content-routing");var Qi=Symbol.for("@libp2p/peer-discovery");var To=Symbol.for("@libp2p/peer-id");function Co(r){return r!=null&&!!r[To]}var Ji=Symbol.for("@libp2p/peer-routing");var Jl="keep-alive";var $w=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"},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 fe=(r,...e)=>{try{[...e]}catch{}};var Rt=class extends EventTarget{#e=new Map;constructor(){super(),fe(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 ta(e,t))}},ea=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ta=globalThis.CustomEvent??ea;function eu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var ra=Symbol.for("@libp2p/service-capabilities"),na=Symbol.for("@libp2p/service-dependencies");var oc={};ve(oc,{Ed25519PrivateKey:()=>Ar,Ed25519PublicKey:()=>qn,generateKeyPair:()=>Fg,generateKeyPairFromSeed:()=>ef,unmarshalEd25519PrivateKey:()=>Ug,unmarshalEd25519PublicKey:()=>Mg});var ca={};ve(ca,{base58btc:()=>ie,base58flickr:()=>wp});var Eb=new Uint8Array(0);function tu(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 It(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 ru(r){return new TextEncoder().encode(r)}function nu(r){return new TextDecoder().decode(r)}function dp(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,y=0,g=0,w=d.length;g!==w&&d[g]===0;)g++,m++;for(var b=(w-g)*f+1>>>0,x=new Uint8Array(b);g!==w;){for(var v=d[g],S=0,_=b-1;(v!==0||S<y)&&_!==-1;_--,S++)v+=256*x[_]>>>0,x[_]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=S,g++}for(var R=b-y;R!==b&&x[R]===0;)R++;for(var q=c.repeat(m);R<b;++R)q+=r.charAt(x[R]);return q}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 y=0,g=0;d[m]===c;)y++,m++;for(var w=(d.length-m)*u+1>>>0,b=new Uint8Array(w);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=w-1;(x!==0||v<g)&&S!==-1;S--,v++)x+=a*b[S]>>>0,b[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,m++}if(d[m]!==" "){for(var _=w-g;_!==w&&b[_]===0;)_++;for(var R=new Uint8Array(y+(w-_)),q=y;_!==w;)R[q++]=b[_++];return R}}}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 pp=dp,mp=pp,su=mp;var oa=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")}},sa=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 iu(this,e)}},ia=class{decoders;constructor(e){this.decoders=e}or(e){return iu(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 iu(r,e){return new ia({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var aa=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 oa(e,t,n),this.decoder=new sa(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 aa(r,e,t,n)}function Yt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=su(t,r);return Kr({prefix:e,name:r,encode:n,decode:s=>It(o(s))})}function gp(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 yp(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 yp(o,n,t)},decode(o){return gp(o,n,t,r)}})}var ie=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wp=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ua={};ve(ua,{identity:()=>Bt});var bp=lu,au=128,Ep=127,xp=~Ep,vp=Math.pow(2,31);function lu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vp;)e[t++]=r&255|au,r/=128;for(;r&xp;)e[t++]=r&255|au,r>>>=7;return e[t]=r|0,lu.bytes=t-n+1,e}var _p=la,Ap=128,cu=127;function la(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw la.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&cu)<<o:(i&cu)*Math.pow(2,o),o+=7}while(i>=Ap);return la.bytes=s-n,t}var Sp=Math.pow(2,7),Rp=Math.pow(2,14),Ip=Math.pow(2,21),Bp=Math.pow(2,28),Tp=Math.pow(2,35),Cp=Math.pow(2,42),kp=Math.pow(2,49),Np=Math.pow(2,56),Lp=Math.pow(2,63),Dp=function(r){return r<Sp?1:r<Rp?2:r<Ip?3:r<Bp?4:r<Tp?5:r<Cp?6:r<kp?7:r<Np?8:r<Lp?9:10},Pp={encode:bp,decode:_p,encodingLength:Dp},Op=Pp,Dn=Op;function Pn(r,e=0){return[Dn.decode(r,e),Dn.decode.bytes]}function Hr(r,e,t=0){return Dn.encode(r,e,t),e}function qr(r){return Dn.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=qr(r),o=n+qr(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new $r(r,t,e,s)}function gr(r){let e=It(r),[t,n]=Pn(e),[o,s]=Pn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new $r(t,o,i,e)}function uu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tu(r.bytes,t.bytes)}}var $r=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var fu=0,Up="identity",hu=It;function Mp(r){return mt(fu,hu(r))}var Bt={code:fu,name:Up,encode:hu,digest:Mp};var da={};ve(da,{sha256:()=>Re,sha512:()=>Fp});function ha({name:r,code:e,encode:t}){return new fa(r,e,t)}var fa=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 pu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=ha({name:"sha2-256",code:18,encode:pu("SHA-256")}),Fp=ha({name:"sha2-512",code:19,encode:pu("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 it(r=0){return new Uint8Array(r)}function Le(r=0){return new Uint8Array(r)}function Ie(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var pa={};ve(pa,{base10:()=>Vp});var Vp=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var ma={};ve(ma,{base16:()=>Kp,base16upper:()=>Hp});var Kp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Hp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ga={};ve(ga,{base2:()=>qp});var qp=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ya={};ve(ya,{base256emoji:()=>Wp});var mu=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}"),$p=mu.reduce((r,e,t)=>(r[t]=e,r),[]),zp=mu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Gp(r){return r.reduce((e,t)=>(e+=$p[t],e),"")}function Yp(r){let e=[];for(let t of r){let n=zp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Wp=Kr({prefix:"\u{1F680}",name:"base256emoji",encode:Gp,decode:Yp});var wa={};ve(wa,{base32:()=>Ge,base32hex:()=>Qp,base32hexpad:()=>em,base32hexpadupper:()=>tm,base32hexupper:()=>Jp,base32pad:()=>Xp,base32padupper:()=>Zp,base32upper:()=>jp,base32z:()=>rm});var Ge=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jp=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xp=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zp=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qp=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jp=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),em=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),tm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),rm=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ba={};ve(ba,{base36:()=>nm,base36upper:()=>om});var nm=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),om=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xa={};ve(xa,{base64:()=>On,base64pad:()=>sm,base64url:()=>Ea,base64urlpad:()=>im});var On=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ea=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),im=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var va={};ve(va,{base8:()=>am});var am=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _a={};ve(_a,{identity:()=>cm});var cm=Kr({prefix:"\0",name:"identity",encode:r=>nu(r),decode:r=>ru(r)});var Wb=new TextEncoder,jb=new TextDecoder;function gu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return hm(t,Aa(r),e??ie.encoder);default:return dm(t,Aa(r),e??Ge.encoder)}}var yu=new WeakMap;function Aa(r){let e=yu.get(r);if(e==null){let t=new Map;return yu.set(r,t),t}return e}var tt=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!==Un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pm)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&&uu(e.multihash,n.multihash)}toString(e){return gu(this,e)}toJSON(){return{"/":gu(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??wu(n,o,s.bytes))}else if(t[mm]===!0){let{version:n,multihash:o,code:s}=t,i=gr(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!==Un)throw new Error(`Version 0 CID must use dag-pb (code: ${Un}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=wu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Un,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=It(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 $r(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]=Pn(e.subarray(t));return t+=p,l},o=n(),s=Un;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]=fm(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 Aa(s).set(n,e),s}};function fm(r,e){switch(r[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${r}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.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 hm(r,e,t){let{prefix:n}=t;if(n!==ie.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 dm(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 Un=112,pm=18;function wu(r,e,t){let n=qr(r),o=n+qr(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var mm=Symbol.for("@ipld/js-cid/CID");var Wt={..._a,...ga,...va,...pa,...ma,...wa,...ba,...ca,...xa,...ya},fE={...da,...ua};function Eu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var bu=Eu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Sa=Eu("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=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),gm={utf8:bu,"utf-8":bu,hex:Wt.base16,latin1:Sa,ascii:Sa,binary:Sa,...Wt},Do=gm;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 rt(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 ym(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...e){if(!ym(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 xu(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),at=(r,e)=>r<<32-e|r>>>e;var SE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var wm=async()=>{};async function vu(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 wm(),n+=s)}}function _u(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function jt(r){return typeof r=="string"&&(r=_u(r)),Gr(r),r}function Ra(...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()}},bm={}.toString;function Au(r,e){if(e!==void 0&&bm.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(jt(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 Em(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 Su=(r,e,t)=>r&e^~r&t,Ru=(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=jt(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),xu(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;Em(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),Ia=BigInt(32);function Iu(r,e=!1){return e?{h:Number(r&Mo),l:Number(r>>Ia&Mo)}:{h:Number(r>>Ia&Mo)|0,l:Number(r&Mo)|0}}function xm(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}=Iu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var vm=(r,e)=>BigInt(r>>>0)<<Ia|BigInt(e>>>0),_m=(r,e,t)=>r>>>t,Am=(r,e,t)=>r<<32-t|e>>>t,Sm=(r,e,t)=>r>>>t|e<<32-t,Rm=(r,e,t)=>r<<32-t|e>>>t,Im=(r,e,t)=>r<<64-t|e>>>t-32,Bm=(r,e,t)=>r>>>t-32|e<<64-t,Tm=(r,e)=>e,Cm=(r,e)=>r,km=(r,e,t)=>r<<t|e>>>32-t,Nm=(r,e,t)=>e<<t|r>>>32-t,Lm=(r,e,t)=>e<<t-32|r>>>64-t,Dm=(r,e,t)=>r<<t-32|e>>>64-t;function Pm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Om=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Um=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Mm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Fm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Vm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Km=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Hm={fromBig:Iu,split:xm,toBig:vm,shrSH:_m,shrSL:Am,rotrSH:Sm,rotrSL:Rm,rotrBH:Im,rotrBL:Bm,rotr32H:Tm,rotr32L:Cm,rotlSH:km,rotlSL:Nm,rotlBH:Lm,rotlBL:Dm,add:Pm,add3L:Om,add3H:Um,add4L:Mm,add4H:Fm,add5H:Km,add5L:Vm},M=Hm;var[qm,$m]=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))),Xt=new Uint32Array(80),Zt=new Uint32Array(80),Ba=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:y}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y){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=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)Xt[b]=e.getUint32(t),Zt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Xt[b-15]|0,v=Zt[b-15]|0,S=M.rotrSH(x,v,1)^M.rotrSH(x,v,8)^M.shrSH(x,v,7),_=M.rotrSL(x,v,1)^M.rotrSL(x,v,8)^M.shrSL(x,v,7),R=Xt[b-2]|0,q=Zt[b-2]|0,$=M.rotrSH(R,q,19)^M.rotrBH(R,q,61)^M.shrSH(R,q,6),U=M.rotrSL(R,q,19)^M.rotrBL(R,q,61)^M.shrSL(R,q,6),ee=M.add4L(_,U,Zt[b-7],Zt[b-16]),D=M.add4H(ee,S,$,Xt[b-7],Xt[b-16]);Xt[b]=D|0,Zt[b]=ee|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:y,Hh:g,Hl:w}=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),v=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),S=l&h^~l&m,_=p&d^~p&y,R=M.add5L(w,v,_,$m[b],Zt[b]),q=M.add5H(R,g,x,S,qm[b],Xt[b]),$=R|0,U=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),ee=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,Je=o&i^o&c^i&c;g=m|0,w=y|0,m=h|0,y=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,q|0,$|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let I=M.add3L($,ee,Je);n=M.add3H(I,q,U,D),o=I|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:y}=M.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:g,l:w}=M.add(this.Hh|0,this.Hl|0,g|0,w|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,y,g,w)}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 Mn=Uo(()=>new Ba);var Vo={};ve(Vo,{abytes:()=>Qr,bitGet:()=>Zm,bitLen:()=>Xm,bitMask:()=>Fn,bitSet:()=>Qm,bytesToHex:()=>Ct,bytesToNumberBE:()=>kt,bytesToNumberLE:()=>Jt,concatBytes:()=>Nt,createHmacDrbg:()=>ka,ensureBytes:()=>le,equalBytes:()=>Wm,hexToBytes:()=>wr,hexToNumber:()=>Ca,isBytes:()=>Qt,numberToBytesBE:()=>er,numberToBytesLE:()=>br,numberToHexUnpadded:()=>ku,numberToVarBytesBE:()=>Ym,utf8ToBytes:()=>jm,validateObject:()=>gt});var Cu=BigInt(0),Fo=BigInt(1),zm=BigInt(2);function Qt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qr(r){if(!Qt(r))throw new Error("Uint8Array expected")}var Gm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ct(r){Qr(r);let e="";for(let t=0;t<r.length;t++)e+=Gm[r[t]];return e}function ku(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ca(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 Bu(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 wr(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=Bu(r.charCodeAt(s)),a=Bu(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 kt(r){return Ca(Ct(r))}function Jt(r){return Qr(r),Ca(Ct(Uint8Array.from(r).reverse()))}function er(r,e){return wr(r.toString(16).padStart(e*2,"0"))}function br(r,e){return er(r,e).reverse()}function Ym(r){return wr(ku(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=wr(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 Nt(...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 Wm(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 jm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Xm(r){let e;for(e=0;r>Cu;r>>=Fo,e+=1);return e}function Zm(r,e){return r>>BigInt(e)&Fo}function Qm(r,e,t){return r|(t?Fo:Cu)<<BigInt(e)}var Fn=r=>(zm<<BigInt(r-1))-Fo,Ta=r=>new Uint8Array(r),Tu=r=>Uint8Array.from(r);function ka(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=Ta(r),o=Ta(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ta())=>{o=a(Tu([0]),l),n=a(),l.length!==0&&(o=a(Tu([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 Nt(...p)};return(l,p)=>{i(),c(l);let h;for(;!(h=p(u()));)c();return i(),h}}var Jm={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=Jm[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 we=BigInt(0),re=BigInt(1),Er=BigInt(2),eg=BigInt(3),Na=BigInt(4),Nu=BigInt(5),Lu=BigInt(8),tg=BigInt(9),rg=BigInt(16);function Q(r,e){let t=r%e;return t>=we?t:e+t}function ng(r,e,t){if(t<=we||e<we)throw new Error("Expected power/modulo > 0");if(t===re)return we;let n=re;for(;e>we;)e&re&&(n=n*r%t),r=r*r%t,e>>=re;return n}function ne(r,e,t){let n=r;for(;e-- >we;)n*=n,n%=t;return n}function Ko(r,e){if(r===we||e<=we)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Q(r,e),n=e,o=we,s=re,i=re,a=we;for(;t!==we;){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!==re)throw new Error("invert: does not exist");return Q(o,e)}function og(r){let e=(r-re)/Er,t,n,o;for(t=r-re,n=0;t%Er===we;t/=Er,n++);for(o=Er;o<r&&ng(o,e,r)!==r-re;o++);if(n===1){let i=(r+re)/Na;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)/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,re<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function sg(r){if(r%Na===eg){let e=(r+re)/Na;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%Lu===Nu){let e=(r-Nu)/Lu;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%rg,og(r)}var Du=(r,e)=>(Q(r,e)&re)===re,ig=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function La(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=ig.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function ag(r,e,t){if(t<we)throw new Error("Expected power > 0");if(t===we)return r.ONE;if(t===re)return e;let n=r.ONE,o=e;for(;t>we;)t&re&&(n=r.mul(n,o)),o=r.sqr(o),t>>=re;return n}function cg(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 Da(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<=we)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Da(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=sg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Fn(o),ZERO:we,ONE:re,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return we<=c&&c<r},is0:c=>c===we,isOdd:c=>(c&re)===re,neg:c=>Q(-c,r),eql:(c,u)=>c===u,sqr:c=>Q(c*c,r),add:(c,u)=>Q(c+u,r),sub:(c,u)=>Q(c-u,r),mul:(c,u)=>Q(c*u,r),pow:(c,u)=>ag(a,c,u),div:(c,u)=>Q(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=>cg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?br(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):kt(c)}});return Object.freeze(a)}function Pu(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 Pa(r){let e=Pu(r);return e+Math.ceil(e/2)}function Ou(r,e,t=!1){let n=r.length,o=Pu(e),s=Pa(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?kt(r):Jt(r),a=Q(i,e-re)+re;return t?br(a,o):er(a,o)}var ug=BigInt(0),Oa=BigInt(1);function qo(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>ug;)s&Oa&&(i=i.add(a)),a=a.double(),s>>=Oa;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let p=1;p<a;p++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let d=0;d<a;d++){let m=d*c,y=Number(i&l);i>>=h,y>c&&(y-=p,i+=Oa);let g=m,w=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?f=f.add(t(b,s[g])):u=u.add(t(x,s[w]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Vn(r){return La(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Da(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),Ye=BigInt(1),$o=BigInt(2),fg=BigInt(8),hg={zip215:!0};function dg(r){let e=Vn(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Uu(r){let e=dg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=$o<<BigInt(a*8)-Ye,f=t.create,l=e.uvRatio||((B,A)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(A))}}catch{return{isValid:!1,value:ct}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,A,k)=>{if(A.length||k)throw new Error("Contexts/pre-hash are not supported");return B}),d=B=>typeof B=="bigint"&&ct<B,m=(B,A)=>d(B)&&d(A)&&B<A,y=B=>B===ct||m(B,u);function g(B,A){if(m(B,A))return B;throw new Error(`Expected valid scalar < ${A}, got ${typeof B} ${B}`)}function w(B){return B===ct?B:g(B,n)}let b=new Map;function x(B){if(!(B instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(A,k,P,O){if(this.ex=A,this.ey=k,this.ez=P,this.et=O,!y(A))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(P))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof v)throw new Error("extended point not allowed");let{x:k,y:P}=A||{};if(!y(k)||!y(P))throw new Error("invalid affine point");return new v(k,P,Ye,f(k*P))}static normalizeZ(A){let k=t.invertBatch(A.map(P=>P.ez));return A.map((P,O)=>P.toAffine(k[O])).map(v.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,b.delete(this)}assertValidity(){let{a:A,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:O,ez:K,et:H}=this,W=f(P*P),G=f(O*O),Y=f(K*K),pe=f(Y*Y),ae=f(W*A),Ae=f(Y*f(ae+G)),Se=f(pe+f(k*f(W*G)));if(Ae!==Se)throw new Error("bad point: equation left != right (1)");let ye=f(P*O),Ne=f(K*H);if(ye!==Ne)throw new Error("bad point: equation left != right (2)")}equals(A){x(A);let{ex:k,ey:P,ez:O}=this,{ex:K,ey:H,ez:W}=A,G=f(k*W),Y=f(K*O),pe=f(P*W),ae=f(H*O);return G===Y&&pe===ae}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:A}=e,{ex:k,ey:P,ez:O}=this,K=f(k*k),H=f(P*P),W=f($o*f(O*O)),G=f(A*K),Y=k+P,pe=f(f(Y*Y)-K-H),ae=G+H,Ae=ae-W,Se=G-H,ye=f(pe*Ae),Ne=f(ae*Se),At=f(pe*Se),mr=f(Ae*ae);return new v(ye,Ne,mr,At)}add(A){x(A);let{a:k,d:P}=e,{ex:O,ey:K,ez:H,et:W}=this,{ex:G,ey:Y,ez:pe,et:ae}=A;if(k===BigInt(-1)){let $l=f((K-O)*(Y+G)),zl=f((K+O)*(Y-G)),Xi=f(zl-$l);if(Xi===ct)return this.double();let Gl=f(H*$o*ae),Yl=f(W*$o*pe),Wl=Yl+Gl,jl=zl+$l,Xl=Yl-Gl,np=f(Wl*Xi),op=f(jl*Xl),sp=f(Wl*Xl),ip=f(Xi*jl);return new v(np,op,ip,sp)}let Ae=f(O*G),Se=f(K*Y),ye=f(W*P*ae),Ne=f(H*pe),At=f((O+K)*(G+Y)-Ae-Se),mr=Ne-ye,Ln=Ne+ye,ql=f(Se-k*Ae),Jd=f(At*mr),ep=f(Ln*ql),tp=f(At*ql),rp=f(mr*Ln);return new v(Jd,ep,rp,tp)}subtract(A){return this.add(A.negate())}wNAF(A){return R.wNAFCached(this,b,A,v.normalizeZ)}multiply(A){let{p:k,f:P}=this.wNAF(g(A,n));return v.normalizeZ([k,P])[0]}multiplyUnsafe(A){let k=w(A);return k===ct?_:this.equals(_)||k===Ye?this:this.equals(S)?this.wNAF(k).p:R.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(A){let{ex:k,ey:P,ez:O}=this,K=this.is0();A==null&&(A=K?fg:t.inv(O));let H=f(k*A),W=f(P*A),G=f(O*A);if(K)return{x:ct,y:Ye};if(G!==Ye)throw new Error("invZ was invalid");return{x:H,y:W}}clearCofactor(){let{h:A}=e;return A===Ye?this:this.multiplyUnsafe(A)}static fromHex(A,k=!1){let{d:P,a:O}=e,K=t.BYTES;A=le("pointHex",A,K);let H=A.slice(),W=A[K-1];H[K-1]=W&-129;let G=Jt(H);G===ct||(k?g(G,u):g(G,t.ORDER));let Y=f(G*G),pe=f(Y-Ye),ae=f(P*Y-O),{isValid:Ae,value:Se}=l(pe,ae);if(!Ae)throw new Error("Point.fromHex: invalid y coordinate");let ye=(Se&Ye)===Ye,Ne=(W&128)!==0;if(!k&&Se===ct&&Ne)throw new Error("Point.fromHex: x=0 and x_0=1");return Ne!==ye&&(Se=f(-Se)),v.fromAffine({x:Se,y:G})}static fromPrivateKey(A){return U(A).point}toRawBytes(){let{x:A,y:k}=this.toAffine(),P=br(k,t.BYTES);return P[P.length-1]|=A&Ye?128:0,P}toHex(){return Ct(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ye,f(e.Gx*e.Gy)),v.ZERO=new v(ct,Ye,Ye,ct);let{BASE:S,ZERO:_}=v,R=qo(v,a*8);function q(B){return Q(B,n)}function $(B){return q(Jt(B))}function U(B){let A=a;B=le("private key",B,A);let k=le("hashed private key",s(B),2*A),P=p(k.slice(0,A)),O=k.slice(A,2*A),K=$(P),H=S.multiply(K),W=H.toRawBytes();return{head:P,prefix:O,scalar:K,point:H,pointBytes:W}}function ee(B){return U(B).pointBytes}function D(B=new Uint8Array,...A){let k=Nt(...A);return $(s(h(k,le("context",B),!!o)))}function Je(B,A,k={}){B=le("message",B),o&&(B=o(B));let{prefix:P,scalar:O,pointBytes:K}=U(A),H=D(k.context,P,B),W=S.multiply(H).toRawBytes(),G=D(k.context,W,K,B),Y=q(H+G*O);w(Y);let pe=Nt(W,br(Y,t.BYTES));return le("result",pe,a*2)}let I=hg;function N(B,A,k,P=I){let{context:O,zip215:K}=P,H=t.BYTES;B=le("signature",B,2*H),A=le("message",A),o&&(A=o(A));let W=Jt(B.slice(H,2*H)),G,Y,pe;try{G=v.fromHex(k,K),Y=v.fromHex(B.slice(0,H),K),pe=S.multiplyUnsafe(W)}catch{return!1}if(!K&&G.isSmallOrder())return!1;let ae=D(O,Y.toRawBytes(),G.toRawBytes(),A);return Y.add(G.multiplyUnsafe(ae)).subtract(pe).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:Je,verify:N,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(B=8,A=v.BASE){return A._setWindowSize(B),A.multiply(BigInt(3)),A}}}}var Ua=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Mu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),WE=BigInt(0),pg=BigInt(1),Fu=BigInt(2),jE=BigInt(3),mg=BigInt(5),gg=BigInt(8);function yg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ua,a=r*r%s*r%s,c=ne(a,Fu,s)*a%s,u=ne(c,pg,s)*r%s,f=ne(u,mg,s)*u%s,l=ne(f,e,s)*f%s,p=ne(l,t,s)*l%s,h=ne(p,n,s)*p%s,d=ne(h,o,s)*h%s,m=ne(d,o,s)*h%s,y=ne(m,e,s)*f%s;return{pow_p_5_8:ne(y,Fu,s)*r%s,b2:a}}function wg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function bg(r,e){let t=Ua,n=Q(e*e*e,t),o=Q(n*n*e,t),s=yg(r*o).pow_p_5_8,i=Q(r*n*s,t),a=Q(e*i*i,t),c=i,u=Q(i*Mu,t),f=a===r,l=a===Q(-r,t),p=a===Q(-r*Mu,t);return f&&(i=c),(l||p)&&(i=u),Du(i,t)&&(i=Q(-i,t)),{isValid:f||l,value:i}}var Eg=Ho(Ua,void 0,!0),xg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Eg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:gg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Mn,randomBytes:Xr,adjustScalarBytes:wg,uvRatio:bg},Jr=Uu(xg);var en=32,Lt=64,zo=32;function Vu(){let r=Jr.utils.randomPrivateKey(),e=Jr.getPublicKey(r);return{privateKey:$u(r,e),publicKey:e}}function Ku(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:$u(e,t),publicKey:t}}function Hu(r,e){let t=r.subarray(0,zo);return Jr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function qu(r,e,t){return Jr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function $u(r,e){let t=new Uint8Array(Lt);for(let n=0;n<zo;n++)t[n]=r[n],t[zo+n]=e[n];return t}var Fe={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Ma={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function zu(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,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 y;if(p.length===0){y=await a.subtle.importKey("jwk",Ma,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Ma,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,l);return Ie([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),y={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",Ma,{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 w=await a.subtle.decrypt(y,g,m);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function tn(r,e){let n=await zu().encrypt(r,e);return On.encode(n)}var Ag=Math.pow(2,7),Sg=Math.pow(2,14),Rg=Math.pow(2,21),Fa=Math.pow(2,28),Va=Math.pow(2,35),Ka=Math.pow(2,42),Ha=Math.pow(2,49),X=128,De=127;function me(r){if(r<Ag)return 1;if(r<Sg)return 2;if(r<Rg)return 3;if(r<Fa)return 4;if(r<Va)return 5;if(r<Ka)return 6;if(r<Ha)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function qa(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|X,r/=128;case 7:e[t++]=r&255|X,r/=128;case 6:e[t++]=r&255|X,r/=128;case 5:e[t++]=r&255|X,r/=128;case 4:e[t++]=r&255|X,r>>>=7;case 3:e[t++]=r&255|X,r>>>=7;case 2:e[t++]=r&255|X,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Ig(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|X),r/=128;case 7:e.set(t++,r&255|X),r/=128;case 6:e.set(t++,r&255|X),r/=128;case 5:e.set(t++,r&255|X),r/=128;case 4:e.set(t++,r&255|X),r>>>=7;case 3:e.set(t++,r&255|X),r>>>=7;case 2:e.set(t++,r&255|X),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function $a(r,e){let t=r[e],n=0;if(n+=t&De,t<X||(t=r[e+1],n+=(t&De)<<7,t<X)||(t=r[e+2],n+=(t&De)<<14,t<X)||(t=r[e+3],n+=(t&De)<<21,t<X)||(t=r[e+4],n+=(t&De)*Fa,t<X)||(t=r[e+5],n+=(t&De)*Va,t<X)||(t=r[e+6],n+=(t&De)*Ka,t<X)||(t=r[e+7],n+=(t&De)*Ha,t<X))return n;throw new RangeError("Could not decode varint")}function Bg(r,e){let t=r.get(e),n=0;if(n+=t&De,t<X||(t=r.get(e+1),n+=(t&De)<<7,t<X)||(t=r.get(e+2),n+=(t&De)<<14,t<X)||(t=r.get(e+3),n+=(t&De)<<21,t<X)||(t=r.get(e+4),n+=(t&De)*Fa,t<X)||(t=r.get(e+5),n+=(t&De)*Va,t<X)||(t=r.get(e+6),n+=(t&De)*Ka,t<X)||(t=r.get(e+7),n+=(t&De)*Ha,t<X))return n;throw new RangeError("Could not decode varint")}function Pe(r,e,t=0){return e==null&&(e=Le(me(r))),e instanceof Uint8Array?qa(r,e,t):Ig(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?$a(r,e):Bg(r,e)}var za=new Float32Array([-0]),tr=new Uint8Array(za.buffer);function Gu(r,e,t){za[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3]}function Yu(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],za[0]}var Ga=new Float64Array([-0]),Oe=new Uint8Array(Ga.buffer);function Wu(r,e,t){Ga[0]=r,e[t]=Oe[0],e[t+1]=Oe[1],e[t+2]=Oe[2],e[t+3]=Oe[3],e[t+4]=Oe[4],e[t+5]=Oe[5],e[t+6]=Oe[6],e[t+7]=Oe[7]}function ju(r,e){return Oe[0]=r[e],Oe[1]=r[e+1],Oe[2]=r[e+2],Oe[3]=r[e+3],Oe[4]=r[e+4],Oe[5]=r[e+5],Oe[6]=r[e+6],Oe[7]=r[e+7],Ga[0]}var Tg=BigInt(Number.MAX_SAFE_INTEGER),Cg=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<Tg&&e>Cg)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>Xu&&(o=0n,++n>Xu&&(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 Xu=4294967296n;function Zu(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 Qu(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 Ya(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 Wa=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=Yu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=ju(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 Qu(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=$a(this.buf,this.pos);return this.pos+=me(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 ja(r){return new Wa(r instanceof Uint8Array?r:r.subarray())}function Ve(r,e,t){let n=ja(r);return e.decode(n,void 0,t)}function Xa(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Le(i);o+i>e&&(n=Le(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 Za(){}var Ja=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},kg=Xa();function Ng(r){return globalThis.Buffer!=null?Le(r):kg(r)}var Hn=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(Za,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 ec((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(qa,me(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(Qa,1,e?1:0)}fixed32(e){return this._push(Kn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Kn,4,t.lo)._push(Kn,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Kn,4,t.lo)._push(Kn,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(Gu,4,e)}double(e){return this._push(Wu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Qa,1,0):this.uint32(t)._push(Dg,t,e)}string(e){let t=Zu(e);return t!==0?this.uint32(t)._push(Ya,t,e):this._push(Qa,1,0)}fork(){return this.states=new Ja(this),this.head=this.tail=new _r(Za,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(Za,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=Ng(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Qa(r,e,t){e[t]=r&255}function Lg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ec=class extends _r{next;constructor(e,t){super(Lg,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 Kn(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 Dg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Hn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Pg,e,r),this},Hn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Og,e,r),this});function Pg(r,e,t){e.set(r,t)}function Og(r,e,t){r.length<40?Ya(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function tc(){return new Hn}function Ke(r,e){let t=tc();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 rc(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 He(r,e){return Wo("message",rn.LENGTH_DELIMITED,r,e)}var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(oe||(oe={}));var nc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(nc||(nc={}));(function(r){r.codec=()=>rc(nc)})(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 qn=class{_key;constructor(e){this._key=nn(e,en)}verify(e,t){return qu(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 rt(e)?e.then(({bytes:t})=>t):e.bytes}},Ar=class{_key;_publicKey;constructor(e,t){this._key=nn(e,Lt),this._publicKey=nn(t,en)}sign(e){return Hu(this._key,e)}get public(){return new qn(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 rt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Bt.digest(this.public.bytes);return ie.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 Ug(r){if(r.length>Lt){r=nn(r,Lt+en);let n=r.subarray(0,Lt),o=r.subarray(Lt,r.length);return new Ar(n,o)}r=nn(r,Lt);let e=r.subarray(0,Lt),t=r.subarray(en);return new Ar(e,t)}function Mg(r){return r=nn(r,en),new qn(r)}async function Fg(){let{privateKey:r,publicKey:e}=Vu();return new Ar(r,e)}async function ef(r){let{privateKey:e,publicKey:t}=Ku(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 pc={};ve(pc,{MAX_RSA_KEY_SIZE:()=>to,RsaPrivateKey:()=>ln,RsaPublicKey:()=>eo,fromJwk:()=>h0,generateKeyPair:()=>d0,unmarshalRsaPrivateKey:()=>hc,unmarshalRsaPublicKey:()=>f0});function bt(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 sr={};ve(sr,{exportToPem:()=>i0,importFromPem:()=>a0,jwkToPkcs1:()=>r0,jwkToPkix:()=>o0,pkcs1ToJwk:()=>t0,pkixToJwk:()=>n0});var Xo=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Po(e);let n=jt(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 Vg(r,e,t,n){Po(r);let o=Au({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=jt(e),u=jt(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 Kg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function sc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Vg(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 y=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),y.set(h.subarray(0,y.length)),await vu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<y.length;g++)y[g]^=h[g]})}return Kg(c,u,a,f,h)}var z=St(tf());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 rr(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 ac(){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 rf(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=rr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=rr(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 nf(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 ze(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 n1=Math.log(2);function es(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function cc(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 Mt(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 Gn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return cc(this.items)}},zn=[new Uint8Array([1])],of="0123456789";var an="",ht=new ArrayBuffer(0),lc=new Uint8Array(0),Yn="EndOfContent",af="OCTET STRING",cf="BIT STRING";function Ft(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):lc}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(!Mt(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 Pt=class{constructor({blockLength:e=0,error:t=an,warnings:n=[],valueBeforeDecode:o=lc}={}){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)}}};Pt.NAME="baseBlock";var Ue=class extends Pt{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'")}};Ue.NAME="valueBlock";var ts=class extends Ft(Pt){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):lc,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=rr(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(!Mt(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 Pt{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(!Mt(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=rr(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 T={},Be=class extends Pt{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 Ue(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 Gn;t||lf(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 nf(t,n)}};Be.NAME="BaseBlock";function lf(r){if(r instanceof T.Constructed)for(let e of r.valueBlock.value)lf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Be{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 Ft(Ue){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};os.NAME="PrimitiveValueBlock";var uf,ss=class extends Be{constructor(e={}){super(e,os),this.idBlock.isConstructed=!1}};uf=ss;T.Primitive=uf;ss.NAME="PRIMITIVE";function Xg(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 Be({},Ue),s=new Pt;if(!Mt(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=Be;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=T.EndOfContent;break;case 1:c=T.Boolean;break;case 2:c=T.Integer;break;case 3:c=T.BitString;break;case 4:c=T.OctetString;break;case 5:c=T.Null;break;case 6:c=T.ObjectIdentifier;break;case 10:c=T.Enumerated;break;case 12:c=T.Utf8String;break;case 13:c=T.RelativeObjectIdentifier;break;case 14:c=T.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=T.Sequence;break;case 17:c=T.Set;break;case 18:c=T.NumericString;break;case 19:c=T.PrintableString;break;case 20:c=T.TeletexString;break;case 21:c=T.VideotexString;break;case 22:c=T.IA5String;break;case 23:c=T.UTCTime;break;case 24:c=T.GeneralizedTime;break;case 25:c=T.GraphicString;break;case 26:c=T.VisibleString;break;case 27:c=T.GeneralString;break;case 28:c=T.UniversalString;break;case 29:c=T.CharacterString;break;case 30:c=T.BmpString;break;case 31:c=T.DATE;break;case 32:c=T.TimeOfDay;break;case 33:c=T.DateTime;break;case 34:c=T.Duration;break;default:{let u=o.idBlock.isConstructed?new T.Constructed:new T.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?T.Constructed:T.Primitive}return o=Xg(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 Be({},Ue);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ms(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Zg(r,e){return r?1:e}var Et=class extends Ue{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(!Mt(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(;Zg(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===Yn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Gn;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}};Et.NAME="ConstructedValueBlock";var ff,nr=class extends Be{constructor(e={}){super(e,Et),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} :`}};mf=nr;T.Constructed=mf;nr.NAME="CONSTRUCTED";var cs=class extends Oe{fromBER(e,t,n){return t}toBER(e){return ft}};cs.override="EndOfContentValueBlock";var gf,ls=class extends Ie{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};gf=ls;T.EndOfContent=gf;ls.NAME=Wn;var yf,or=class extends Ie{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}`}};yf=or;T.Null=yf;or.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,hc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};us.NAME="BooleanValueBlock";var wf,fs=class extends Ie{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}`}};wf=fs;T.Boolean=wf;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===Wn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==ff)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 bf,Pt=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},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?nr.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)}};bf=Pt;T.OctetString=bf;Pt.NAME=ff;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===Wn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==hf)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 ft;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 Ef,cn=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},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 nr.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)}`}}};Ef=cn;T.BitString=Ef;cn.NAME=hf;var xf;function t0(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=ts(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=ts(t,s)),s}function uf(r){if(r>=Gn.length)for(let e=Gn.length;e<=r;e++){let t=new Uint8Array([0]),n=Gn[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)),Gn.push(n)}return Gn[r]}function r0(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 jn=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=hc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(af(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=r0(uf(n),t),i="-";break;default:t=t0(t,uf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=lf.charAt(t[c]));return a===!1&&(i+=lf.charAt(0)),i}};xf=jn;jn.NAME="IntegerValueBlock";Object.defineProperty(xf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var vf,me=class r extends Ie{constructor(e={}){super(e,jn),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 Yn,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()}`}};vf=me;T.Integer=vf;me.NAME="INTEGER";var _f,ps=class extends me{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};_f=ps;T.Enumerated=_f;ps.NAME="ENUMERATED";var Xn=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=Rr(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=rr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ft;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}}};Xn.NAME="sidBlock";var ms=class extends Oe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Xn;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,ft;t.push(o)}return dc(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 Xn;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 Af,ut=class extends Ie{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()}}};Af=ut;T.ObjectIdentifier=Af;ut.NAME="OBJECT IDENTIFIER";var Zn=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=Rr(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=rr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ft;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}}};Zn.NAME="relativeSidBlock";var gs=class extends Oe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Zn;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,ft;n.push(s)}return dc(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 Zn;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 Sf,ys=class extends Ie{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()}}};Sf=ys;T.RelativeObjectIdentifier=Sf;ys.NAME="RelativeObjectIdentifier";var Rf,ve=class extends nr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Rf=ve;T.Sequence=Rf;ve.NAME="SEQUENCE";var If,ws=class extends nr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};If=ws;T.Set=If;ws.NAME="SET";var bs=class extends Mt(Oe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ln}toJSON(){return{...super.toJSON(),value:this.value}}};bs.NAME="StringValueBlock";var Es=class extends bs{};Es.NAME="SimpleStringValueBlock";var He=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}};He.NAME="SIMPLE STRING";var xs=class extends He{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 Bf,Ot=class extends xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Bf=Ot;T.Utf8String=Bf;Ot.NAME="UTF8String";var vs=class extends He{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 Tf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Tf=_s;T.BmpString=Tf;_s.NAME="BMPString";var As=class extends He{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=rr(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 Cf,Ss=class extends As{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Cf=Ss;T.UniversalString=Cf;Ss.NAME="UniversalString";var kf,Rs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};kf=Rs;T.NumericString=kf;Rs.NAME="NumericString";var Nf,Is=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Nf=Is;T.PrintableString=Nf;Is.NAME="PrintableString";var Lf,Bs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Lf=Bs;T.TeletexString=Lf;Bs.NAME="TeletexString";var Df,Ts=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Df=Ts;T.VideotexString=Df;Ts.NAME="VideotexString";var Pf,Cs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Pf=Cs;T.IA5String=Pf;Cs.NAME="IA5String";var Of,ks=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Of=ks;T.GraphicString=Of;ks.NAME="GraphicString";var Uf,Qn=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Uf=Qn;T.VisibleString=Uf;Qn.NAME="VisibleString";var Mf,Ns=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Mf=Ns;T.GeneralString=Mf;Ns.NAME="GeneralString";var Ff,Ls=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Ff=Ls;T.CharacterString=Ff;Ls.NAME="CharacterString";var Vf,Jn=class extends Qn{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]=$e(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=$e(this.month,2),t[2]=$e(this.day,2),t[3]=$e(this.hour,2),t[4]=$e(this.minute,2),t[5]=$e(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}}};Vf=Jn;T.UTCTime=Vf;Jn.NAME="UTCTime";var Kf,Ds=class extends Jn{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($e(this.year,4)),t.push($e(this.month,2)),t.push($e(this.day,2)),t.push($e(this.hour,2)),t.push($e(this.minute,2)),t.push($e(this.second,2)),this.millisecond!==0&&(t.push("."),t.push($e(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Kf=Ds;T.GeneralizedTime=Kf;Ds.NAME="GeneralizedTime";var Hf,Ps=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Hf=Ps;T.DATE=Hf;Ps.NAME="DATE";var qf,Os=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};qf=Os;T.TimeOfDay=qf;Os.NAME="TimeOfDay";var $f,Us=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};$f=Us;T.DateTime=$f;Us.NAME="DateTime";var zf,Ms=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};zf=Ms;T.Duration=zf;Ms.NAME="Duration";var Gf,Fs=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Gf=Fs;T.TIME=Gf;Fs.NAME="TIME";function o0(r){let{result:e}=un(r),t=e.valueBlock.value;return{n:H(Et(t[1].toBigInt()),"base64url"),e:H(Et(t[2].toBigInt()),"base64url"),d:H(Et(t[3].toBigInt()),"base64url"),p:H(Et(t[4].toBigInt()),"base64url"),q:H(Et(t[5].toBigInt()),"base64url"),dp:H(Et(t[6].toBigInt()),"base64url"),dq:H(Et(t[7].toBigInt()),"base64url"),qi:H(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function s0(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 ve({value:[new me({value:0}),me.fromBigInt(xt(L(r.n,"base64url"))),me.fromBigInt(xt(L(r.e,"base64url"))),me.fromBigInt(xt(L(r.d,"base64url"))),me.fromBigInt(xt(L(r.p,"base64url"))),me.fromBigInt(xt(L(r.q,"base64url"))),me.fromBigInt(xt(L(r.dp,"base64url"))),me.fromBigInt(xt(L(r.dq,"base64url"))),me.fromBigInt(xt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function i0(r){let{result:e}=un(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(Et(t[0].toBigInt()),"base64url"),e:H(Et(t[1].toBigInt()),"base64url")}}function a0(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new ve({value:[new ve({value:[new ut({value:"1.2.840.113549.1.1.1"}),new or]}),new cn({valueHex:new ve({value:[me.fromBigInt(xt(L(r.n,"base64url"))),me.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 c0=16,mc=32,gc=1e4;async function l0(r,e){let t=Me.get(),o=new ve({value:[new me({value:0}),new ve({value:[new ut({value:"1.2.840.113549.1.1.1"}),new or]}),new Pt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=wt(c0),a=await uc(Jr,e,i,{c:gc,dkLen:mc}),c=wt(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 ve({value:[new Pt({valueHex:i}),new me({value:gc}),new me({value:mc}),new ve({value:[new ut({value:"1.2.840.113549.2.11"}),new or]})]}),p=new ve({value:[new ut({value:"1.2.840.113549.1.5.13"}),new ve({value:[new ve({value:[new ut({value:"1.2.840.113549.1.5.12"}),l]}),new ve({value:[new ut({value:"2.16.840.1.101.3.4.1.42"}),new Pt({valueHex:c})]})]})]}),d=new ve({value:[p,new Pt({valueHex:f})]}).toBER(),m=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...H(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function u0(r,e){let t=Me.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}=un(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=f0(s),l=await uc(Jr,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=eo(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=un(h);n=Yf(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}=un(o);n=Yf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return yc(n)}function f0(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=eo(s.valueBlock.value[0].getValue()),a=gc,c=mc;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=eo(u.valueBlock.value[1].getValue());return{cipherText:eo(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Yf(r){return eo(r.valueBlock.value[2].getValue())}function eo(r){return new Uint8Array(r,0,r.byteLength)}async function Wf(r){let e=await Me.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 Zf(e);return{privateKey:t[0],publicKey:t[1]}}async function wc(r){let t=[await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await h0(r)],n=await Zf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function jf(r,e){let t=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Me.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Xf(r,e,t){let n=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Me.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Zf(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Me.get().subtle.exportKey("jwk",r.privateKey),Me.get().subtle.exportKey("jwk",r.publicKey)])}async function h0(r){return Me.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 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 ro=8192,to=class{_key;constructor(e){this._key=e}verify(e,t){return Xf(this._key,t,e)}marshal(){return sr.jwkToPkix(this._key)}get bytes(){return gt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},fn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return wt(16)}sign(e){return jf(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new to(this._publicKey)}marshal(){return sr.jwkToPkcs1(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=Se.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return H(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return sr.exportToPem(this,e);if(t==="libp2p-key")return nn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function yc(r){let e=sr.pkcs1ToJwk(r);if(Ks(e)>ro)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await wc(e);return new fn(t.privateKey,t.publicKey)}function p0(r){let e=sr.pkixToJwk(r);if(Ks(e)>ro)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new to(e)}async function m0(r){if(Ks(r)>ro)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await wc(r);return new fn(e.privateKey,e.publicKey)}async function g0(r){if(r>ro)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Wf(r);return new fn(e.privateKey,e.publicKey)}var Ac={};xe(Ac,{Secp256k1PrivateKey:()=>oo,Secp256k1PublicKey:()=>no,generateKeyPair:()=>T0,unmarshalSecp256k1PrivateKey:()=>I0,unmarshalSecp256k1PublicKey:()=>B0});var y0=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]),ir=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ar=new Uint32Array(64),Ec=class extends Qr{constructor(){super(64,32,8,!1),this.A=ir[0]|0,this.B=ir[1]|0,this.C=ir[2]|0,this.D=ir[3]|0,this.E=ir[4]|0,this.F=ir[5]|0,this.G=ir[6]|0,this.H=ir[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)ar[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=ar[l-15],h=ar[l-2],d=it(p,7)^it(p,18)^p>>>3,m=it(h,17)^it(h,19)^h>>>10;ar[l]=m+ar[l-7]+d+ar[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+Iu(a,c,u)+y0[l]+ar[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Bu(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(){ar.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Qf=Mo(()=>new Ec);function w0(r){let e=Kn(r);mt(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:b0,hexToBytes:E0}=Ko,Ir={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Ir;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:b0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Ir,t=typeof r=="string"?E0(r):r;en(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}=Ir._parseInt(t.subarray(2)),{d:i,l:a}=Ir._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}`}},Ft=BigInt(0),rt=BigInt(1),q1=BigInt(2),Jf=BigInt(3),$1=BigInt(4);function x0(r){let e=w0(r),{Fp:t}=e,n=e.toBytes||((d,m,y)=>{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),y=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function s(d){let{a:m,b:y}=e,g=t.sqr(d),w=t.mul(g,d);return t.add(t.add(w,t.mul(d,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Ft<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:g,n:w}=e;if(m&&typeof d!="bigint"){if(Qt(d)&&(d=Bt(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(y*2,"0")}let b;try{b=typeof d=="bigint"?d:Tt(le("private key",d,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=Q(b,w)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,g){if(this.px=m,this.py=y,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(m){let{x:y,y:g}=m||{};if(!m||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let w=b=>t.eql(b,t.ZERO);return w(y)&&w(g)?l.ZERO:new l(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(g=>g.pz));return m.map((g,w)=>g.toAffine(y[w])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(o(le("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),w=s(m);if(!t.eql(g,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.eql(t.mul(y,v),t.mul(b,w)),_=t.eql(t.mul(g,v),t.mul(x,w));return S&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,g=t.mul(y,Jf),{px:w,py:b,pz:x}=this,v=t.ZERO,S=t.ZERO,_=t.ZERO,R=t.mul(w,w),q=t.mul(b,b),$=t.mul(x,x),U=t.mul(w,b);return U=t.add(U,U),_=t.mul(w,x),_=t.add(_,_),v=t.mul(m,_),S=t.mul(g,$),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),_=t.mul(g,_),$=t.mul(m,$),U=t.sub(R,$),U=t.mul(m,U),U=t.add(U,_),_=t.add(R,R),R=t.add(_,R),R=t.add(R,$),R=t.mul(R,U),S=t.add(S,R),$=t.mul(b,x),$=t.add($,$),R=t.mul($,U),v=t.sub(v,R),_=t.mul($,q),_=t.add(_,_),_=t.add(_,_),new l(v,S,_)}add(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.ZERO,_=t.ZERO,R=t.ZERO,q=e.a,$=t.mul(e.b,Jf),U=t.mul(y,b),ee=t.mul(g,x),D=t.mul(w,v),Qe=t.add(y,g),I=t.add(b,x);Qe=t.mul(Qe,I),I=t.add(U,ee),Qe=t.sub(Qe,I),I=t.add(y,w);let N=t.add(b,v);return I=t.mul(I,N),N=t.add(U,D),I=t.sub(I,N),N=t.add(g,w),S=t.add(x,v),N=t.mul(N,S),S=t.add(ee,D),N=t.sub(N,S),R=t.mul(q,I),S=t.mul($,D),R=t.add(S,R),S=t.sub(ee,R),R=t.add(ee,R),_=t.mul(S,R),ee=t.add(U,U),ee=t.add(ee,U),D=t.mul(q,D),I=t.mul($,I),ee=t.add(ee,D),D=t.sub(U,D),D=t.mul(q,D),I=t.add(I,D),U=t.mul(ee,I),_=t.add(_,U),U=t.mul(N,I),S=t.mul(Qe,S),S=t.sub(S,U),U=t.mul(Qe,ee),R=t.mul(N,R),R=t.add(R,U),new l(S,_,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let g=t.invertBatch(y.map(w=>w.pz));return y.map((w,b)=>w.toAffine(g[b])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Ft)return y;if(a(m),m===rt)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:w,k1:b,k2neg:x,k2:v}=g.splitScalar(m),S=y,_=y,R=this;for(;b>Ft||v>Ft;)b&rt&&(S=S.add(R)),v&rt&&(_=_.add(R)),R=R.double(),b>>=rt,v>>=rt;return w&&(S=S.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),S.add(_)}multiply(m){a(m);let y=m,g,w,{endo:b}=e;if(b){let{k1neg:x,k1:v,k2neg:S,k2:_}=b.splitScalar(y),{p:R,f:q}=this.wNAF(v),{p:$,f:U}=this.wNAF(_);R=h.constTimeNegate(x,R),$=h.constTimeNegate(S,$),$=new l(t.mul($.px,b.beta),$.py,$.pz),g=R.add($),w=q.add(U)}else{let{p:x,f:v}=this.wNAF(y);g=x,w=v}return l.normalizeZ([g,w])[0]}multiplyAndAddUnsafe(m,y,g){let w=l.BASE,b=(v,S)=>S===Ft||S===rt||!v.equals(w)?v.multiplyUnsafe(S):v.multiply(S),x=b(this,y).add(b(m,g));return x.is0()?void 0:x}toAffine(m){let{px:y,py:g,pz:w}=this,b=this.is0();m==null&&(m=b?t.ONE:t.inv(w));let x=t.mul(y,m),v=t.mul(g,m),S=t.mul(w,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===rt)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===rt?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Bt(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:c,weierstrassEquation:s,isWithinCurveOrder:i}}function v0(r){let e=Kn(r);return mt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function eh(r){let e=v0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Ft<I&&I<t.ORDER}function a(I){return Q(I,n)}function c(I){return Ho(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=x0({...e,toBytes(I,N,F){let B=N.toAffine(),A=t.toBytes(B.x),k=Ct;return F?k(Uint8Array.from([N.hasEvenY()?2:3]),A):k(Uint8Array.from([4]),A,t.toBytes(B.y))},fromBytes(I){let N=I.length,F=I[0],B=I.subarray(1);if(N===o&&(F===2||F===3)){let A=Tt(B);if(!i(A))throw new Error("Point is not on curve");let k=l(A),P;try{P=t.sqrt(k)}catch(K){let W=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+W)}let O=(P&rt)===rt;return(F&1)===1!==O&&(P=t.neg(P)),{x:A,y:P}}else if(N===s&&F===4){let A=t.fromBytes(B.subarray(0,t.BYTES)),k=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:A,y:k}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>Bt(er(I,e.nByteLength));function d(I){let N=n>>rt;return I>N}function m(I){return d(I)?a(-I):I}let y=(I,N,F)=>Tt(I.slice(N,F));class g{constructor(N,F,B){this.r=N,this.s=F,this.recovery=B,this.assertValidity()}static fromCompact(N){let F=e.nByteLength;return N=le("compactSignature",N,F*2),new g(y(N,0,F),y(N,F,2*F))}static fromDER(N){let{r:F,s:B}=Ir.toSig(le("DER",N));return new g(F,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:F,s:B,recovery:A}=this,k=_(le("msgHash",N));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let P=A===2||A===3?F+e.n:F;if(P>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let O=A&1?"03":"02",V=u.fromHex(O+h(P)),K=c(P),W=a(-k*K),G=a(B*K),Y=u.BASE.multiplyAndAddUnsafe(V,W,G);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return br(this.toDERHex())}toDERHex(){return Ir.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return br(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=Ma(e.n);return Fu(e.randomBytes(I),e.n)},precompute(I=8,N=u.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function b(I,N=!0){return u.fromPrivateKey(I).toRawBytes(N)}function x(I){let N=Qt(I),F=typeof I=="string",B=(N||F)&&I.length;return N?B===o||B===s:F?B===2*o||B===2*s:I instanceof u}function v(I,N,F=!0){if(x(I))throw new Error("first arg must be private key");if(!x(N))throw new Error("second arg must be public key");return u.fromHex(N).multiply(f(I)).toRawBytes(F)}let S=e.bits2int||function(I){let N=Tt(I),F=I.length*8-e.nBitLength;return F>0?N>>BigInt(F):N},_=e.bits2int_modN||function(I){return a(S(I))},R=Vn(e.nBitLength);function q(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Ft<=I&&I<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return er(I,e.nByteLength)}function $(I,N,F=U){if(["recovered","canonical"].some(ae=>ae in F))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:A}=e,{lowS:k,prehash:P,extraEntropy:O}=F;k==null&&(k=!0),I=le("msgHash",I),P&&(I=le("prehashed msgHash",B(I)));let V=_(I),K=f(N),W=[q(K),q(V)];if(O!=null&&O!==!1){let ae=O===!0?A(t.BYTES):O;W.push(le("extraEntropy",ae))}let G=Ct(...W),Y=V;function de(ae){let _e=S(ae);if(!p(_e))return;let Ae=c(_e),ge=u.BASE.multiply(_e).toAffine(),ke=a(ge.x);if(ke===Ft)return;let _t=a(Ae*a(Y+ke*K));if(_t===Ft)return;let gr=(ge.x===ke?0:2)|Number(ge.y&rt),Pn=_t;return k&&d(_t)&&(Pn=m(_t),gr^=1),new g(ke,Pn,gr)}return{seed:G,k2sig:de}}let U={lowS:e.lowS,prehash:!1},ee={lowS:e.lowS,prehash:!1};function D(I,N,F=U){let{seed:B,k2sig:A}=$(I,N,F),k=e;return Da(k.hash.outputLen,k.nByteLength,k.hmac)(B,A)}u.BASE._setWindowSize(8);function Qe(I,N,F,B=ee){let A=I;if(N=le("msgHash",N),F=le("publicKey",F),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:k,prehash:P}=B,O,V;try{if(typeof A=="string"||Qt(A))try{O=g.fromDER(A)}catch(ge){if(!(ge instanceof Ir.Err))throw ge;O=g.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:ge,s:ke}=A;O=new g(ge,ke)}else throw new Error("PARSE");V=u.fromHex(F)}catch(ge){if(ge.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(k&&O.hasHighS())return!1;P&&(N=e.hash(N));let{r:K,s:W}=O,G=_(N),Y=c(W),de=a(G*Y),ae=a(K*Y),_e=u.BASE.multiplyAndAddUnsafe(V,de,ae)?.toAffine();return _e?a(_e.x)===K:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:D,verify:Qe,ProjectivePoint:u,Signature:g,utils:w}}function _0(r){return{hash:r,hmac:(e,...t)=>zn(r,e,Uo(...t)),randomBytes:Zr}}function th(r,e){let t=n=>eh({...r,..._0(n)});return Object.freeze({...t(e),create:t})}var oh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),rh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),A0=BigInt(1),xc=BigInt(2),nh=(r,e)=>(r+e/xc)/e;function S0(r){let e=oh,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,p=ne(l,t,e)*f%e,h=ne(p,xc,e)*u%e,d=ne(h,o,e)*h%e,m=ne(d,s,e)*d%e,y=ne(m,a,e)*m%e,g=ne(y,c,e)*y%e,w=ne(g,a,e)*m%e,b=ne(w,t,e)*f%e,x=ne(b,i,e)*d%e,v=ne(x,n,e)*u%e,S=ne(v,xc,e);if(!vc.eql(vc.sqr(S),r))throw new Error("Cannot find square root");return S}var vc=qo(oh,void 0,void 0,{sqrt:S0}),ht=th({a:BigInt(0),b:BigInt(7),Fp:vc,n:rh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=rh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-A0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=nh(s*r,e),c=nh(-n*r,e),u=Q(r-a*t-c*o,e),f=Q(-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}}}},Qf),J1=BigInt(0);var ev=ht.ProjectivePoint;function sh(){return ht.utils.randomPrivateKey()}function ih(r,e){let t=Se.digest(e instanceof Uint8Array?e:e.subarray());if(et(t))return t.then(({digest:n})=>ht.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return ht.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function ah(r,e,t){let n=Se.digest(t instanceof Uint8Array?t:t.subarray());if(et(n))return n.then(({digest:o})=>ht.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return ht.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function ch(r){return ht.ProjectivePoint.fromHex(r).toRawBytes(!0)}function lh(r){try{ht.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function _c(r){try{ht.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function uh(r){try{return ht.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var no=class{_key;constructor(e){_c(e),this._key=e}verify(e,t){return ah(this._key,t,e)}marshal(){return ch(this._key)}get bytes(){return gt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}},oo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??uh(e),lh(this._key),_c(this._publicKey)}sign(e){return ih(this._key,e)}get public(){return new no(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return H(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return nn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function I0(r){return new oo(r)}function B0(r){return new no(r)}async function T0(){let r=sh();return new oo(r)}var cr={rsa:bc,ed25519:lc,secp256k1:Ac};function Sc(r){let e=Object.keys(cr).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Rc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return cr[r];throw Sc(r)}async function fh(r,e){return Rc(r).generateKeyPair(e??2048)}function so(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return cr.rsa.unmarshalRsaPublicKey(t);case oe.Ed25519:return cr.ed25519.unmarshalEd25519PublicKey(t);case oe.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Sc(e.Type??"unknown")}}function hh(r,e){return e=(e??"rsa").toLowerCase(),Rc(e),r.bytes}async function io(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return cr.rsa.unmarshalRsaPrivateKey(t);case oe.Ed25519:return cr.ed25519.unmarshalEd25519PrivateKey(t);case oe.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Sc(e.Type??"RSA")}}function dh(r,e){return e=(e??"rsa").toLowerCase(),Rc(e),r.bytes}var je=At(wh(),1);je.default.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Mn.baseEncode(r);je.default.formatters.p=r=>r==null?"undefined":r.toString();je.default.formatters.c=r=>r==null?"undefined":r.toString();je.default.formatters.k=r=>r==null?"undefined":r.toString();je.default.formatters.a=r=>r==null?"undefined":r.toString();function H0(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 q0(r)}}}function q0(r){let e=H0(`${r}:trace`);return je.default.enabled(`${r}:trace`)&&je.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,je.default)(`${r}:trace`)),Object.assign((0,je.default)(r),{error:(0,je.default)(`${r}:error`),trace:e})}var $0=Symbol.for("nodejs.util.inspect.custom"),bh=Object.values(Wt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Wt.identity.decoder),Eh=114,Ic=36,Bc=37,ao=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()})`}[ta]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return st.createV1(Eh,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 we(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[$0](){return`PeerId(${this.toString()})`}},Tr=class extends ao{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Cr=class extends ao{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},kr=class extends ao{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function xh(r){if(r.type==="RSA")return new Tr(r);if(r.type==="Ed25519")return new Cr(r);if(r.type==="secp256k1")return new kr(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function we(r,e){if(e=e??bh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=yr(ie.decode(`z${r}`));return r.startsWith("12D")?new Cr({multihash:t}):r.startsWith("16U")?new kr({multihash:t}):new Tr({multihash:t})}return mn(bh.decode(r))}function mn(r){try{let e=yr(r);if(e.code===Yt.code){if(e.digest.length===Ic)return new Cr({multihash:e});if(e.digest.length===Bc)return new kr({multihash:e})}if(e.code===Se.code)return new Tr({multihash:e})}catch{return z0(st.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function z0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Eh)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Se.code)return new Tr({multihash:r.multihash});if(e.code===Yt.code){if(e.digest.length===Ic)return new Cr({multihash:r.multihash});if(e.digest.length===Bc)return new kr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function gn(r,e){return r.length===Ic?new Cr({multihash:pt(Yt.code,r),privateKey:e}):r.length===Bc?new kr({multihash:pt(Yt.code,r),privateKey:e}):new Tr({multihash:await Se.digest(r),publicKey:r,privateKey:e})}function yn(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 yn(this.map.entries(),e=>[we(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,we(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 yn(this.map.keys(),e=>we(e))}values(){return this.map.values()}get size(){return this.map.size}};var Vt=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 yn(this.set.entries(),e=>{let t=we(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=we(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return yn(this.set.values(),e=>we(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 Rh=Symbol.for("@achingbrain/uint8arraylist");function Sh(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 Gs(r){return!!r?.[Rh]}var be=class r{bufs;length;[Rh]=!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(Gs(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(Gs(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=Sh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Sh(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(Gs(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(!Gs(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=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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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 Tc=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Tc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ot(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 Nr(r,e){return Math.floor(Math.random()*(e-r))+r}var Lr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=Nr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Cc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ih={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Bh=new globalThis.TextEncoder;function G0(r,e){let t=Cc[e],n=Ih[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Y0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Cc[e],o=Ih[e],s=r;for(;s.length>0;){let i=Bh.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 kc(r,{size:e=32,utf8Buffer:t}={}){if(!Cc[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 Y0(r,e,t);r=Bh.encode(r)}return G0(r,e)}var W0=At(Ah(),1);var lo={hash:r=>Number(kc(r,{size:32})),hashV:(r,e)=>j0(lo.hash(r,e))};function j0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var X0=500,uo=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??lo,this.seed=e.seed??Nr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new dt(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 Lr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Lr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Nr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Lr(this.bucketSize));for(let a=0;a<X0;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 Lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new dt(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 dt(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))<=95}},Z0={1:.5,2:.84,4:.95,8:.98};function Q0(r=.001){return r>.002?2:r>1e-5?4:8}function Th(r,e=.001){let t=Q0(e),n=Z0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log(o/t))+2,Tc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Ys=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??lo,this.seed=e.seed??Nr(0,Math.pow(2,10)),this.filterSeries=[new uo({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 uo({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 Nc(r,e=.001,t){return new Ys({...Th(r,e),...t??{}})}var Ch=async()=>{let r=await fh("Ed25519"),e=await J0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function J0(r){return gn(hh(r.public),dh(r))}var kh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var fo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(fo||(fo={}));var wn=class r{static createFromProtobuf=async e=>{let t=fo.decode(e),n=await gn(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=Nh(n,o,s),c=await(await io(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",kh.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=fo.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=Nh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return so(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Nh=(r,e,t)=>{let n=L(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new be(o,n,s,e,i,t)};function Lh(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 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 Dh=45,ey=15,bn=new Ws;function Lc(r){if(!(r.length>ey))return bn.new(r).parseWith(()=>bn.readIPv4Addr())}function Dc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dh))return bn.new(r).parseWith(()=>bn.readIPv6Addr())}function js(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dh))return bn.new(r).parseWith(()=>bn.readIPAddr())}var $_=parseInt("0xFFFF",16),z_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function En(r){return!!Lc(r)}function xn(r){return!!Dc(r)}function Xs(r){return!!js(r)}var Uh=En,sy=xn,Pc=function(r){let e=0;if(r=r.toString().trim(),Uh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(sy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Uh(t[n]),i;s&&(i=Pc(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(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")},Mh=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 vn={},Oc={},ay=[[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"]];ay.forEach(r=>{let e=cy(...r);Oc[e.code]=e,vn[e.name]=e});function cy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(Oc[r]!=null)return Oc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(vn[r]!=null)return vn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var BA=Z("ip4"),TA=Z("ip6"),CA=Z("ipcidr");function Vc(r,e){switch(Z(r).code){case 4:case 41:return uy(e);case 42:return Fc(e);case 6:case 273:case 33:case 132:return Kh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fc(e);case 421:return py(e);case 444:return Vh(e);case 445:return Vh(e);case 466:return dy(e);case 481:return globalThis.encodeURIComponent(Fc(e));default:return H(e,"base16")}}function Kc(r,e){switch(Z(r).code){case 4:return Fh(e);case 41:return Fh(e);case 42:return Mc(e);case 6:case 273:case 33:case 132:return Hc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Mc(e);case 421:return fy(e);case 444:return my(e);case 445:return gy(e);case 466:return hy(e);case 481:return Mc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var Uc=Object.values(Wt).map(r=>r.decoder),ly=function(){let r=Uc[0].or(Uc[1]);return Uc.slice(2).forEach(e=>r=r.or(e)),r}();function Fh(r){if(!Xs(r))throw new Error("invalid ip address");return Pc(r)}function uy(r){let e=Mh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Xs(e))throw new Error("invalid ip address");return e}function Hc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Kh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Mc(r){let e=L(r),t=Uint8Array.from(De(e.length));return Re([t,e],t.length+e.length)}function Fc(r){let e=ct(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function fy(r){let e;r[0]==="Q"||r[0]==="1"?e=yr(ie.decode(`z${r}`)).bytes:e=st.parse(r).multihash.bytes;let t=Uint8Array.from(De(e.length));return Re([t,e],t.length+e.length)}function hy(r){let e=ly.decode(r),t=Uint8Array.from(De(e.length));return Re([t,e],t.length+e.length)}function dy(r){let e=ct(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function py(r){let e=ct(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function my(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=ze.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=Hc(n);return Re([t,o],t.length+o.length)}function gy(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=ze.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=Hc(n);return Re([t,o],t.length+o.length)}function Vh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=Kh(t);return`${n}:${o}`}function Hh(r){r=qc(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=Z(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw $h("invalid address: "+r);if(a.path===!0){n=qc(o.slice(s).join("/")),e.push([a.code,Kc(a.code,n)]),t.push([a.code,n]);break}let c=Kc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Vc(a.code,c)])}return{string:qh(t),bytes:zc(e),tuples:e,stringTuples:t,path:n}}function $c(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=ct(r,o),i=pe(s),a=Z(s),c=yy(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 $h("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=Vc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:qh(t),tuples:e,stringTuples:t,path:n}}function qh(r){let e=[];return r.map(t=>{let n=Z(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),qc(e.join("/"))}function zc(r){return Re(r.map(e=>{let t=Z(e[0]),n=Uint8Array.from(De(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function yy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=ct(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function qc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function $h(r){return new Error("Error parsing address: "+r)}var wy=Symbol.for("nodejs.util.inspect.custom"),Gc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),by=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],Zs=class r{bytes;#e;#t;#s;#a;[Gc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=$c(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Hh(e)}else if(lr(e))t=$c(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=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),by.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=Z(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=Z(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({},Z(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Z(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(zc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===vn.p2p.code&&e.push([n,o]),n===vn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(ie.decode(`z${n}`),"base58btc"):H(st.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=_n.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=>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)}[wy](){return`Multiaddr(${this.#e})`}};var _n=new Map;function lr(r){return!!r?.[Gc]}function se(r){return new Zs(r)}var zh="libp2p-peer-record",Gh=Uint8Array.from([3,1]);var ho;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ke((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=>Ve(s,n.codec()),n.decode=s=>Fe(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((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=>Ve(n,r.codec()),r.decode=n=>Fe(n,r.codec())})(ho||(ho={}));var Dr=class r{static createFromProtobuf=e=>{let t=ho.decode(e),n=mn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=zh;static CODEC=Gh;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=ho.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||!Lh(this.multiaddrs,e.multiaddrs))}};function Ey(r){return r[Symbol.asyncIterator]!=null}function xy(r){if(Ey(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 po=xy;var Wc=At(Wh(),1);var go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},jc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},jh=r=>globalThis.DOMException===void 0?new jc(r):new DOMException(r),Xh=r=>{let e=r.reason===void 0?jh("This operation was aborted."):r.reason;return e instanceof Error?e:jh(e)};function yo(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(Xh(p)),p.addEventListener("abort",()=>{f(Xh(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new go;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 Xc(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 wo=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=Xc(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 ur=class extends Wc.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:wo,...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=yo(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 go&&!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 fr={},An=r=>{r.addEventListener("message",e=>{An.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{An.dispatchEvent("message",r,e)})};An.addEventListener=(r,e)=>{fr[r]==null&&(fr[r]=[]),fr[r].push(e)};An.removeEventListener=(r,e)=>{fr[r]!=null&&(fr[r]=fr[r].filter(t=>t===e))};An.dispatchEvent=function(r,e,t){fr[r]!=null&&fr[r].forEach(n=>n(e,t))};var Zc=An;var Qc="lock:worker:request-read",Jc="lock:worker:release-read",el="lock:master:grant-read",tl="lock:worker:request-write",rl="lock:worker:release-write",nl="lock:master:grant-write";var Zh=(r=21)=>Math.random().toString().substring(2);var Qh=(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)})}}}))},Jh=(r,e,t,n)=>async()=>{let o=Zh();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)})},Ay={singleProcess:!1},ed=r=>{if(r=Object.assign({},Ay,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Zc.addEventListener("message",Qh(t,"requestReadLock",Qc,Jc,el)),Zc.addEventListener("message",Qh(t,"requestWriteLock",tl,rl,nl)),t}return{isWorker:!0,readLock:t=>Jh(t,Qc,el,Jc),writeLock:t=>Jh(t,tl,nl,rl)}};var Pr={},hr;async function ol(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>yo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Sy=(r,e)=>{if(hr.isWorker===!0)return{readLock:hr.readLock(r,e),writeLock:hr.writeLock(r,e)};let t=new ur({concurrency:1}),n;return{async readLock(){if(n!=null)return ol(n,e);n=new ur({concurrency:e.concurrency,autoStart:!1});let o=n,s=ol(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,ol(t,e)}}},Ry={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function sl(r){let e=Object.assign({},Ry,r);return hr==null&&(hr=ed(e),hr.isWorker!==!0&&(hr.addEventListener("requestReadLock",t=>{Pr[t.data.name]!=null&&Pr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),hr.addEventListener("requestWriteLock",async t=>{Pr[t.data.name]!=null&&Pr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Pr[e.name]==null&&(Pr[e.name]=Sy(e.name,e)),Pr[e.name]}var Be={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Sn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((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=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((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),ei.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=ei.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Js.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(Js.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=>Ve(o,r.codec()),r.decode=o=>Fe(o,r.codec())})(Sn||(Sn={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(Js||(Js={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(ei||(ei={}));function Rn(r,e){let t=Sn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=xh({...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 Kt="/",td=new TextEncoder().encode(Kt),ti=td[0],Or=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]!==ti)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Kt))}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=td),this._buf[0]!==ti){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ti,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ti;)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(Kt).slice(1)}type(){return Iy(this.baseNamespace())}name(){return By(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Kt)||(e+=Kt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Kt):new r(e.slice(0,-1).join(Kt))}child(e){return this.toString()===Kt?e:e.toString()===Kt?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(),...Ty(e.map(t=>t.namespaces()))])}};function Iy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function By(r){let e=r.split(":");return e[e.length-1]}function Ty(r){return[].concat(...r)}var il="/peers/";function In(r){if(!Co(r)||r.type==null)throw new E("Invalid PeerId",Be.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Or(`${il}${e}`)}async function rd(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)),!lr(o.multiaddr))throw new E("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 ni(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Be.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(e.publicKey,r.publicKey))throw new E("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 E("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=ri(l,{validate:nd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ri(l,{validate:od,map:sd})}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=ri([...a.entries()],{validate:nd})}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=ri([...p.entries()],{validate:od,map:sd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await rd(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 ri(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 nd(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Be.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Be.ERR_INVALID_PARAMETERS)}function od(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Be.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Be.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Be.ERR_INVALID_PARAMETERS)}}function sd(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 oi(r,e,t){let n=r.toString().split("/")[2],o=ze.decode(n),s=mn(o),i=t.get(s);if(i!=null)return i;let a=Rn(s,e);return t.set(s,a),a}function Cy(r,e){return r==null?{}:{prefix:il,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(oi(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(oi(n.key,n.value,e),oi(o.key,o.value,e)))}}var si=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=sl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(In(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Be.ERR_INVALID_PARAMETERS);await this.datastore.delete(In(e))}async load(e){let t=await this.datastore.get(In(e));return Rn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ni(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 ni(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 ni(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(Cy(e??{},t))){let s=oi(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(In(e)),n=Rn(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=Sn.encode(t);return n!=null&&te(s,n)?{peer:Rn(e,s),previous:o,updated:!1}:(await this.datastore.put(In(e),s),{peer:Rn(e,s),previous:o,updated:!0})}};var ii=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 si(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 po(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 wn.openAndCertify(e,Dr.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=Dr.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 wn.createFromProtobuf(s.peerRecordEnvelope),a=Dr.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 ky(r){return r[Symbol.asyncIterator]!=null}function Ny(r){if(ky(r))return(async()=>{for await(let e of r);})();for(let e of r);}var al=Ny;function Ly(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 id=Ly;function Dy(r){return r[Symbol.asyncIterator]!=null}function Py(r,e){let t=0;if(Dy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=id(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 Ur=Py;function Oy(r){return r[Symbol.asyncIterator]!=null}function Uy(r,e){return Oy(r)?async function*(){yield*(await po(r)).sort(e)}():function*(){yield*po(r).sort(e)}()}var cl=Uy;function My(r){return r[Symbol.asyncIterator]!=null}function Fy(r,e){return My(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 ll=Fy;var ai=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 al(this.putMany(e,n)),e=[],await al(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=Ur(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ur(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>cl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Ur(n,()=>o++>=s)}return e.limit!=null&&(n=ll(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Ur(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ur(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>cl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Ur(n,()=>s++>=o)}return e.limit!=null&&(n=ll(n,e.limit)),n}};var ld=At(ul(),1);function ud(r){return r=r??new Error("Not Found"),(0,ld.default)(r,"ERR_NOT_FOUND")}var ci=class extends ai{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 ud();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 Or(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Or(e)}};function fd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Hy=r=>r;function fl(r,e){let t=r.getPeerId();return t!=null&&we(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var li=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??Hy,this._updatePeerStoreAddresses=fd(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=fl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=fl(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=fl(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 hl=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=>nu(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")}},qy=["metrics","connectionProtector","dns"],$y=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function hd(r={}){let e=new hl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!$y.includes(o)){let i=e.components[o];if(i==null&&!qy.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 dd(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 Gy(t))if(e[n]!==!0)throw new E(`Service "${Yy(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?.[sa])?r[sa]:[]}function Gy(r){return Array.isArray(r?.[ia])?r[ia]:[]}function Yy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var md=At(pd(),1),Wy=["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"],jy=Wy.map(r=>new md.Netmask(r));function Xy(r){for(let e of jy)if(e.contains(r))return!0;return!1}function Zy(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.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 ui(r){return En(r)?Xy(r):xn(r)?Zy(r):void 0}function gd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ui(`${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 Qy=r=>r.toString().split("/").slice(1),Eo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),j=r=>({match:e=>Eo(t=>t===r).match(e),pattern:r}),di=()=>({match:r=>Eo(e=>typeof e=="string").match(r),pattern:"{string}"}),pi=()=>({match:r=>Eo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Te=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ie.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),fi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{_a.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Ee=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),nt=(...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(", ")})`}),J=(...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 he(...r){function e(o){let s=Qy(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 pl=J(j("dns4"),di()),ml=J(j("dns6"),di()),gl=J(j("dnsaddr"),di()),yd=J(j("dns"),di()),tR=he(pl),rR=he(ml),nR=he(gl),oR=he(nt(yd,gl,pl,ml)),wd=J(j("ip4"),Eo(En)),bd=J(j("ip6"),Eo(xn)),Ed=nt(wd,bd),vt=nt(Ed,yd,pl,ml,gl),sR=he(vt),iR=he(wd),aR=he(bd),cR=he(Ed),yl=J(vt,j("tcp"),pi()),xo=J(vt,j("udp"),pi()),lR=he(yl),uR=he(xo),wl=J(xo,j("quic")),mi=J(xo,j("quic-v1")),Jy=nt(wl,mi),fR=he(wl),hR=he(mi),dl=nt(vt,yl,xo,wl,mi),xd=nt(J(dl,j("ws"),Ee(Te()))),dR=he(xd),vd=nt(J(dl,j("wss"),Ee(Te())),J(dl,j("tls"),j("ws"),Ee(Te()))),pR=he(vd),_d=J(xo,j("webrtc-direct"),Ee(fi()),Ee(fi()),Ee(Te())),mR=he(_d),Ad=J(mi,j("webtransport"),Ee(fi()),Ee(fi()),Ee(Te())),gR=he(Ad),hi=nt(xd,vd,J(yl,Ee(Te())),J(Jy,Ee(Te())),J(vt,Ee(Te())),_d,Ad,Te()),yR=he(hi),ew=J(hi,j("p2p-circuit"),Te()),vo=he(ew),tw=nt(J(hi,j("p2p-circuit"),j("webrtc"),Ee(Te())),J(hi,j("webrtc"),Ee(Te())),j("webrtc")),wR=he(tw),rw=nt(J(vt,j("tcp"),pi(),j("http"),Ee(Te())),J(vt,j("http"),Ee(Te()))),bR=he(rw),nw=nt(J(vt,j("tcp"),nt(J(j("443"),j("http")),J(pi(),j("https"))),Ee(Te())),J(vt,j("tls"),j("http"),Ee(Te())),J(vt,j("https"),Ee(Te()))),ER=he(nw);function bl(r){try{let{address:e}=r.nodeAddress();return!!ui(e)}catch{return!0}}function ow(r,e){let t=bl(r.multiaddr),n=bl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function sw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function iw(r,e){let t=vo.exactMatch(r.multiaddr),n=vo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Bn(r,e){let t=ow(r,e);if(t!==0)return t;let n=iw(r,e);return n!==0?n:sw(r,e)}var dr=class extends Event{constructor(e,t){super(e),this.detail=t}};function gi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var El=60;function yi(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??El,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var aw=4;function xl(r,e={}){let t=new ur({concurrency:e.queryConcurrency??aw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),gi(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new dr("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=yi(await a.json());return o.onProgress?.(new dr("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Sd(){return[xl("https://cloudflare-dns.com/dns-query"),xl("https://dns.google/resolve")]}var Bd=At(Id(),1);var vl=class{lru;constructor(e){this.lru=(0,Bd.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 yi({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??El)*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 Td(r){return new vl(r)}var cw=1e3,wi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Td(e.cacheSize??cw),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["."]=Sd())}async query(e,t={}){let n=gi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new dr("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 dr("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 Cd(r={}){return new wi(r)}var lw=32,{code:uw}=Z("dnsaddr"),Mr=async function(e,t={}){let n=t.maxRecursiveDepth??lw;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===uw)??[],i=await(t?.dns??Cd()).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=se(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 Fd=At(Md(),1),xi=Fd.default;var Ht;(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"})(Ht||(Ht={}));var C;(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"})(C||(C={}));var gw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Mr},addressSorter:Bn},transportManager:{faultTolerance:$t.FATAL_ALL}};async function Vd(r){let e=xi(gw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Ht.ERR_PROTECTOR_REQUIRED,C.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await gn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",C.ERR_INVALID_KEY);return e}var Kd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},yw=new WeakMap;function ww({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Kd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Kd())},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}),yw.set(l,()=>{c(s),s=null,i()}),l}}var bw=ww(),Hd=bw;var vi=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 Al}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 Hd(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)}},Al=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 _i(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:we(t),r.forEach(n=>{if(!lr(n))throw new E("Invalid Multiaddr",C.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",C.ERR_INVALID_PARAMETERS)}else{let s=we(o);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",C.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 Ai=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}},kn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ai(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 Ai(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 Sl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Si(r={}){return Ew(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 Ew(r,e){e=e??{};let t=e.onEnd,n=new kn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new kn,s!=null?s({error:y}):(n.push({error:y}),o)),l=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},p=y=>i?o:(i=!0,y!=null?f(y):u({done:!0})),h=()=>(n=new kn,p(),{done:!0}),d=y=>(p(y),{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 y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let w,b;g!=null&&(w=new Promise((x,v)=>{b=()=>{v(new Sl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}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(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(y){return m.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}var Rl=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 Nn(r,e,t,n){let o=new Rl(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 Ri=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 pr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Ri(t?.errorMessage,t?.errorCode));let n,o=new Ri(t?.errorMessage,t?.errorCode);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 Ii=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 zt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function xw(){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=xw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,fe(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 zt),this.cleanup())}async join(e={}){let t=new Ii(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 Ln=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 zt)}),this.clear()}async onEmpty(e){this.size!==0&&await Nn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Nn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Nn(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=Si({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 Ln{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ci="last-dial-failure";var ki=5,Ni=100,Li=50,Di=1e3*60*7;var Fr={minConnections:ki,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Di,autoDialDiscoveredPeersDebounce:10},Pi=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??Fr.minConnections,this.autoDialPriority=t.autoDialPriority??Fr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Fr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Fr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Fr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Fr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ti({concurrency:t.autoDialConcurrency??Fr.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 Vt(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(Ci);if(f==null)return!0;let l=parseInt(H(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 _w=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function qd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_w;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var $d={maxConnections:Ni,allow:[]},Oi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??$d.maxConnections,this.allow=t.allow??$d.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 qd(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 Ui=class extends Ln{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function _o(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 _n.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 Ao={addressSorter:Bn,maxParallelDials:Li,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Mr}},Mi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Ao.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Ao.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Ao.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Ao.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,fe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))_n.set(n,o);this.queue=new Ui({concurrency:t.maxParallelDials??Ao.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,fe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=_i(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),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 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())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),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",C.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:{[Ci]: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",C.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Dl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=_o([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return fe(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 E("Tried to dial self",C.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",C.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!==C.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!==C.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",C.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",C.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=>!vo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Dl=50,qt={minConnections:ki,maxConnections:Ni,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Di,autoDialDiscoveredPeersDebounce:10},Fi=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 E("Connection Manager maxConnections must be greater than minConnections",C.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=>se(o)),this.deny=(t.deny??[]).map(o=>se(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??qt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new vi({points:t.inboundConnectionThreshold??qt.inboundConnectionThreshold,duration:1}),this.autoDial=new Pi({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 Oi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Mi(e,{addressSorter:t.addressSorter??Bn,maxParallelDials:t.maxParallelDials??Li,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Mr},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(ru)]});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",C.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=_i(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),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Dl}),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)}};function Rw(r){return r[Symbol.asyncIterator]!=null}function Iw(...r){let e=[];for(let t of r)Rw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Si({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 So=Iw;var Vi=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",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Vt;for await(let s of So(...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",C.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(Ht.NOT_STARTED_YET,C.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(Ht.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Ki=globalThis.CustomEvent??Event;async function*Pl(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(y=>{m.done=!0,m.ok=!0,m.value=y,o.dispatchEvent(new Ki("task-complete"))},y=>{m.done=!0,m.err=y,o.dispatchEvent(new Ki("task-complete"))})}c=!0,o.dispatchEvent(new Ki("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ki("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 Hi=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",C.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",C.ERR_FIND_SELF);let n=this,o=So(...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(Ht.NOT_FOUND,C.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Nc(1024);for await(let s of Pl(async function*(){let i=So(...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 qi=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,fe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,fe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=_o([this.shutdownController.signal,e?.signal]);fe(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Nn(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,fe(1/0,this.walkController.signal);let e=_o([this.walkController.signal,this.shutdownController.signal]);fe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=wt(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 Ol=32,Ul=64,$i=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}`,C.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}`,C.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=xi.bind({ignoreUndefined:!0})({maxInboundStreams:Ol,maxOutboundStreams:Ul},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",C.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!==C.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 Ml=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 Gd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ml({name:e,metrics:t}):n=new Map,n}var zi=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=Gd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??$t.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",C.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,C.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)}`,C.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=C.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",C.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!==$t.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,C.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===$t.FATAL_ALL)throw new E(n,C.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 Fl=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 Yd(){return new Fl}var Gi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Vl=class extends Gi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Wd(r,e){let t=Yd();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 be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Vl("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 be:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Gi("unexpected end of input","ERR_UNEXPECTED_EOF");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 Yi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Ro(r,e={}){let t=Wd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??ct,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Yi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Yi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Bw=L(`
8
- `);async function Vr(r,e,t){await r.write(e,t)}async function jd(r,e,t){await r.writeV(e,t)}async function Tw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Bw[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 mr(r,e){let t=await Tw(r,e);return H(t.subarray())}async function Io(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Cw(r,e[0],t);let n=Ro(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} :`}};ff=nr;T.Constructed=ff;nr.NAME="CONSTRUCTED";var is=class extends Ue{fromBER(e,t,n){return t}toBER(e){return ht}};is.override="EndOfContentValueBlock";var hf,as=class extends Be{constructor(e={}){super(e,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};hf=as;T.EndOfContent=hf;as.NAME=Yn;var df,or=class extends Be{constructor(e={}){super(e,Ue),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}`}};df=or;T.Null=df;or.NAME="NULL";var cs=class extends Ft(Ue){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 Mt(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,ac.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="BooleanValueBlock";var pf,ls=class extends Be{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}`}};pf=ls;T.Boolean=pf;ls.NAME="BOOLEAN";var us=class extends Ft(Et){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=Et.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===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==af)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?Et.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 mf,Ot=class r extends Be{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?nr.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)}};mf=Ot;T.OctetString=mf;Ot.NAME=af;var fs=class extends Ft(Et){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=Et.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==cf)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(!Mt(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 Et.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 gf,sn=class extends Be{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 nr.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)}`}}};gf=sn;T.BitString=gf;sn.NAME=cf;var yf;function Qg(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 sf(r){if(r>=zn.length)for(let e=zn.length;e<=r;e++){let t=new Uint8Array([0]),n=zn[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)),zn.push(n)}return zn[r]}function Jg(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 Wn=class extends Ft(Ue){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=ac.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(rf(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=Jg(sf(n),t),i="-";break;default:t=Qg(t,sf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=of.charAt(t[c]));return a===!1&&(i+=of.charAt(0)),i}};yf=Wn;Wn.NAME="IntegerValueBlock";Object.defineProperty(yf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var wf,ge=class r extends Be{constructor(e={}){super(e,Wn),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 Gn,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()}`}};wf=ge;T.Integer=wf;ge.NAME="INTEGER";var bf,hs=class extends ge{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};bf=hs;T.Enumerated=bf;hs.NAME="ENUMERATED";var jn=class extends Ft(Ue){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(!Mt(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=rr(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}}};jn.NAME="sidBlock";var ds=class extends Ue{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.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 cc(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 jn;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 Ef,ft=class extends Be{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()}}};Ef=ft;T.ObjectIdentifier=Ef;ft.NAME="OBJECT IDENTIFIER";var Xn=class extends Ft(Pt){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(!Mt(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=rr(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}}};Xn.NAME="relativeSidBlock";var ps=class extends Ue{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 Xn;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 cc(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 Xn;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 xf,ms=class extends Be{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()}}};xf=ms;T.RelativeObjectIdentifier=xf;ms.NAME="RelativeObjectIdentifier";var vf,_e=class extends nr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};vf=_e;T.Sequence=vf;_e.NAME="SEQUENCE";var _f,gs=class extends nr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};_f=gs;T.Set=_f;gs.NAME="SET";var ys=class extends Ft(Ue){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 qe=class extends ns{constructor({...e}={}){super(e,ws)}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}};qe.NAME="SIMPLE STRING";var bs=class extends qe{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}};bs.NAME="Utf8StringValueBlock";var Af,Ut=class extends bs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Af=Ut;T.Utf8String=Af;Ut.NAME="UTF8String";var Es=class extends qe{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))}};Es.NAME="BmpStringValueBlock";var Sf,xs=class extends Es{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Sf=xs;T.BmpString=Sf;xs.NAME="BMPString";var vs=class extends qe{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=rr(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 Rf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Rf=_s;T.UniversalString=Rf;_s.NAME="UniversalString";var If,As=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};If=As;T.NumericString=If;As.NAME="NumericString";var Bf,Ss=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Bf=Ss;T.PrintableString=Bf;Ss.NAME="PrintableString";var Tf,Rs=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Tf=Rs;T.TeletexString=Tf;Rs.NAME="TeletexString";var Cf,Is=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Cf=Is;T.VideotexString=Cf;Is.NAME="VideotexString";var kf,Bs=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};kf=Bs;T.IA5String=kf;Bs.NAME="IA5String";var Nf,Ts=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Nf=Ts;T.GraphicString=Nf;Ts.NAME="GraphicString";var Lf,Zn=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Lf=Zn;T.VisibleString=Lf;Zn.NAME="VisibleString";var Df,Cs=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Df=Cs;T.GeneralString=Df;Cs.NAME="GeneralString";var Pf,ks=class extends qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Pf=ks;T.CharacterString=Pf;ks.NAME="CharacterString";var Of,Qn=class extends Zn{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]=ze(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ze(this.month,2),t[2]=ze(this.day,2),t[3]=ze(this.hour,2),t[4]=ze(this.minute,2),t[5]=ze(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}}};Of=Qn;T.UTCTime=Of;Qn.NAME="UTCTime";var Uf,Ns=class extends Qn{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(ze(this.year,4)),t.push(ze(this.month,2)),t.push(ze(this.day,2)),t.push(ze(this.hour,2)),t.push(ze(this.minute,2)),t.push(ze(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ze(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Uf=Ns;T.GeneralizedTime=Uf;Ns.NAME="GeneralizedTime";var Mf,Ls=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Mf=Ls;T.DATE=Mf;Ls.NAME="DATE";var Ff,Ds=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Ff=Ds;T.TimeOfDay=Ff;Ds.NAME="TimeOfDay";var Vf,Ps=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Vf=Ps;T.DateTime=Vf;Ps.NAME="DateTime";var Kf,Os=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Kf=Os;T.Duration=Kf;Os.NAME="Duration";var Hf,Us=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Hf=Us;T.TIME=Hf;Us.NAME="TIME";function t0(r){let{result:e}=cn(r),t=e.valueBlock.value;return{n:F(xt(t[1].toBigInt()),"base64url"),e:F(xt(t[2].toBigInt()),"base64url"),d:F(xt(t[3].toBigInt()),"base64url"),p:F(xt(t[4].toBigInt()),"base64url"),q:F(xt(t[5].toBigInt()),"base64url"),dp:F(xt(t[6].toBigInt()),"base64url"),dq:F(xt(t[7].toBigInt()),"base64url"),qi:F(xt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function r0(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 ge({value:0}),ge.fromBigInt(vt(L(r.n,"base64url"))),ge.fromBigInt(vt(L(r.e,"base64url"))),ge.fromBigInt(vt(L(r.d,"base64url"))),ge.fromBigInt(vt(L(r.p,"base64url"))),ge.fromBigInt(vt(L(r.q,"base64url"))),ge.fromBigInt(vt(L(r.dp,"base64url"))),ge.fromBigInt(vt(L(r.dq,"base64url"))),ge.fromBigInt(vt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function n0(r){let{result:e}=cn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:F(xt(t[0].toBigInt()),"base64url"),e:F(xt(t[1].toBigInt()),"base64url")}}function o0(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 or]}),new sn({valueHex:new _e({value:[ge.fromBigInt(vt(L(r.n,"base64url"))),ge.fromBigInt(vt(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function xt(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 vt(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 s0=16,uc=32,fc=1e4;async function i0(r,e){let t=Fe.get(),o=new _e({value:[new ge({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new or]}),new Ot({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=bt(s0),a=await sc(Mn,e,i,{c:fc,dkLen:uc}),c=bt(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 Ot({valueHex:i}),new ge({value:fc}),new ge({value:uc}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new or]})]}),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 Ot({valueHex:c})]})]})]}),d=new _e({value:[p,new Ot({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 a0(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}=cn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=c0(s),l=await sc(Mn,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Jn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=cn(h);n=qf(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=qf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return hc(n)}function c0(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=Jn(s.valueBlock.value[0].getValue()),a=fc,c=uc;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=Jn(u.valueBlock.value[1].getValue());return{cipherText:Jn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function qf(r){return Jn(r.valueBlock.value[2].getValue())}function Jn(r){return new Uint8Array(r,0,r.byteLength)}async function $f(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 Yf(e);return{privateKey:t[0],publicKey:t[1]}}async function dc(r){let t=[await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await l0(r)],n=await Yf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function zf(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 Gf(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 Yf(r){if(r.privateKey==null||r.publicKey==null)throw new E("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 l0(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 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 to=8192,eo=class{_key;constructor(e){this._key=e}verify(e,t){return Gf(this._key,t,e)}marshal(){return sr.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 rt(e)?e.then(({bytes:t})=>t):e.bytes}},ln=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return bt(16)}sign(e){return zf(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new eo(this._publicKey)}marshal(){return sr.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 rt(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 sr.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 hc(r){let e=sr.pkcs1ToJwk(r);if(Fs(e)>to)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await dc(e);return new ln(t.privateKey,t.publicKey)}function f0(r){let e=sr.pkixToJwk(r);if(Fs(e)>to)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new eo(e)}async function h0(r){if(Fs(r)>to)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await dc(r);return new ln(e.privateKey,e.publicKey)}async function d0(r){if(r>to)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await $f(r);return new ln(e.privateKey,e.publicKey)}var bc={};ve(bc,{Secp256k1PrivateKey:()=>no,Secp256k1PublicKey:()=>ro,generateKeyPair:()=>R0,unmarshalSecp256k1PrivateKey:()=>A0,unmarshalSecp256k1PublicKey:()=>S0});var p0=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]),ir=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ar=new Uint32Array(64),mc=class extends Zr{constructor(){super(64,32,8,!1),this.A=ir[0]|0,this.B=ir[1]|0,this.C=ir[2]|0,this.D=ir[3]|0,this.E=ir[4]|0,this.F=ir[5]|0,this.G=ir[6]|0,this.H=ir[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)ar[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=ar[l-15],h=ar[l-2],d=at(p,7)^at(p,18)^p>>>3,m=at(h,17)^at(h,19)^h>>>10;ar[l]=m+ar[l-7]+d+ar[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=at(a,6)^at(a,11)^at(a,25),h=f+p+Su(a,c,u)+p0[l]+ar[l]|0,m=(at(n,2)^at(n,13)^at(n,22))+Ru(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(){ar.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Wf=Uo(()=>new mc);function m0(r){let e=Vn(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:g0,hexToBytes:y0}=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:g0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?y0(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}`}},Vt=BigInt(0),ot=BigInt(1),T1=BigInt(2),jf=BigInt(3),C1=BigInt(4);function w0(r){let e=m0(r),{Fp:t}=e,n=e.toBytes||((d,m,y)=>{let g=m.toAffine();return Nt(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(d=>{let m=d.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function s(d){let{a:m,b:y}=e,g=t.sqr(d),w=t.mul(g,d);return t.add(t.add(w,t.mul(d,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Vt<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:g,n:w}=e;if(m&&typeof d!="bigint"){if(Qt(d)&&(d=Ct(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(y*2,"0")}let b;try{b=typeof d=="bigint"?d:kt(le("private key",d,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=Q(b,w)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,g){if(this.px=m,this.py=y,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(m){let{x:y,y:g}=m||{};if(!m||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let w=b=>t.eql(b,t.ZERO);return w(y)&&w(g)?l.ZERO:new l(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(g=>g.pz));return m.map((g,w)=>g.toAffine(y[w])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(o(le("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),w=s(m);if(!t.eql(g,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.eql(t.mul(y,v),t.mul(b,w)),_=t.eql(t.mul(g,v),t.mul(x,w));return S&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,g=t.mul(y,jf),{px:w,py:b,pz:x}=this,v=t.ZERO,S=t.ZERO,_=t.ZERO,R=t.mul(w,w),q=t.mul(b,b),$=t.mul(x,x),U=t.mul(w,b);return U=t.add(U,U),_=t.mul(w,x),_=t.add(_,_),v=t.mul(m,_),S=t.mul(g,$),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),_=t.mul(g,_),$=t.mul(m,$),U=t.sub(R,$),U=t.mul(m,U),U=t.add(U,_),_=t.add(R,R),R=t.add(_,R),R=t.add(R,$),R=t.mul(R,U),S=t.add(S,R),$=t.mul(b,x),$=t.add($,$),R=t.mul($,U),v=t.sub(v,R),_=t.mul($,q),_=t.add(_,_),_=t.add(_,_),new l(v,S,_)}add(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.ZERO,_=t.ZERO,R=t.ZERO,q=e.a,$=t.mul(e.b,jf),U=t.mul(y,b),ee=t.mul(g,x),D=t.mul(w,v),Je=t.add(y,g),I=t.add(b,x);Je=t.mul(Je,I),I=t.add(U,ee),Je=t.sub(Je,I),I=t.add(y,w);let N=t.add(b,v);return I=t.mul(I,N),N=t.add(U,D),I=t.sub(I,N),N=t.add(g,w),S=t.add(x,v),N=t.mul(N,S),S=t.add(ee,D),N=t.sub(N,S),R=t.mul(q,I),S=t.mul($,D),R=t.add(S,R),S=t.sub(ee,R),R=t.add(ee,R),_=t.mul(S,R),ee=t.add(U,U),ee=t.add(ee,U),D=t.mul(q,D),I=t.mul($,I),ee=t.add(ee,D),D=t.sub(U,D),D=t.mul(q,D),I=t.add(I,D),U=t.mul(ee,I),_=t.add(_,U),U=t.mul(N,I),S=t.mul(Je,S),S=t.sub(S,U),U=t.mul(Je,ee),R=t.mul(N,R),R=t.add(R,U),new l(S,_,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let g=t.invertBatch(y.map(w=>w.pz));return y.map((w,b)=>w.toAffine(g[b])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Vt)return y;if(a(m),m===ot)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:w,k1:b,k2neg:x,k2:v}=g.splitScalar(m),S=y,_=y,R=this;for(;b>Vt||v>Vt;)b&ot&&(S=S.add(R)),v&ot&&(_=_.add(R)),R=R.double(),b>>=ot,v>>=ot;return w&&(S=S.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),S.add(_)}multiply(m){a(m);let y=m,g,w,{endo:b}=e;if(b){let{k1neg:x,k1:v,k2neg:S,k2:_}=b.splitScalar(y),{p:R,f:q}=this.wNAF(v),{p:$,f:U}=this.wNAF(_);R=h.constTimeNegate(x,R),$=h.constTimeNegate(S,$),$=new l(t.mul($.px,b.beta),$.py,$.pz),g=R.add($),w=q.add(U)}else{let{p:x,f:v}=this.wNAF(y);g=x,w=v}return l.normalizeZ([g,w])[0]}multiplyAndAddUnsafe(m,y,g){let w=l.BASE,b=(v,S)=>S===Vt||S===ot||!v.equals(w)?v.multiplyUnsafe(S):v.multiply(S),x=b(this,y).add(b(m,g));return x.is0()?void 0:x}toAffine(m){let{px:y,py:g,pz:w}=this,b=this.is0();m==null&&(m=b?t.ONE:t.inv(w));let x=t.mul(y,m),v=t.mul(g,m),S=t.mul(w,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===ot)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===ot?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Ct(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=qo(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function b0(r){let e=Vn(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Xf(r){let e=b0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Vt<I&&I<t.ORDER}function a(I){return Q(I,n)}function c(I){return Ko(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=w0({...e,toBytes(I,N,V){let B=N.toAffine(),A=t.toBytes(B.x),k=Nt;return V?k(Uint8Array.from([N.hasEvenY()?2:3]),A):k(Uint8Array.from([4]),A,t.toBytes(B.y))},fromBytes(I){let N=I.length,V=I[0],B=I.subarray(1);if(N===o&&(V===2||V===3)){let A=kt(B);if(!i(A))throw new Error("Point is not on curve");let k=l(A),P;try{P=t.sqrt(k)}catch(H){let W=H instanceof Error?": "+H.message:"";throw new Error("Point is not on curve"+W)}let O=(P&ot)===ot;return(V&1)===1!==O&&(P=t.neg(P)),{x:A,y:P}}else if(N===s&&V===4){let A=t.fromBytes(B.subarray(0,t.BYTES)),k=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:A,y:k}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>Ct(er(I,e.nByteLength));function d(I){let N=n>>ot;return I>N}function m(I){return d(I)?a(-I):I}let y=(I,N,V)=>kt(I.slice(N,V));class g{constructor(N,V,B){this.r=N,this.s=V,this.recovery=B,this.assertValidity()}static fromCompact(N){let V=e.nByteLength;return N=le("compactSignature",N,V*2),new g(y(N,0,V),y(N,V,2*V))}static fromDER(N){let{r:V,s:B}=Rr.toSig(le("DER",N));return new g(V,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:V,s:B,recovery:A}=this,k=_(le("msgHash",N));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let P=A===2||A===3?V+e.n:V;if(P>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let O=A&1?"03":"02",K=u.fromHex(O+h(P)),H=c(P),W=a(-k*H),G=a(B*H),Y=u.BASE.multiplyAndAddUnsafe(K,W,G);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return wr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=Pa(e.n);return Ou(e.randomBytes(I),e.n)},precompute(I=8,N=u.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function b(I,N=!0){return u.fromPrivateKey(I).toRawBytes(N)}function x(I){let N=Qt(I),V=typeof I=="string",B=(N||V)&&I.length;return N?B===o||B===s:V?B===2*o||B===2*s:I instanceof u}function v(I,N,V=!0){if(x(I))throw new Error("first arg must be private key");if(!x(N))throw new Error("second arg must be public key");return u.fromHex(N).multiply(f(I)).toRawBytes(V)}let S=e.bits2int||function(I){let N=kt(I),V=I.length*8-e.nBitLength;return V>0?N>>BigInt(V):N},_=e.bits2int_modN||function(I){return a(S(I))},R=Fn(e.nBitLength);function q(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Vt<=I&&I<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return er(I,e.nByteLength)}function $(I,N,V=U){if(["recovered","canonical"].some(ae=>ae in V))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:A}=e,{lowS:k,prehash:P,extraEntropy:O}=V;k==null&&(k=!0),I=le("msgHash",I),P&&(I=le("prehashed msgHash",B(I)));let K=_(I),H=f(N),W=[q(H),q(K)];if(O!=null&&O!==!1){let ae=O===!0?A(t.BYTES):O;W.push(le("extraEntropy",ae))}let G=Nt(...W),Y=K;function pe(ae){let Ae=S(ae);if(!p(Ae))return;let Se=c(Ae),ye=u.BASE.multiply(Ae).toAffine(),Ne=a(ye.x);if(Ne===Vt)return;let At=a(Se*a(Y+Ne*H));if(At===Vt)return;let mr=(ye.x===Ne?0:2)|Number(ye.y&ot),Ln=At;return k&&d(At)&&(Ln=m(At),mr^=1),new g(Ne,Ln,mr)}return{seed:G,k2sig:pe}}let U={lowS:e.lowS,prehash:!1},ee={lowS:e.lowS,prehash:!1};function D(I,N,V=U){let{seed:B,k2sig:A}=$(I,N,V),k=e;return ka(k.hash.outputLen,k.nByteLength,k.hmac)(B,A)}u.BASE._setWindowSize(8);function Je(I,N,V,B=ee){let A=I;if(N=le("msgHash",N),V=le("publicKey",V),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:k,prehash:P}=B,O,K;try{if(typeof A=="string"||Qt(A))try{O=g.fromDER(A)}catch(ye){if(!(ye instanceof Rr.Err))throw ye;O=g.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:ye,s:Ne}=A;O=new g(ye,Ne)}else throw new Error("PARSE");K=u.fromHex(V)}catch(ye){if(ye.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(k&&O.hasHighS())return!1;P&&(N=e.hash(N));let{r:H,s:W}=O,G=_(N),Y=c(W),pe=a(G*Y),ae=a(H*Y),Ae=u.BASE.multiplyAndAddUnsafe(K,pe,ae)?.toAffine();return Ae?a(Ae.x)===H:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:D,verify:Je,ProjectivePoint:u,Signature:g,utils:w}}function E0(r){return{hash:r,hmac:(e,...t)=>$n(r,e,Ra(...t)),randomBytes:Xr}}function Zf(r,e){let t=n=>Xf({...r,...E0(n)});return Object.freeze({...t(e),create:t})}var eh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Qf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),x0=BigInt(1),gc=BigInt(2),Jf=(r,e)=>(r+e/gc)/e;function v0(r){let e=eh,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,p=ne(l,t,e)*f%e,h=ne(p,gc,e)*u%e,d=ne(h,o,e)*h%e,m=ne(d,s,e)*d%e,y=ne(m,a,e)*m%e,g=ne(y,c,e)*y%e,w=ne(g,a,e)*m%e,b=ne(w,t,e)*f%e,x=ne(b,i,e)*d%e,v=ne(x,n,e)*u%e,S=ne(v,gc,e);if(!yc.eql(yc.sqr(S),r))throw new Error("Cannot find square root");return S}var yc=Ho(eh,void 0,void 0,{sqrt:v0}),dt=Zf({a:BigInt(0),b:BigInt(7),Fp:yc,n:Qf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Qf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-x0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Jf(s*r,e),c=Jf(-n*r,e),u=Q(r-a*t-c*o,e),f=Q(-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}}}},Wf),F1=BigInt(0);var V1=dt.ProjectivePoint;function th(){return dt.utils.randomPrivateKey()}function rh(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(rt(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 nh(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(rt(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 oh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function sh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function wc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function ih(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var ro=class{_key;constructor(e){wc(e),this._key=e}verify(e,t){return nh(this._key,t,e)}marshal(){return oh(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 rt(e)?{bytes:t}=await e:t=e.bytes,t}},no=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??ih(e),sh(this._key),wc(this._publicKey)}sign(e){return rh(this._key,e)}get public(){return new ro(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 rt(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 A0(r){return new no(r)}function S0(r){return new ro(r)}async function R0(){let r=th();return new no(r)}var cr={rsa:pc,ed25519:oc,secp256k1:bc};function Ec(r){let e=Object.keys(cr).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function xc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return cr[r];throw Ec(r)}async function ah(r,e){return xc(r).generateKeyPair(e??2048)}function oo(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return cr.rsa.unmarshalRsaPublicKey(t);case oe.Ed25519:return cr.ed25519.unmarshalEd25519PublicKey(t);case oe.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Ec(e.Type??"unknown")}}function ch(r,e){return e=(e??"rsa").toLowerCase(),xc(e),r.bytes}async function so(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return cr.rsa.unmarshalRsaPrivateKey(t);case oe.Ed25519:return cr.ed25519.unmarshalEd25519PrivateKey(t);case oe.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Ec(e.Type??"RSA")}}function lh(r,e){return e=(e??"rsa").toLowerCase(),xc(e),r.bytes}var Xe=St(ph(),1);Xe.default.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);Xe.default.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);Xe.default.formatters.m=r=>r==null?"undefined":On.baseEncode(r);Xe.default.formatters.p=r=>r==null?"undefined":r.toString();Xe.default.formatters.c=r=>r==null?"undefined":r.toString();Xe.default.formatters.k=r=>r==null?"undefined":r.toString();Xe.default.formatters.a=r=>r==null?"undefined":r.toString();function F0(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 Hs(){return{forComponent(r){return V0(r)}}}function V0(r){let e=F0(`${r}:trace`);return Xe.default.enabled(`${r}:trace`)&&Xe.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Xe.default)(`${r}:trace`)),Object.assign((0,Xe.default)(r),{error:(0,Xe.default)(`${r}:error`),trace:e})}var gh=Symbol.for("nodejs.util.inspect.custom"),mh=Object.values(Wt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Wt.identity.decoder),yh=114,Ac=36,Sc=37,io=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()})`}[To]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return tt.createV1(yh,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 be(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[gh](){return`PeerId(${this.toString()})`}},Br=class extends io{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends io{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Cr=class extends io{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},vc=2336,_c=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Bt.digest(L(this.url))}[gh](){return`PeerId(${this.url})`}[To]=!0;toString(){return this.toCID().toString()}toCID(){return tt.createV1(vc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function wh(r){if(r.type==="RSA")return new Br(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Cr(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function be(r,e){if(e=e??mh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=gr(ie.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Cr({multihash:t}):new Br({multihash:t})}return dn(mh.decode(r))}function dn(r){try{let e=gr(r);if(e.code===Bt.code){if(e.digest.length===Ac)return new Tr({multihash:e});if(e.digest.length===Sc)return new Cr({multihash:e})}if(e.code===Re.code)return new Br({multihash:e})}catch{return K0(tt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function K0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==yh&&r.code!==vc)throw new Error("Supplied PeerID CID is invalid");if(r.code===vc){let t=F(r.multihash.digest);return new _c(new URL(t))}let e=r.multihash;if(e.code===Re.code)return new Br({multihash:r.multihash});if(e.code===Bt.code){if(e.digest.length===Ac)return new Tr({multihash:r.multihash});if(e.digest.length===Sc)return new Cr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function pn(r,e){return r.length===Ac?new Tr({multihash:mt(Bt.code,r),privateKey:e}):r.length===Sc?new Cr({multihash:mt(Bt.code,r),privateKey:e}):new Br({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 Ze=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=>[be(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,be(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=>be(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=be(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=be(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mn(this.set.values(),e=>be(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 _h=Symbol.for("@achingbrain/uint8arraylist");function vh(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 $s(r){return!!r?.[_h]}var Ee=class r{bufs;length;[_h]=!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($s(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($s(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=vh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=vh(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($s(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(!$s(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=Le(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=it(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=it(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=it(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=Le(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=it(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=it(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=it(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=it(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=it(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 Rc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Rc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=it(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 kr(r,e){return Math.floor(Math.random()*(e-r))+r}var Nr=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=kr(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 Ic={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ah={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Sh=new globalThis.TextEncoder;function H0(r,e){let t=Ic[e],n=Ah[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function q0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ic[e],o=Ah[e],s=r;for(;s.length>0;){let i=Sh.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 Bc(r,{size:e=32,utf8Buffer:t}={}){if(!Ic[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 q0(r,e,t);r=Sh.encode(r)}return H0(r,e)}var $0=St(xh(),1);var co={hash:r=>Number(Bc(r,{size:32})),hashV:(r,e)=>z0(co.hash(r,e))};function z0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var G0=500,lo=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??co,this.seed=e.seed??kr(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 Nr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Nr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[kr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Nr(this.bucketSize));for(let a=0;a<G0;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 Nr(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))<=95}},Y0={1:.5,2:.84,4:.95,8:.98};function W0(r=.001){return r>.002?2:r>1e-5?4:8}function Rh(r,e=.001){let t=W0(e),n=Y0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log(o/t))+2,Rc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var zs=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??co,this.seed=e.seed??kr(0,Math.pow(2,10)),this.filterSeries=[new lo({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 lo({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 Tc(r,e=.001,t){return new zs({...Rh(r,e),...t??{}})}var Ih=async()=>{let r=await ah("Ed25519"),e=await j0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function j0(r){return pn(ch(r.public),lh(r))}var Bh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var uo;(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())})(uo||(uo={}));var gn=class r{static createFromProtobuf=async e=>{let t=uo.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=Th(n,o,s),c=await(await so(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",Bh.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=uo.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=Th(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return oo(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Th=(r,e,t)=>{let n=L(r),o=Pe(n.byteLength),s=Pe(e.length),i=Pe(t.length);return new Ee(o,n,s,e,i,t)};function Ch(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 Gs=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 kh=45,X0=15,yn=new Gs;function Cc(r){if(!(r.length>X0))return yn.new(r).parseWith(()=>yn.readIPv4Addr())}function kc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>kh))return yn.new(r).parseWith(()=>yn.readIPv6Addr())}function Ys(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>kh))return yn.new(r).parseWith(()=>yn.readIPAddr())}var N_=parseInt("0xFFFF",16),L_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function wn(r){return!!Cc(r)}function bn(r){return!!kc(r)}function Ws(r){return!!Ys(r)}var Dh=wn,ty=bn,Nc=function(r){let e=0;if(r=r.toString().trim(),Dh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(ty(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Dh(t[n]),i;s&&(i=Nc(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")},Ph=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={},Lc={},ny=[[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"]];ny.forEach(r=>{let e=oy(...r);Lc[e.code]=e,En[e.name]=e});function oy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(Lc[r]!=null)return Lc[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 gA=Z("ip4"),yA=Z("ip6"),wA=Z("ipcidr");function Uc(r,e){switch(Z(r).code){case 4:case 41:return iy(e);case 42:return Oc(e);case 6:case 273:case 33:case 132:return Mh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Oc(e);case 421:return uy(e);case 444:return Uh(e);case 445:return Uh(e);case 466:return ly(e);case 481:return globalThis.encodeURIComponent(Oc(e));default:return F(e,"base16")}}function Mc(r,e){switch(Z(r).code){case 4:return Oh(e);case 41:return Oh(e);case 42:return Pc(e);case 6:case 273:case 33:case 132:return Fc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Pc(e);case 421:return ay(e);case 444:return fy(e);case 445:return hy(e);case 466:return cy(e);case 481:return Pc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var Dc=Object.values(Wt).map(r=>r.decoder),sy=function(){let r=Dc[0].or(Dc[1]);return Dc.slice(2).forEach(e=>r=r.or(e)),r}();function Oh(r){if(!Ws(r))throw new Error("invalid ip address");return Nc(r)}function iy(r){let e=Ph(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ws(e))throw new Error("invalid ip address");return e}function Fc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Mh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Pc(r){let e=L(r),t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function Oc(r){let e=lt(r);if(r=r.slice(me(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function ay(r){let e;r[0]==="Q"||r[0]==="1"?e=gr(ie.decode(`z${r}`)).bytes:e=tt.parse(r).multihash.bytes;let t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function cy(r){let e=sy.decode(r),t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function ly(r){let e=lt(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function uy(r){let e=lt(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function fy(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=Ge.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=Fc(n);return Ie([t,o],t.length+o.length)}function hy(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=Ge.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=Fc(n);return Ie([t,o],t.length+o.length)}function Uh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Mh(t);return`${n}:${o}`}function Fh(r){r=Vc(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=Z(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Kh("invalid address: "+r);if(a.path===!0){n=Vc(o.slice(s).join("/")),e.push([a.code,Mc(a.code,n)]),t.push([a.code,n]);break}let c=Mc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Uc(a.code,c)])}return{string:Vh(t),bytes:Hc(e),tuples:e,stringTuples:t,path:n}}function Kc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=me(s),a=Z(s),c=dy(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 Kh("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=Uc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Vh(t),tuples:e,stringTuples:t,path:n}}function Vh(r){let e=[];return r.map(t=>{let n=Z(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Vc(e.join("/"))}function Hc(r){return Ie(r.map(e=>{let t=Z(e[0]),n=Uint8Array.from(Pe(t.code));return e.length>1&&e[1]!=null&&(n=Ie([n,e[1]])),n}))}function dy(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+me(t)}}function Vc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Kh(r){return new Error("Error parsing address: "+r)}var py=Symbol.for("nodejs.util.inspect.custom"),qc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),my=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],js=class r{bytes;#e;#t;#s;#a;[qc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Kc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Fh(e)}else if(lr(e))t=Kc(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=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),my.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=Z(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=Z(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({},Z(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Z(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(Hc(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"?F(ie.decode(`z${n}`),"base58btc"):F(tt.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 E(`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)}[py](){return`Multiaddr(${this.#e})`}};var xn=new Map;function lr(r){return!!r?.[qc]}function se(r){return new js(r)}var Hh="libp2p-peer-record",qh=Uint8Array.from([3,1]);var fo;(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())})(fo||(fo={}));var Lr=class r{static createFromProtobuf=e=>{let t=fo.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=Hh;static CODEC=qh;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=fo.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||!Ch(this.multiaddrs,e.multiaddrs))}};function gy(r){return r[Symbol.asyncIterator]!=null}function yy(r){if(gy(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 ho=yy;var zc=St(zh(),1);var mo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Gc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Gh=r=>globalThis.DOMException===void 0?new Gc(r):new DOMException(r),Yh=r=>{let e=r.reason===void 0?Gh("This operation was aborted."):r.reason;return e instanceof Error?e:Gh(e)};function go(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(Yh(p)),p.addEventListener("abort",()=>{f(Yh(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new mo;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 Yc(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 yo=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=Yc(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 ur=class extends zc.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:yo,...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=go(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 mo&&!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 fr={},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)=>{fr[r]==null&&(fr[r]=[]),fr[r].push(e)};vn.removeEventListener=(r,e)=>{fr[r]!=null&&(fr[r]=fr[r].filter(t=>t===e))};vn.dispatchEvent=function(r,e,t){fr[r]!=null&&fr[r].forEach(n=>n(e,t))};var Wc=vn;var jc="lock:worker:request-read",Xc="lock:worker:release-read",Zc="lock:master:grant-read",Qc="lock:worker:request-write",Jc="lock:worker:release-write",el="lock:master:grant-write";var Wh=(r=21)=>Math.random().toString().substring(2);var jh=(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)})}}}))},Xh=(r,e,t,n)=>async()=>{let o=Wh();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)})},Ey={singleProcess:!1},Zh=r=>{if(r=Object.assign({},Ey,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Wc.addEventListener("message",jh(t,"requestReadLock",jc,Xc,Zc)),Wc.addEventListener("message",jh(t,"requestWriteLock",Qc,Jc,el)),t}return{isWorker:!0,readLock:t=>Xh(t,jc,Zc,Xc),writeLock:t=>Xh(t,Qc,el,Jc)}};var Dr={},hr;async function tl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>go((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var xy=(r,e)=>{if(hr.isWorker===!0)return{readLock:hr.readLock(r,e),writeLock:hr.writeLock(r,e)};let t=new ur({concurrency:1}),n;return{async readLock(){if(n!=null)return tl(n,e);n=new ur({concurrency:e.concurrency,autoStart:!1});let o=n,s=tl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,tl(t,e)}}},vy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function rl(r){let e=Object.assign({},vy,r);return hr==null&&(hr=Zh(e),hr.isWorker!==!0&&(hr.addEventListener("requestReadLock",t=>{Dr[t.data.name]!=null&&Dr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),hr.addEventListener("requestWriteLock",async t=>{Dr[t.data.name]!=null&&Dr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Dr[e.name]==null&&(Dr[e.name]=xy(e.name,e)),Dr[e.name]}var Te={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),Qs.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=Qs.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),Zs.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(Zs.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 Zs;(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())})(Zs||(Zs={}));var Qs;(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())})(Qs||(Qs={}));function An(r,e){let t=_n.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=wh({...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="/",Qh=new TextEncoder().encode(Ht),Js=Qh[0],Pr=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]!==Js)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(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=Qh),this._buf[0]!==Js){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Js,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Js;)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 _y(this.baseNamespace())}name(){return Ay(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(),...Sy(e.map(t=>t.namespaces()))])}};function _y(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Ay(r){let e=r.split(":");return e[e.length-1]}function Sy(r){return[].concat(...r)}var nl="/peers/";function Sn(r){if(!Co(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pr(`${nl}${e}`)}async function Jh(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)),!lr(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 ti(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(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=ei(l,{validate:ed})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ei(l,{validate:td,map:rd})}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=ei([...a.entries()],{validate:ed})}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=ei([...p.entries()],{validate:td,map:rd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Jh(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 ei(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 ed(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 td(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 rd(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 ri(r,e,t){let n=r.toString().split("/")[2],o=Ge.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 Ry(r,e){return r==null?{}:{prefix:nl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ri(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ri(n.key,n.value,e),ri(o.key,o.value,e)))}}var ni=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=rl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.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 ti(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 ti(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 ti(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Ze;for await(let{key:n,value:o}of this.datastore.query(Ry(e??{},t))){let s=ri(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 oi=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 ni(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 ho(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,Lr.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=Lr.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=Lr.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 Iy(r){return r[Symbol.asyncIterator]!=null}function By(r){if(Iy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ol=By;function Ty(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 nd=Ty;function Cy(r){return r[Symbol.asyncIterator]!=null}function ky(r,e){let t=0;if(Cy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=nd(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 Or=ky;function Ny(r){return r[Symbol.asyncIterator]!=null}function Ly(r,e){return Ny(r)?async function*(){yield*(await ho(r)).sort(e)}():function*(){yield*ho(r).sort(e)}()}var sl=Ly;function Dy(r){return r[Symbol.asyncIterator]!=null}function Py(r,e){return Dy(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 il=Py;var si=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 ol(this.putMany(e,n)),e=[],await ol(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=Or(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Or(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>sl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Or(n,()=>o++>=s)}return e.limit!=null&&(n=il(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Or(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Or(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>sl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Or(n,()=>s++>=o)}return e.limit!=null&&(n=il(n,e.limit)),n}};var id=St(al(),1);function ad(r){return r=r??new Error("Not Found"),(0,id.default)(r,"ERR_NOT_FOUND")}var ii=class extends si{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 ad();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 Pr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Pr(e)}};function cd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var My=r=>r;function cl(r,e){let t=r.getPeerId();return t!=null&&be(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var ai=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??My,this._updatePeerStoreAddresses=cd(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=cl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=cl(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=cl(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 ll=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=Hs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>eu(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")}},Fy=["metrics","connectionProtector","dns"],Vy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ld(r={}){let e=new ll(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Vy.includes(o)){let i=e.components[o];if(i==null&&!Fy.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 ud(r){let e={};for(let t of Object.values(r.components))for(let n of Ky(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Hy(t))if(e[n]!==!0)throw new E(`Service "${qy(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 Ky(r){return Array.isArray(r?.[ra])?r[ra]:[]}function Hy(r){return Array.isArray(r?.[na])?r[na]:[]}function qy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var hd=St(fd(),1),$y=["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"],zy=$y.map(r=>new hd.Netmask(r));function Gy(r){for(let e of zy)if(e.contains(r))return!0;return!1}function Yy(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.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 ci(r){return wn(r)?Gy(r):bn(r)?Yy(r):void 0}function dd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ci(`${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 Wy=r=>r.toString().split("/").slice(1),bo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),j=r=>({match:e=>bo(t=>t===r).match(e),pattern:r}),fi=()=>({match:r=>bo(e=>typeof e=="string").match(r),pattern:"{string}"}),hi=()=>({match:r=>bo(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{ie.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),li=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ea.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),xe=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),st=(...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(", ")})`}),J=(...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 he(...r){function e(o){let s=Wy(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 fl=J(j("dns4"),fi()),hl=J(j("dns6"),fi()),dl=J(j("dnsaddr"),fi()),pd=J(j("dns"),fi()),qS=he(fl),$S=he(hl),zS=he(dl),GS=he(st(pd,dl,fl,hl)),md=J(j("ip4"),bo(wn)),gd=J(j("ip6"),bo(bn)),yd=st(md,gd),_t=st(yd,pd,fl,hl,dl),YS=he(_t),WS=he(md),jS=he(gd),XS=he(yd),pl=J(_t,j("tcp"),hi()),Eo=J(_t,j("udp"),hi()),ZS=he(pl),QS=he(Eo),ml=J(Eo,j("quic")),di=J(Eo,j("quic-v1")),jy=st(ml,di),JS=he(ml),eR=he(di),ul=st(_t,pl,Eo,ml,di),wd=st(J(ul,j("ws"),xe(Ce()))),tR=he(wd),bd=st(J(ul,j("wss"),xe(Ce())),J(ul,j("tls"),j("ws"),xe(Ce()))),rR=he(bd),Ed=J(Eo,j("webrtc-direct"),xe(li()),xe(li()),xe(Ce())),nR=he(Ed),xd=J(di,j("webtransport"),xe(li()),xe(li()),xe(Ce())),oR=he(xd),ui=st(wd,bd,J(pl,xe(Ce())),J(jy,xe(Ce())),J(_t,xe(Ce())),Ed,xd,Ce()),sR=he(ui),Xy=J(ui,j("p2p-circuit"),Ce()),xo=he(Xy),Zy=st(J(ui,j("p2p-circuit"),j("webrtc"),xe(Ce())),J(ui,j("webrtc"),xe(Ce())),j("webrtc")),iR=he(Zy),Qy=st(J(_t,j("tcp"),hi(),j("http"),xe(Ce())),J(_t,j("http"),xe(Ce()))),aR=he(Qy),Jy=st(J(_t,j("tcp"),st(J(j("443"),j("http")),J(hi(),j("https"))),xe(Ce())),J(_t,j("tls"),j("http"),xe(Ce())),J(_t,j("https"),xe(Ce()))),cR=he(Jy);function gl(r){try{let{address:e}=r.nodeAddress();return!!ci(e)}catch{return!0}}function ew(r,e){let t=gl(r.multiaddr),n=gl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function tw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function rw(r,e){let t=xo.exactMatch(r.multiaddr),n=xo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rn(r,e){let t=ew(r,e);if(t!==0)return t;let n=rw(r,e);return n!==0?n:tw(r,e)}var de=class extends Event{constructor(e,t){super(e),this.detail=t}};function pi(r){let e=[Qe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var yl=60;function mi(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:Qe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Qe[e.type],TTL:e.TTL??e.ttl??yl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var nw=4;function wl(r,e={}){let t=new ur({concurrency:e.queryConcurrency??nw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(o.types).forEach(a=>{s.append("type",Qe[a])}),o.onProgress?.(new de("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=mi(await a.json());return o.onProgress?.(new de("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function vd(){return[wl("https://cloudflare-dns.com/dns-query"),wl("https://dns.google/resolve")]}var Sd=St(Ad(),1);var bl=class{lru;constructor(e){this.lru=(0,Sd.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 mi({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:Qe[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??yl)*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 Rd(r){return new bl(r)}var ow=1e3,gi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Rd(e.cacheSize??ow),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["."]=vd())}async query(e,t={}){let n=pi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("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 de("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Qe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Qe||(Qe={}));function Id(r={}){return new gi(r)}var sw=32,{code:iw}=Z("dnsaddr"),Ur=async function(e,t={}){let n=t.maxRecursiveDepth??sw;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===iw)??[],i=await(t?.dns??Id()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Qe.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 p=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...p.map(h=>h.toString()))}else c.push(l.toString())}return c};var Od=St(Pd(),1),bi=Od.default;var qt;(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"})(qt||(qt={}));var C;(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"})(C||(C={}));var hw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ur},addressSorter:Rn},transportManager:{faultTolerance:zt.FATAL_ALL}};async function Ud(r){let e=bi(hw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(qt.ERR_PROTECTOR_REQUIRED,C.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await pn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",C.ERR_INVALID_KEY);return e}var Md=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},dw=new WeakMap;function pw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Md());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Md())},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}),dw.set(l,()=>{c(s),s=null,i()}),l}}var mw=pw(),Fd=mw;var Ei=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 xl}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 Fd(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)}},xl=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 xi(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:be(t),r.forEach(n=>{if(!lr(n))throw new E("Invalid Multiaddr",C.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",C.ERR_INVALID_PARAMETERS)}else{let s=be(o);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",C.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 vi=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}},Tn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vi(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 vi(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 vl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function _i(r={}){return gw(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 gw(r,e){e=e??{};let t=e.onEnd,n=new Tn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new Tn,s!=null?s({error:y}):(n.push({error:y}),o)),l=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},p=y=>i?o:(i=!0,y!=null?f(y):u({done:!0})),h=()=>(n=new Tn,p(),{done:!0}),d=y=>(p(y),{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 y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let w,b;g!=null&&(w=new Promise((x,v)=>{b=()=>{v(new vl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}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(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(y){return m.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}var _l=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 _l(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 Ai=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 dr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Ai(t?.errorMessage,t?.errorCode));let n,o=new Ai(t?.errorMessage,t?.errorCode);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 Si=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 yw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ri=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=yw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,fe(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 Si(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 dr(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 Rt{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 Ri(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=_i({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 Ii=class extends kn{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 Ti=5,Ci=100,ki=50,Ni=1e3*60*7;var Mr={minConnections:Ti,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Ni,autoDialDiscoveredPeersDebounce:10},Li=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??Mr.minConnections,this.autoDialPriority=t.autoDialPriority??Mr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Mr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Mr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Mr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Mr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ii({concurrency:t.autoDialConcurrency??Mr.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 Ze;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 bw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Vd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??bw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Kd={maxConnections:Ci,allow:[]},Di=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kd.maxConnections,this.allow=t.allow??Kd.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 Ze;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 Vd(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 Pi=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 vo(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 Hd(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 _o={addressSorter:Rn,maxParallelDials:ki,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ur}},Oi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??_o.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??_o.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??_o.maxDialQueueLength,this.dialTimeout=t.dialTimeout??_o.dialTimeout,this.connections=t.connections??new Ze,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,fe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))xn.set(n,o);this.queue=new Pi({concurrency:t.maxParallelDials??_o.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,fe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=xi(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 de("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 de("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 de("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new de("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 de("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",C.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",C.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??kl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=vo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return fe(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 E("Tried to dial self",C.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",C.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!==C.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!==C.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 Hd(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",C.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",C.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=>!xo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var kl=50,$t={minConnections:Ti,maxConnections:Ci,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Ni,autoDialDiscoveredPeersDebounce:10},Ui=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??$t.maxConnections;let n=t.minConnections??$t.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",C.ERR_INVALID_PARAMETERS);this.connections=new Ze,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??$t.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Ei({points:t.inboundConnectionThreshold??$t.inboundConnectionThreshold,duration:1}),this.autoDial=new Li({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??$t.autoDialConcurrency,autoDialPriority:t.autoDialPriority??$t.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??$t.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??$t.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??$t.autoDialMaxQueueLength}),this.connectionPruner=new Di({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Oi(e,{addressSorter:t.addressSorter??Rn,maxParallelDials:t.maxParallelDials??ki,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ur},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(Jl)]});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",C.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=xi(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 de("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??kl}),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)}};function vw(r){return r[Symbol.asyncIterator]!=null}function _w(...r){let e=[];for(let t of r)vw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=_i({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 Ao=_w;var Mi=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",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Kt;for await(let s of Ao(...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",C.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(qt.NOT_STARTED_YET,C.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(qt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Fi=globalThis.CustomEvent??Event;async function*Nl(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(y=>{m.done=!0,m.ok=!0,m.value=y,o.dispatchEvent(new Fi("task-complete"))},y=>{m.done=!0,m.err=y,o.dispatchEvent(new Fi("task-complete"))})}c=!0,o.dispatchEvent(new Fi("task-complete"))}catch(d){u=d,o.dispatchEvent(new Fi("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 Vi=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",C.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",C.ERR_FIND_SELF);let n=this,o=Ao(...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(qt.NOT_FOUND,C.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Tc(1024);for await(let s of Nl(async function*(){let i=Ao(...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 Ki=class extends Rt{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,fe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,fe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=vo([this.shutdownController.signal,e?.signal]);fe(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,fe(1/0,this.walkController.signal);let e=vo([this.walkController.signal,this.shutdownController.signal]);fe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=bt(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 dr(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 Ll=32,Dl=64,Hi=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}`,C.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}`,C.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=bi.bind({ignoreUndefined:!0})({maxInboundStreams:Ll,maxOutboundStreams:Dl},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",C.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!==C.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 Pl=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 qd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Pl({name:e,metrics:t}):n=new Map,n}var qi=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=qd({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 E("Transport must have a valid tag",C.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,C.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)}`,C.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new de("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=C.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",C.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!==zt.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,C.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 E(n,C.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 Ol=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 dr(this.readNext.promise,t?.signal,t)}};function $d(){return new Ol}var $i=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ul=class extends $i{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function zd(r,e){let t=$d();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 Ee;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Ul("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 Ee:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new $i("unexpected end of input","ERR_UNEXPECTED_EOF");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 zi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function So(r,e={}){let t=zd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??Pe;return{read:async i=>{let a=-1,c=new Ee;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new zi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new zi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new Ee(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Ee(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Aw=L(`
8
+ `);async function Fr(r,e,t){await r.write(e,t)}async function Gd(r,e,t){await r.writeV(e,t)}async function Sw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Aw[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 pr(r,e){let t=await Sw(r,e);return F(t.subarray())}async function Ro(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Rw(r,e[0],t);let n=So(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 jd(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===Ce&&(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 Vr(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 E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Cw(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=Ro({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async w=>{let{sink:b}=d.unwrap();await b(async function*(){let x=!1;for await(let v of w){if(u&&await f.promise,c)yield v;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ce,e,v.byteLength);let S=`${e}
12
- `;yield new be(Uint8Array.from([19]),L(`${Ce}
13
- `),De(S.length),L(S),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ce,e,v.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 y()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await g())}finally{i=!1,s=!0,a.resolve()}}async function y(){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 Gd(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await pr(n,t);if(t.log.trace('select: read "%s"',a),a===ke&&(t.log.trace("select: reading protocol response"),a=await pr(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 pr(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 Rw(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=So({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async w=>{let{sink:b}=d.unwrap();await b(async function*(){let x=!1;for await(let v of w){if(u&&await f.promise,c)yield v;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',ke,e,v.byteLength);let S=`${e}
12
+ `;yield new Ee(Uint8Array.from([19]),L(`${ke}
13
+ `),Pe(S.length),L(S),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',ke,e,v.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 y()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await g())}finally{i=!1,s=!0,a.resolve()}}async function y(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',ke,e),await d.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 w=await mr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===Ce&&(w=await mr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',w,e),w!==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 w=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 w(b)}}if(r.closeWrite!=null){let w=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 w(b)}}if(r.close!=null){let w=r.close.bind(r);r.close=async b=>{let x=[];u&&x.push(f.promise),p&&x.push(h.promise),x.length>0?await pr(Promise.all(x),b?.signal):(s=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}function Wi(r){return r[Symbol.asyncIterator]!=null}var ji=r=>{let e=pe(r),t=Ne(e);return De(r,t),ji.bytes=e,t};ji.bytes=0;function Xi(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 Wi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Xi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ji;return new be(t(r.byteLength),r)};var Dn=At(ul(),1);var kw=8,Nw=1024*1024*4,Kr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Kr||(Kr={}));var ql=r=>{let e=ct(r);return ql.bytes=pe(e),e};ql.bytes=0;function Hl(r,e){let t=new be,n=Kr.LENGTH,o=-1,s=e?.lengthDecoder??ql,i=e?.maxLengthLength??kw,a=e?.maxDataLength??Nw;function*c(){for(;t.byteLength>0;){if(n===Kr.LENGTH)try{if(o=s(t),o<0)throw(0,Dn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Dn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Kr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Dn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Kr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Kr.LENGTH}}}return Wi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Dn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Dn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Hl.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 Hl(n,{...e??{},onLength:s=>{t=s}})};async function Bo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Ro(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===Ce){t.log.trace('handle: respond with "%s" for "%s"',Ce,o),await Vr(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 Vr(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 be(...e.map(i=>Xi.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 g(){if(p){await h.promise;return}p=!0;try{t.log.trace("optimistic: reading multistream select header");let w=await pr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===ke&&(w=await pr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',w,e),w!==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 w=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 w(b)}}if(r.closeWrite!=null){let w=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 w(b)}}if(r.close!=null){let w=r.close.bind(r);r.close=async b=>{let x=[];u&&x.push(f.promise),p&&x.push(h.promise),x.length>0?await dr(Promise.all(x),b?.signal):(s=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}function Gi(r){return r[Symbol.asyncIterator]!=null}var Yi=r=>{let e=me(r),t=Le(e);return Pe(r,t),Yi.bytes=e,t};Yi.bytes=0;function Wi(r,e){e=e??{};let t=e.lengthEncoder??Yi;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Gi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Wi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Yi;return new Ee(t(r.byteLength),r)};var Nn=St(al(),1);var Iw=8,Bw=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Vl=r=>{let e=lt(r);return Vl.bytes=me(e),e};Vl.bytes=0;function Fl(r,e){let t=new Ee,n=Vr.LENGTH,o=-1,s=e?.lengthDecoder??Vl,i=e?.maxLengthLength??Iw,a=e?.maxDataLength??Bw;function*c(){for(;t.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(t),o<0)throw(0,Nn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Nn.default)(new Error("message length too long"),"ERR_MSG_DATA_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(0,Nn.default)(new Error("message length length too long"),"ERR_MSG_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 Gi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Fl.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 Fl(n,{...e??{},onLength:s=>{t=s}})};async function Io(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=So(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await pr(n,t);if(t.log.trace('handle: read "%s"',o),o===ke){t.log.trace('handle: respond with "%s" for "%s"',ke,o),await Fr(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 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 Ee(...e.map(i=>Wi.single(L(`${i}
18
18
  `))),L(`
19
- `));t.log.trace('handle: respond with "%s" for %s',e,o),await Vr(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 Vr(n,L(`na
20
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var Dw=500,$l=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";[tu]=!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(Dw);fe(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 Zd(r){return new $l(r)}var Pw=3e4;function Ow(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Ol}function Uw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Ul}function Qd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Zi=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}`,C.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",C.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}),fe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",C.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){({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",C.ERR_INVALID_MULTIADDR);let h=we(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){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=we(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",C.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:y,protocol:g}=await Bo(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let w=Ow(g,this.components.registrar);if(Qd(g,"inbound",l)===w){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${w}`,C.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=y.source,d.sink=y.sink,d.protocol=g,y.closeWrite!=null&&(d.closeWrite=y.closeWrite),y.closeRead!=null&&(d.closeRead=y.closeRead),y.close!=null&&(d.close=y.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",C.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let y=await u.newStream();l.log.trace("started new stream %s for protocols %s",y.id,d);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(Pw);fe(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:w}=await Io(y,d,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",w);let b=Uw(w,this.components.registrar,m),x=Qd(w,"outbound",l);if(x>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - ${x}/${b}`,C.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[w]}),y.source=g.source,y.sink=g.sink,y.protocol=w,g.closeWrite!=null&&(y.closeWrite=g.closeWrite),g.closeRead!=null&&(y.closeRead=g.closeRead),g.close!=null&&(y.close=g.close),this.components.metrics?.trackProtocolStream(y,l),y}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new E(String(g),C.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",C.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Zd({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 Bo(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,C.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 Io(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,C.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 Io(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),C.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 Bo(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),C.ERR_MUXER_UNAVAILABLE)}}};var Jd="1.7.0",ep="libp2p";var zl=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 oa(a.type,{detail:a.detail}));return c||u},fe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??$s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=hd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:ep,version:Jd},logger:this.logger,events:t,datastore:e.datastore??new ci,connectionGater:gd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new ii(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 Zi(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 zi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Fi(this.components,e.connectionManager)),this.configureComponent("registrar",new $i(this.components)),this.configureComponent("addressManager",new li(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 Hi(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 Vi(this.components,{routers:i})),this.configureComponent("randomWalk",new qi(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[Ji]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ji])),u[ra]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ra])),u[ea]!=null&&(this.log("registering service %s for peer discovery",a),u[ea].addEventListener?.("peer",f=>{this.#e(f)}))}dd(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 Vt;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",C.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",C.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={}){lr(e)&&(e=we(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!==C.ERR_NOT_FOUND)throw s}let n=Re([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return so(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(C.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function tp(r={}){let e=r.peerId??=await Ch();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await io(e.privateKey),new zl(await Vd(r))}async function Fw(r={}){let e=await tp(r);return r.start!==!1&&await e.start(),e}return mp(Vw);})();
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 Cw=500,Kl=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";[Ql]=!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(Cw);fe(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 Wd(r){return new Kl(r)}var kw=3e4;function Nw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Ll}function Lw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Dl}function jd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var ji=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}`,C.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",C.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}),fe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",C.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 de("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",C.ERR_INVALID_MULTIADDR);let h=be(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new de("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=be(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",C.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:y,protocol:g}=await Io(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let w=Nw(g,this.components.registrar);if(jd(g,"inbound",l)===w){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${w}`,C.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=y.source,d.sink=y.sink,d.protocol=g,y.closeWrite!=null&&(d.closeWrite=y.closeWrite),y.closeRead!=null&&(d.closeRead=y.closeRead),y.close!=null&&(d.close=y.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",C.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let y=await u.newStream();l.log.trace("started new stream %s for protocols %s",y.id,d);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(kw);fe(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:w}=await Ro(y,d,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",w);let b=Lw(w,this.components.registrar,m),x=jd(w,"outbound",l);if(x>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - ${x}/${b}`,C.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[w]}),y.source=g.source,y.sink=g.sink,y.protocol=w,g.closeWrite!=null&&(y.closeWrite=g.closeWrite),g.closeRead!=null&&(y.closeRead=g.closeRead),g.close!=null&&(y.close=g.close),this.components.metrics?.trackProtocolStream(y,l),y}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new E(String(g),C.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",C.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Wd({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 Io(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,C.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 Ro(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,C.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 Ro(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),C.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 Io(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),C.ERR_MUXER_UNAVAILABLE)}}};var Xd="1.8.0-ce6da9896",Zd="libp2p";var Hl=class extends Rt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Rt,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new ta(a.type,{detail:a.detail}));return c||u},fe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Hs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=ld({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Zd,version:Xd},logger:this.logger,events:t,datastore:e.datastore??new ii,connectionGater:dd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new oi(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 ji(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 qi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ui(this.components,e.connectionManager)),this.configureComponent("registrar",new Hi(this.components)),this.configureComponent("addressManager",new ai(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 Vi(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 Mi(this.components,{routers:i})),this.configureComponent("randomWalk",new Ki(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[Zi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Zi])),u[Ji]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ji])),u[Qi]!=null&&(this.log("registering service %s for peer discovery",a),u[Qi].addEventListener?.("peer",f=>{this.#e(f)}))}ud(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 E("no protocols were provided to open a stream",C.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",C.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={}){lr(e)&&(e=be(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!==C.ERR_NOT_FOUND)throw s}let n=Ie([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return oo(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(C.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Qd(r={}){let e=r.peerId??=await Ih();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await so(e.privateKey),new Hl(await Ud(r))}async function Pw(r={}){let e=await Qd(r);return r.start!==!1&&await e.start(),e}return hp(Ow);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  pvtsutils/build/index.js: