libp2p 1.2.0 → 1.2.1

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,34 +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 jd=Object.create;var xo=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Wd=Object.getOwnPropertyNames;var Xd=Object.getPrototypeOf,Zd=Object.prototype.hasOwnProperty;var tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),we=(r,e)=>{for(var t in e)xo(r,t,{get:e[t],enumerable:!0})},Ol=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wd(e))!Zd.call(r,o)&&o!==t&&xo(r,o,{get:()=>e[o],enumerable:!(n=Yd(e,o))||n.enumerable});return r};var dt=(r,e,t)=>(t=r!=null?jd(Xd(r)):{},Ol(e||!r||!r.__esModule?xo(t,"default",{value:r,enumerable:!0}):t,r)),Jd=r=>Ol(xo({},"__esModule",{value:!0}),r);var Vu=tt(rn=>{"use strict";var Rg="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Rg}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}},ja="string",Ig=/^[0-9a-f]+$/i,_g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Sg=/^[a-zA-Z0-9-_]+$/,qo=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=kt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Je=class{static toString(e,t=!1){let n=kt.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}},zo=class r{static isHex(e){return typeof e===ja&&Ig.test(e)}static isBase64(e){return typeof e===ja&&_g.test(e)}static isBase64Url(e){return typeof e===ja&&Sg.test(e)}static ToString(e,t="utf8"){let n=kt.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 Je.toString(n,!0);case"utf16":case"utf16be":return Je.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 Je.fromString(e,!0);case"utf16":case"utf16be":return Je.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=kt.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 qo.fromString(e);case"utf16":case"utf16be":return Je.fromString(e);case"utf16le":case"usc2":return Je.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 qo.toString(e);case"utf16":case"utf16be":return Je.toString(e);case"utf16le":case"usc2":return Je.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=kt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=kt.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 Je.toString(e,t)}static FromUtf16String(e,t=!1){return Je.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,"")||""}};zo.DEFAULT_UTF8_ENCODING="utf8";function Bg(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 Cg(...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 Tg(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}rn.BufferSourceConverter=kt;rn.Convert=zo;rn.assign=Bg;rn.combine=Cg;rn.isEqual=Tg});var lc=tt((_v,Wf)=>{var cn=1e3,ln=cn*60,un=ln*60,Ir=un*24,f0=Ir*7,h0=Ir*365.25;Wf.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return d0(r);if(t==="number"&&isFinite(r))return e.long?m0(r):p0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function d0(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*h0;case"weeks":case"week":case"w":return t*f0;case"days":case"day":case"d":return t*Ir;case"hours":case"hour":case"hrs":case"hr":case"h":return t*un;case"minutes":case"minute":case"mins":case"min":case"m":return t*ln;case"seconds":case"second":case"secs":case"sec":case"s":return t*cn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function p0(r){var e=Math.abs(r);return e>=Ir?Math.round(r/Ir)+"d":e>=un?Math.round(r/un)+"h":e>=ln?Math.round(r/ln)+"m":e>=cn?Math.round(r/cn)+"s":r+"ms"}function m0(r){var e=Math.abs(r);return e>=Ir?Ls(r,e,Ir,"day"):e>=un?Ls(r,e,un,"hour"):e>=ln?Ls(r,e,ln,"minute"):e>=cn?Ls(r,e,cn,"second"):r+" ms"}function Ls(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Zf=tt((Sv,Xf)=>{function g0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=lc(),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 g(...m){if(!g.enabled)return;let y=g,w=Number(new Date),b=w-(l||w);y.diff=b,y.prev=l,y.curr=w,l=w,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(R,T)=>{if(R==="%%")return"%";A++;let N=t.formatters[T];if(typeof N=="function"){let q=m[A];R=N.call(y,q),m.splice(A,1),A--}return R}),t.formatArgs.call(y,m),(y.log||t.log).apply(y,m)}return g.namespace=f,g.useColors=t.useColors(),g.color=t.selectColor(f),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,d=t.enabled(f)),d),set:m=>{p=m}}),typeof t.init=="function"&&t.init(g),g}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}Xf.exports=g0});var uc=tt((Ge,Ds)=>{Ge.formatArgs=w0;Ge.save=b0;Ge.load=E0;Ge.useColors=y0;Ge.storage=x0();Ge.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`."))}})();Ge.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 y0(){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 w0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ds.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)}Ge.log=console.debug||console.log||(()=>{});function b0(r){try{r?Ge.storage.setItem("debug",r):Ge.storage.removeItem("debug")}catch{}}function E0(){let r;try{r=Ge.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function x0(){try{return localStorage}catch{}}Ds.exports=Zf()(Ge);var{formatters:v0}=Ds.exports;v0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Ah=tt((e2,Cc)=>{"use strict";var ny=Object.prototype.hasOwnProperty,Ve="~";function co(){}Object.create&&(co.prototype=Object.create(null),new co().__proto__||(Ve=!1));function oy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function vh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new oy(t,n||r,o),i=Ve?Ve+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 Hs(r,e){--r._eventsCount===0?r._events=new co:delete r._events[e]}function De(){this._events=new co,this._eventsCount=0}De.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ny.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};De.prototype.listeners=function(e){var t=Ve?Ve+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};De.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};De.prototype.emit=function(e,t,n,o,s,i){var a=Ve?Ve+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};De.prototype.on=function(e,t,n){return vh(this,e,t,n,!1)};De.prototype.once=function(e,t,n){return vh(this,e,t,n,!0)};De.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return Hs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Hs(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:Hs(this,s)}return this};De.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&Hs(this,t)):(this._events=new co,this._eventsCount=0),this};De.prototype.off=De.prototype.removeListener;De.prototype.addListener=De.prototype.on;De.prefixed=Ve;De.EventEmitter=De;typeof Cc<"u"&&(Cc.exports=De)});var Gc=tt((bR,Uh)=>{"use strict";function Oh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function xy(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 Oh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Oh(new o,t)}}Uh.exports=xy});var $h=tt(ho=>{(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(g){throw l=g,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(g){throw l=g,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}(),ho.ip2long=i,ho.long2ip=a,ho.Netmask=r}).call(ho)});var Gh=tt((zh,ri)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),o=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",i="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${i})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${i})|(?:::)(?:${i})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(h,d){if(h.indexOf("::")!==h.lastIndexOf("::"))return null;let g=0,m=-1,y=(h.match(a.zoneIndex)||[])[0],w,b;for(y&&(y=y.substring(1),h=h.replace(/%.+$/,""));(m=h.indexOf(":",m+1))>=0;)g++;if(h.substr(0,2)==="::"&&g--,h.substr(-2,2)==="::"&&g--,g>d)return null;for(b=d-g,w=":";b--;)w+="0:";return h=h.replace("::",w),h[0]===":"&&(h=h.slice(1)),h[h.length-1]===":"&&(h=h.slice(0,-1)),d=function(){let A=h.split(":"),v=[];for(let R=0;R<A.length;R++)v.push(parseInt(A[R],16));return v}(),{parts:d,zoneId:y}}function u(h,d,g,m){if(h.length!==d.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,w;for(;m>0;){if(w=g-m,w<0&&(w=0),h[y]>>w!==d[y]>>w)return!1;m-=g,y+=1}return!0}function f(h){if(o.test(h))return parseInt(h,16);if(h[0]==="0"&&!isNaN(parseInt(h[1],10))){if(n.test(h))return parseInt(h,8);throw new Error(`ipaddr: cannot parse ${h} as octal`)}return parseInt(h,10)}function l(h,d){for(;h.length<d;)h=`0${h}`;return h}let p={};p.IPv4=function(){function h(d){if(d.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let g,m;for(g=0;g<d.length;g++)if(m=d[g],!(0<=m&&m<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=d}return h.prototype.SpecialRanges={unspecified:[[new h([0,0,0,0]),8]],broadcast:[[new h([255,255,255,255]),32]],multicast:[[new h([224,0,0,0]),4]],linkLocal:[[new h([169,254,0,0]),16]],loopback:[[new h([127,0,0,0]),8]],carrierGradeNat:[[new h([100,64,0,0]),10]],private:[[new h([10,0,0,0]),8],[new h([172,16,0,0]),12],[new h([192,168,0,0]),16]],reserved:[[new h([192,0,0,0]),24],[new h([192,0,2,0]),24],[new h([192,88,99,0]),24],[new h([198,18,0,0]),15],[new h([198,51,100,0]),24],[new h([203,0,113,0]),24],[new h([240,0,0,0]),4]]},h.prototype.kind=function(){return"ipv4"},h.prototype.match=function(d,g){let m;if(g===void 0&&(m=d,d=m[0],g=m[1]),d.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,d.octets,8,g)},h.prototype.prefixLengthFromSubnetMask=function(){let d=0,g=!1,m={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},y,w,b;for(y=3;y>=0;y-=1)if(w=this.octets[y],w in m){if(b=m[w],g&&b!==0)return null;b!==8&&(g=!0),d+=b}else return null;return 32-d},h.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},h.prototype.toByteArray=function(){return this.octets.slice(0)},h.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},h.prototype.toNormalizedString=function(){return this.toString()},h.prototype.toString=function(){return this.octets.join(".")},h}(),p.IPv4.broadcastAddressFromCIDR=function(h){try{let d=this.parseCIDR(h),g=d[0].toByteArray(),m=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],w=0;for(;w<4;)y.push(parseInt(g[w],10)|parseInt(m[w],10)^255),w++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},p.IPv4.isIPv4=function(h){return this.parser(h)!==null},p.IPv4.isValid=function(h){try{return new this(this.parser(h)),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(h){return!!(p.IPv4.isValid(h)&&h.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.networkAddressFromCIDR=function(h){let d,g,m,y,w;try{for(d=this.parseCIDR(h),m=d[0].toByteArray(),w=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],g=0;g<4;)y.push(parseInt(m[g],10)&parseInt(w[g],10)),g++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},p.IPv4.parse=function(h){let d=this.parser(h);if(d===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(d)},p.IPv4.parseCIDR=function(h){let d;if(d=h.match(/^(.+)\/(\d+)$/)){let g=parseInt(d[2]);if(g>=0&&g<=32){let m=[this.parse(d[1]),g];return Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},p.IPv4.parser=function(h){let d,g,m;if(d=h.match(t.fourOctet))return function(){let y=d.slice(1,6),w=[];for(let b=0;b<y.length;b++)g=y[b],w.push(f(g));return w}();if(d=h.match(t.longValue)){if(m=f(d[1]),m>4294967295||m<0)throw new Error("ipaddr: address outside defined range");return function(){let y=[],w;for(w=0;w<=24;w+=8)y.push(m>>w&255);return y}().reverse()}else return(d=h.match(t.twoOctet))?function(){let y=d.slice(1,4),w=[];if(m=f(y[1]),m>16777215||m<0)throw new Error("ipaddr: address outside defined range");return w.push(f(y[0])),w.push(m>>16&255),w.push(m>>8&255),w.push(m&255),w}():(d=h.match(t.threeOctet))?function(){let y=d.slice(1,5),w=[];if(m=f(y[2]),m>65535||m<0)throw new Error("ipaddr: address outside defined range");return w.push(f(y[0])),w.push(f(y[1])),w.push(m>>8&255),w.push(m&255),w}():null},p.IPv4.subnetMaskFromPrefixLength=function(h){if(h=parseInt(h),h<0||h>32)throw new Error("ipaddr: invalid IPv4 prefix length");let d=[0,0,0,0],g=0,m=Math.floor(h/8);for(;g<m;)d[g]=255,g++;return m<4&&(d[m]=Math.pow(2,h%8)-1<<8-h%8),new this(d)},p.IPv6=function(){function h(d,g){let m,y;if(d.length===16)for(this.parts=[],m=0;m<=14;m+=2)this.parts.push(d[m]<<8|d[m+1]);else if(d.length===8)this.parts=d;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(m=0;m<this.parts.length;m++)if(y=this.parts[m],!(0<=y&&y<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");g&&(this.zoneId=g)}return h.prototype.SpecialRanges={unspecified:[new h([0,0,0,0,0,0,0,0]),128],linkLocal:[new h([65152,0,0,0,0,0,0,0]),10],multicast:[new h([65280,0,0,0,0,0,0,0]),8],loopback:[new h([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new h([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new h([0,0,0,0,0,65535,0,0]),96],rfc6145:[new h([0,0,0,0,65535,0,0,0]),96],rfc6052:[new h([100,65435,0,0,0,0,0,0]),96],"6to4":[new h([8194,0,0,0,0,0,0,0]),16],teredo:[new h([8193,0,0,0,0,0,0,0]),32],reserved:[[new h([8193,3512,0,0,0,0,0,0]),32]],benchmarking:[new h([8193,2,0,0,0,0,0,0]),48],amt:[new h([8193,3,0,0,0,0,0,0]),32],as112v6:[new h([8193,4,274,0,0,0,0,0]),48],deprecated:[new h([8193,16,0,0,0,0,0,0]),28],orchid2:[new h([8193,32,0,0,0,0,0,0]),28]},h.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},h.prototype.kind=function(){return"ipv6"},h.prototype.match=function(d,g){let m;if(g===void 0&&(m=d,d=m[0],g=m[1]),d.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,d.parts,16,g)},h.prototype.prefixLengthFromSubnetMask=function(){let d=0,g=!1,m={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},y,w;for(let b=7;b>=0;b-=1)if(y=this.parts[b],y in m){if(w=m[y],g&&w!==0)return null;w!==16&&(g=!0),d+=w}else return null;return 128-d},h.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},h.prototype.toByteArray=function(){let d,g=[],m=this.parts;for(let y=0;y<m.length;y++)d=m[y],g.push(d>>8),g.push(d&255);return g},h.prototype.toFixedLengthString=function(){let d=function(){let m=[];for(let y=0;y<this.parts.length;y++)m.push(l(this.parts[y].toString(16),4));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),d+g},h.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let d=this.parts.slice(-2),g=d[0],m=d[1];return new p.IPv4([g>>8,g&255,m>>8,m&255])},h.prototype.toNormalizedString=function(){let d=function(){let m=[];for(let y=0;y<this.parts.length;y++)m.push(this.parts[y].toString(16));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),d+g},h.prototype.toRFC5952String=function(){let d=/((^|:)(0(:|$)){2,})/g,g=this.toNormalizedString(),m=0,y=-1,w;for(;w=d.exec(g);)w[0].length>y&&(m=w.index,y=w[0].length);return y<0?g:`${g.substring(0,m)}::${g.substring(m+y)}`},h.prototype.toString=function(){return this.toRFC5952String()},h}(),p.IPv6.broadcastAddressFromCIDR=function(h){try{let d=this.parseCIDR(h),g=d[0].toByteArray(),m=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],w=0;for(;w<16;)y.push(parseInt(g[w],10)|parseInt(m[w],10)^255),w++;return new this(y)}catch(d){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${d})`)}},p.IPv6.isIPv6=function(h){return this.parser(h)!==null},p.IPv6.isValid=function(h){if(typeof h=="string"&&h.indexOf(":")===-1)return!1;try{let d=this.parser(h);return new this(d.parts,d.zoneId),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(h){let d,g,m,y,w;try{for(d=this.parseCIDR(h),m=d[0].toByteArray(),w=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],g=0;g<16;)y.push(parseInt(m[g],10)&parseInt(w[g],10)),g++;return new this(y)}catch(b){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${b})`)}},p.IPv6.parse=function(h){let d=this.parser(h);if(d.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(d.parts,d.zoneId)},p.IPv6.parseCIDR=function(h){let d,g,m;if((g=h.match(/^(.+)\/(\d+)$/))&&(d=parseInt(g[2]),d>=0&&d<=128))return m=[this.parse(g[1]),d],Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},p.IPv6.parser=function(h){let d,g,m,y,w,b;if(m=h.match(a.deprecatedTransitional))return this.parser(`::ffff:${m[1]}`);if(a.native.test(h))return c(h,8);if((m=h.match(a.transitional))&&(b=m[6]||"",d=c(m[1].slice(0,-1)+b,6),d.parts)){for(w=[parseInt(m[2]),parseInt(m[3]),parseInt(m[4]),parseInt(m[5])],g=0;g<w.length;g++)if(y=w[g],!(0<=y&&y<=255))return null;return d.parts.push(w[0]<<8|w[1]),d.parts.push(w[2]<<8|w[3]),{parts:d.parts,zoneId:d.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(h){if(h=parseInt(h),h<0||h>128)throw new Error("ipaddr: invalid IPv6 prefix length");let d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,m=Math.floor(h/8);for(;g<m;)d[g]=255,g++;return m<16&&(d[m]=Math.pow(2,h%8)-1<<8-h%8),new this(d)},p.fromByteArray=function(h){let d=h.length;if(d===4)return new p.IPv4(h);if(d===16)return new p.IPv6(h);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},p.isValid=function(h){return p.IPv6.isValid(h)||p.IPv4.isValid(h)},p.parse=function(h){if(p.IPv6.isValid(h))return p.IPv6.parse(h);if(p.IPv4.isValid(h))return p.IPv4.parse(h);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},p.parseCIDR=function(h){try{return p.IPv6.parseCIDR(h)}catch{try{return p.IPv4.parseCIDR(h)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},p.process=function(h){let d=this.parse(h);return d.kind()==="ipv6"&&d.isIPv4MappedAddress()?d.toIPv4Address():d},p.subnetMatch=function(h,d,g){let m,y,w,b;g==null&&(g="unicast");for(y in d)if(Object.prototype.hasOwnProperty.call(d,y)){for(w=d[y],w[0]&&!(w[0]instanceof Array)&&(w=[w]),m=0;m<w.length;m++)if(b=w[m],h.kind()===b[0].kind()&&h.match.apply(h,b))return y}return g},typeof ri<"u"&&ri.exports?ri.exports=p:r.ipaddr=p})(zh)});var ld=tt((mI,cd)=>{"use strict";cd.exports=ad;var $y=lc(),ur=ad.prototype,Hy=new Date%1e9;function qy(){return(Math.random()*1e9>>>0)+Hy++}function ad(r){r=r||{},this.id=r.id||qy(),this.max=r.max||1/0,this.items=r.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(r.lastModified||new Date);for(var e,t,n=this.items.length;n--;)e=this.items[n],t=new Date(e.expires)-new Date,this._lookup[e.key]=e,t>0?this.expire(e.key,t):t<=0&&this.delete(e.key)}ur.has=function(r){return r in this._lookup};ur.get=function(r){if(!this.has(r))return null;var e=this._lookup[r];return e.refresh&&this.expire(r,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};ur.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};ur.set=function(r,e,t){var n=this._lookup[r],o=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,o)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(o),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(o.meta=t.meta),t.refresh&&(o.refresh=t.ttl)),this};ur.delete=function(r){var e=this._lookup[r];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[r],this.size--,this):!1};ur.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=$y(e)),typeof t!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),t),n.expires=Number(new Date)+t,this};ur.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};ur.toJSON=function(){for(var r=new Array(this.items.length),e,t=r.length;t--;)e=this.items[t],r[t]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:r}}});var pd=tt((vI,dd)=>{"use strict";dd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Ed=tt((wd,bd)=>{"use strict";var ui=pd(),{hasOwnProperty:gd}=Object.prototype,{propertyIsEnumerable:jy}=Object,In=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Yy=wd,md={concatArrays:!1,ignoreUndefined:!1},fi=r=>{let e=[];for(let t in r)gd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)jy.call(r,n)&&e.push(n)}return e};function _n(r){return Array.isArray(r)?Wy(r):ui(r)?Xy(r):r}function Wy(r){let e=r.slice(0,0);return fi(r).forEach(t=>{In(e,t,_n(r[t]))}),e}function Xy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return fi(r).forEach(t=>{In(e,t,_n(r[t]))}),e}var yd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?In(r,o,al(r[o],e[o],n)):In(r,o,_n(e[o])))}),r),Zy=(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++)gd.call(s,a)&&(i.push(String(a)),s===r?In(n,o++,s[a]):In(n,o++,_n(s[a])));n=yd(n,s,fi(s).filter(a=>!i.includes(a)),t)}),n};function al(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Zy(r,e,t):!ui(e)||!ui(r)?_n(e):yd(r,e,fi(e),t)}bd.exports=function(...r){let e=al(_n(md),this!==Yy&&this||{},md),t={_:{}};for(let n of r)if(n!==void 0){if(!ui(n))throw new TypeError("`"+n+"` is not an Option Object");t=al(t,{_:n},e)}return t._}});var _w={};we(_w,{createLibp2p:()=>Iw});var Ul=Symbol.for("@libp2p/connection");var $i=Symbol.for("@libp2p/content-routing");var Hi=Symbol.for("@libp2p/peer-discovery");var qi=Symbol.for("@libp2p/peer-id");function vo(r){return r!=null&&!!r[qi]}var zi=Symbol.for("@libp2p/peer-routing");var Ml="keep-alive";var Dw=Symbol.for("@libp2p/transport");var Kt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Kt||(Kt={}));var $t=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),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??{}}},Ao=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 Ro="ERR_TIMEOUT";var dr=class extends EventTarget{#e=new Map;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 ji(e,t))}},Gi=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ji=globalThis.CustomEvent??Gi;var Xe=(r,...e)=>{try{[...e]}catch{}};function Fl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var za={};we(za,{Ed25519PrivateKey:()=>xr,Ed25519PublicKey:()=>Kn,generateKeyPair:()=>xg,generateKeyPairFromSeed:()=>Fu,unmarshalEd25519PrivateKey:()=>bg,unmarshalEd25519PublicKey:()=>Eg});var Ji={};we(Ji,{base58btc:()=>ee,base58flickr:()=>op});var Vw=new Uint8Array(0);function Vl(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 Kl(r){return new TextEncoder().encode(r)}function $l(r){return new TextDecoder().decode(r)}function Qd(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 g=0,m=0,y=0,w=d.length;y!==w&&d[y]===0;)y++,g++;for(var b=(w-y)*f+1>>>0,A=new Uint8Array(b);y!==w;){for(var v=d[y],R=0,T=b-1;(v!==0||R<m)&&T!==-1;T--,R++)v+=256*A[T]>>>0,A[T]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=R,y++}for(var N=b-m;N!==b&&A[N]===0;)N++;for(var q=c.repeat(g);N<b;++N)q+=r.charAt(A[N]);return q}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var m=0,y=0;d[g]===c;)m++,g++;for(var w=(d.length-g)*u+1>>>0,b=new Uint8Array(w);d[g];){var A=t[d.charCodeAt(g)];if(A===255)return;for(var v=0,R=w-1;(A!==0||v<y)&&R!==-1;R--,v++)A+=a*b[R]>>>0,b[R]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=v,g++}if(d[g]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var N=new Uint8Array(m+(w-T)),q=m;T!==w;)N[q++]=b[T++];return N}}}function h(d){var g=p(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:h}}var ep=Qd,tp=ep,ql=tp;var Yi=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")}},Wi=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 zl(this,e)}},Xi=class{decoders;constructor(e){this.decoders=e}or(e){return zl(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 zl(r,e){return new Xi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Zi=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 Yi(e,t,n),this.decoder=new Wi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Vr({name:r,prefix:e,encode:t,decode:n}){return new Zi(r,e,t,n)}function Ht({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=ql(t,r);return Vr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function rp(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 np(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 re({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Vr({prefix:e,name:r,encode(o){return np(o,n,t)},decode(o){return rp(o,n,t,r)}})}var ee=Ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),op=Ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};we(ea,{identity:()=>qt});var sp=Yl,Gl=128,ip=127,ap=~ip,cp=Math.pow(2,31);function Yl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=cp;)e[t++]=r&255|Gl,r/=128;for(;r&ap;)e[t++]=r&255|Gl,r>>>=7;return e[t]=r|0,Yl.bytes=t-n+1,e}var lp=Qi,up=128,jl=127;function Qi(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Qi.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&jl)<<o:(i&jl)*Math.pow(2,o),o+=7}while(i>=up);return Qi.bytes=s-n,t}var fp=Math.pow(2,7),hp=Math.pow(2,14),dp=Math.pow(2,21),pp=Math.pow(2,28),mp=Math.pow(2,35),gp=Math.pow(2,42),yp=Math.pow(2,49),wp=Math.pow(2,56),bp=Math.pow(2,63),Ep=function(r){return r<fp?1:r<hp?2:r<dp?3:r<pp?4:r<mp?5:r<gp?6:r<yp?7:r<wp?8:r<bp?9:10},xp={encode:sp,decode:lp,encodingLength:Ep},vp=xp,kn=vp;function Ln(r,e=0){return[kn.decode(r,e),kn.decode.bytes]}function Kr(r,e,t=0){return kn.encode(r,e,t),e}function $r(r){return kn.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=$r(r),o=n+$r(t),s=new Uint8Array(o+t);return Kr(r,s,0),Kr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function pr(r){let e=Rt(r),[t,n]=Ln(e),[o,s]=Ln(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hr(t,o,i,e)}function Wl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Vl(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Xl=0,Ap="identity",Zl=Rt;function Rp(r){return pt(Xl,Zl(r))}var qt={code:Xl,name:Ap,encode:Zl,digest:Rp};var na={};we(na,{sha256:()=>Ae,sha512:()=>Ip});function ra({name:r,code:e,encode:t}){return new ta(r,e,t)}var ta=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 Ql(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ae=ra({name:"sha2-256",code:18,encode:Ql("SHA-256")}),Ip=ra({name:"sha2-512",code:19,encode:Ql("SHA-512")});function ne(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 zt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function It(r=0){return globalThis.Buffer?.alloc!=null?zt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Ce(r=0){return globalThis.Buffer?.allocUnsafe!=null?zt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Re(r,e){if(globalThis.Buffer!=null)return zt(globalThis.Buffer.concat(r,e));e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ce(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return zt(t)}var oa={};we(oa,{base10:()=>_p});var _p=Ht({prefix:"9",name:"base10",alphabet:"0123456789"});var sa={};we(sa,{base16:()=>Sp,base16upper:()=>Bp});var Sp=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bp=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ia={};we(ia,{base2:()=>Cp});var Cp=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aa={};we(aa,{base256emoji:()=>Dp});var eu=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}"),Tp=eu.reduce((r,e,t)=>(r[t]=e,r),[]),Np=eu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function kp(r){return r.reduce((e,t)=>(e+=Tp[t],e),"")}function Lp(r){let e=[];for(let t of r){let n=Np[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Dp=Vr({prefix:"\u{1F680}",name:"base256emoji",encode:kp,decode:Lp});var ca={};we(ca,{base32:()=>qe,base32hex:()=>Mp,base32hexpad:()=>Vp,base32hexpadupper:()=>Kp,base32hexupper:()=>Fp,base32pad:()=>Op,base32padupper:()=>Up,base32upper:()=>Pp,base32z:()=>$p});var qe=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pp=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Op=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Up=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mp=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Fp=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Vp=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Kp=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$p=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var la={};we(la,{base36:()=>Hp,base36upper:()=>qp});var Hp=Ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qp=Ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fa={};we(fa,{base64:()=>Dn,base64pad:()=>zp,base64url:()=>ua,base64urlpad:()=>Gp});var Dn=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),zp=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ua=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Gp=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};we(ha,{base8:()=>jp});var jp=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var da={};we(da,{identity:()=>Yp});var Yp=Vr({prefix:"\0",name:"identity",encode:r=>$l(r),decode:r=>Kl(r)});var pb=new TextEncoder,mb=new TextDecoder;function tu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Jp(t,pa(r),e??ee.encoder);default:return Qp(t,pa(r),e??qe.encoder)}}var ru=new WeakMap;function pa(r){let e=ru.get(r);if(e==null){let t=new Map;return ru.set(r,t),t}return e}var rt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==em)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&&Wl(e.multihash,n.multihash)}toString(e){return tu(this,e)}toJSON(){return{"/":tu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??nu(n,o,s.bytes))}else if(t[tm]===!0){let{version:n,multihash:o,code:s}=t,i=pr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pn)throw new Error(`Version 0 CID must use dag-pb (code: ${Pn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=nu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=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 Hr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Ln(e.subarray(t));return t+=p,l},o=n(),s=Pn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=Zp(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 pa(s).set(n,e),s}};function Zp(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case qe.prefix:{let t=e??qe;return[qe.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 Jp(r,e,t){let{prefix:n}=t;if(n!==ee.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 Qp(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Pn=112,em=18;function nu(r,e,t){let n=$r(r),o=n+$r(e),s=new Uint8Array(o+t.byteLength);return Kr(r,s,0),Kr(e,s,n),s.set(t,o),s}var tm=Symbol.for("@ipld/js-cid/CID");var Gt={...da,...ia,...ha,...oa,...sa,...ca,...la,...Ji,...fa,...aa},Nb={...na,...ea};function su(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ou=su("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ma=su("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=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),rm={utf8:ou,"utf-8":ou,hex:Gt.base16,latin1:ma,ascii:ma,binary:ma,...Gt},_o=rm;function D(r,e="utf8"){let t=_o[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zt(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function Ze(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function qr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function nm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function ga(r,...e){if(!nm(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function So(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");qr(r.outputLen),qr(r.blockLen)}function zr(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 iu(r,e){ga(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Bo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function au(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var jr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),nt=(r,e)=>r<<32-e|r>>>e,om=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!om)throw new Error("Non little-endian hardware is not supported");var sm=async()=>{};async function cu(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 sm(),n+=s)}}function ya(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function jt(r){if(typeof r=="string"&&(r=ya(r)),!au(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function Co(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];if(!au(o))throw new Error("Uint8Array expected");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 Gr=class{clone(){return this._cloneInto()}},im={}.toString;function lu(r,e){if(e!==void 0&&im.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function To(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 Yr(r=32){if(Bo&&typeof Bo.getRandomValues=="function")return Bo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function am(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 Wr=class extends Gr{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){zr(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){zr(this),iu(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;am(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 No=BigInt(4294967295),wa=BigInt(32);function uu(r,e=!1){return e?{h:Number(r&No),l:Number(r>>wa&No)}:{h:Number(r>>wa&No)|0,l:Number(r&No)|0}}function cm(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}=uu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var lm=(r,e)=>BigInt(r>>>0)<<wa|BigInt(e>>>0),um=(r,e,t)=>r>>>t,fm=(r,e,t)=>r<<32-t|e>>>t,hm=(r,e,t)=>r>>>t|e<<32-t,dm=(r,e,t)=>r<<32-t|e>>>t,pm=(r,e,t)=>r<<64-t|e>>>t-32,mm=(r,e,t)=>r>>>t-32|e<<64-t,gm=(r,e)=>e,ym=(r,e)=>r,wm=(r,e,t)=>r<<t|e>>>32-t,bm=(r,e,t)=>e<<t|r>>>32-t,Em=(r,e,t)=>e<<t-32|r>>>64-t,xm=(r,e,t)=>r<<t-32|e>>>64-t;function vm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Am=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Rm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Im=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),_m=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Sm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Bm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Cm={fromBig:uu,split:cm,toBig:lm,shrSH:um,shrSL:fm,rotrSH:hm,rotrSL:dm,rotrBH:pm,rotrBL:mm,rotr32H:gm,rotr32L:ym,rotlSH:wm,rotlSL:bm,rotlBH:Em,rotlBL:xm,add:vm,add3L:Am,add3H:Rm,add4L:Im,add4H:_m,add5H:Bm,add5L:Sm},O=Cm;var[Tm,Nm]=O.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Yt=new Uint32Array(80),Wt=new Uint32Array(80),ba=class extends Wr{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:g,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,g,m]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,g,m){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=g|0,this.Hl=m|0}process(e,t){for(let b=0;b<16;b++,t+=4)Yt[b]=e.getUint32(t),Wt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=Yt[b-15]|0,v=Wt[b-15]|0,R=O.rotrSH(A,v,1)^O.rotrSH(A,v,8)^O.shrSH(A,v,7),T=O.rotrSL(A,v,1)^O.rotrSL(A,v,8)^O.shrSL(A,v,7),N=Yt[b-2]|0,q=Wt[b-2]|0,z=O.rotrSH(N,q,19)^O.rotrBH(N,q,61)^O.shrSH(N,q,6),U=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),le=O.add4L(T,U,Wt[b-7],Wt[b-16]),ie=O.add4H(le,R,z,Yt[b-7],Yt[b-16]);Yt[b]=ie|0,Wt[b]=le|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:g,Gl:m,Hh:y,Hl:w}=this;for(let b=0;b<80;b++){let A=O.rotrSH(l,p,14)^O.rotrSH(l,p,18)^O.rotrBH(l,p,41),v=O.rotrSL(l,p,14)^O.rotrSL(l,p,18)^O.rotrBL(l,p,41),R=l&h^~l&g,T=p&d^~p&m,N=O.add5L(w,v,T,Nm[b],Wt[b]),q=O.add5H(N,y,A,R,Tm[b],Yt[b]),z=N|0,U=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),le=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),ie=n&s^n&a^s&a,We=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=d|0,h=l|0,d=p|0,{h:l,l:p}=O.add(u|0,f|0,q|0,z|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let I=O.add3L(z,le,We);n=O.add3H(I,q,U,ie),o=I|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:p}=O.add(this.Eh|0,this.El|0,l|0,p|0),{h,l:d}=O.add(this.Fh|0,this.Fl|0,h|0,d|0),{h:g,l:m}=O.add(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=O.add(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,g,m,y,w)}roundClean(){Yt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Xr=To(()=>new ba);var Lo={};we(Lo,{bitGet:()=>Mm,bitLen:()=>Um,bitMask:()=>On,bitSet:()=>Fm,bytesToHex:()=>St,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>va,ensureBytes:()=>oe,equalBytes:()=>Pm,hexToBytes:()=>gr,hexToNumber:()=>xa,isBytes:()=>ot,numberToBytesBE:()=>Zt,numberToBytesLE:()=>yr,numberToHexUnpadded:()=>pu,numberToVarBytesBE:()=>Dm,utf8ToBytes:()=>Om,validateObject:()=>mt});var du=BigInt(0),ko=BigInt(1),km=BigInt(2);function ot(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var Lm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function St(r){if(!ot(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=Lm[r[t]];return e}function pu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function xa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _t={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function fu(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t._A&&r<=_t._F)return r-(_t._A-10);if(r>=_t._a&&r<=_t._f)return r-(_t._a-10)}function gr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=fu(r.charCodeAt(s)),a=fu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return xa(St(r))}function Xt(r){if(!ot(r))throw new Error("Uint8Array expected");return xa(St(Uint8Array.from(r).reverse()))}function Zt(r,e){return gr(r.toString(16).padStart(e*2,"0"))}function yr(r,e){return Zt(r,e).reverse()}function Dm(r){return gr(pu(r))}function oe(r,e,t){let n;if(typeof e=="string")try{n=gr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(ot(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 o=0;o<r.length;o++){let s=r[o];if(!ot(s))throw new Error("Uint8Array expected");e+=s.length}let t=new Uint8Array(e),n=0;for(let o=0;o<r.length;o++){let s=r[o];t.set(s,n),n+=s.length}return t}function Pm(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 Om(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Um(r){let e;for(e=0;r>du;r>>=ko,e+=1);return e}function Mm(r,e){return r>>BigInt(e)&ko}var Fm=(r,e,t)=>r|(t?ko:du)<<BigInt(e),On=r=>(km<<BigInt(r-1))-ko,Ea=r=>new Uint8Array(r),hu=r=>Uint8Array.from(r);function va(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ea(r),o=Ea(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ea())=>{o=a(hu([0]),l),n=a(),l.length!==0&&(o=a(hu([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 Vm={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"||ot(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=Vm[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 me=BigInt(0),Z=BigInt(1),wr=BigInt(2),Km=BigInt(3),Aa=BigInt(4),mu=BigInt(5),gu=BigInt(8),$m=BigInt(9),Hm=BigInt(16);function X(r,e){let t=r%e;return t>=me?t:e+t}function qm(r,e,t){if(t<=me||e<me)throw new Error("Expected power/modulo > 0");if(t===Z)return me;let n=Z;for(;e>me;)e&Z&&(n=n*r%t),r=r*r%t,e>>=Z;return n}function J(r,e,t){let n=r;for(;e-- >me;)n*=n,n%=t;return n}function Do(r,e){if(r===me||e<=me)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=me,s=Z,i=Z,a=me;for(;t!==me;){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!==Z)throw new Error("invert: does not exist");return X(o,e)}function zm(r){let e=(r-Z)/wr,t,n,o;for(t=r-Z,n=0;t%wr===me;t/=wr,n++);for(o=wr;o<r&&qm(o,e,r)!==r-Z;o++);if(n===1){let i=(r+Z)/Aa;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+Z)/wr;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 g=a.sqr(p);h<u&&!a.eql(g,a.ONE);h++)g=a.sqr(g);let d=a.pow(f,Z<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function Gm(r){if(r%Aa===Km){let e=(r+Z)/Aa;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%gu===mu){let e=(r-mu)/gu;return function(n,o){let s=n.mul(o,wr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,wr),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%Hm,zm(r)}var yu=(r,e)=>(X(r,e)&Z)===Z,jm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ra(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=jm.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function Ym(r,e,t){if(t<me)throw new Error("Expected power > 0");if(t===me)return r.ONE;if(t===Z)return e;let n=r.ONE,o=e;for(;t>me;)t&Z&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Z;return n}function Wm(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 Ia(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Po(r,e,t=!1,n={}){if(r<=me)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ia(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Gm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:On(o),ZERO:me,ONE:Z,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return me<=c&&c<r},is0:c=>c===me,isOdd:c=>(c&Z)===Z,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>Ym(a,c,u),div:(c,u)=>X(c*Do(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Do(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Wm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?yr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function wu(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 bu(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 _a(r){let e=bu(r);return e+Math.ceil(e/2)}function Eu(r,e,t=!1){let n=r.length,o=bu(e),s=_a(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Xt(r),a=X(i,e-Z)+Z;return t?yr(a,o):Zt(a,o)}var Zm=BigInt(0),Sa=BigInt(1);function Oo(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>Zm;)s&Sa&&(i=i.add(a)),a=a.double(),s>>=Sa;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 g=d*c,m=Number(i&l);i>>=h,m>c&&(m-=p,i+=Sa);let y=g,w=g+Math.abs(m)-1,b=d%2!==0,A=m<0;m===0?f=f.add(t(b,s[y])):u=u.add(t(A,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 Un(r){return Ra(r.Fp),mt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ia(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var st=BigInt(0),ze=BigInt(1),Uo=BigInt(2),Jm=BigInt(8),Qm={zip215:!0};function eg(r){let e=Un(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Mo(r){let e=eg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Uo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((_,x)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(x))}}catch{return{isValid:!1,value:st}}}),p=e.adjustScalarBytes||(_=>_),h=e.domain||((_,x,C)=>{if(x.length||C)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&st<_,g=(_,x)=>d(_)&&d(x)&&_<x,m=_=>_===st||g(_,u);function y(_,x){if(g(_,x))return _;throw new Error(`Expected valid scalar < ${x}, got ${typeof _} ${_}`)}function w(_){return _===st?_:y(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(x,C,L,P){if(this.ex=x,this.ey=C,this.ez=L,this.et=P,!m(x))throw new Error("x required");if(!m(C))throw new Error("y required");if(!m(L))throw new Error("z required");if(!m(P))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(x){if(x instanceof v)throw new Error("extended point not allowed");let{x:C,y:L}=x||{};if(!m(C)||!m(L))throw new Error("invalid affine point");return new v(C,L,ze,f(C*L))}static normalizeZ(x){let C=t.invertBatch(x.map(L=>L.ez));return x.map((L,P)=>L.toAffine(C[P])).map(v.fromAffine)}_setWindowSize(x){this._WINDOW_SIZE=x,b.delete(this)}assertValidity(){let{a:x,d:C}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:L,ey:P,ez:F,et:K}=this,Y=f(L*L),H=f(P*P),G=f(F*F),ue=f(G*G),te=f(Y*x),xe=f(G*f(te+H)),ve=f(ue+f(C*f(Y*H)));if(xe!==ve)throw new Error("bad point: equation left != right (1)");let pe=f(L*P),Be=f(F*K);if(pe!==Be)throw new Error("bad point: equation left != right (2)")}equals(x){A(x);let{ex:C,ey:L,ez:P}=this,{ex:F,ey:K,ez:Y}=x,H=f(C*Y),G=f(F*P),ue=f(L*Y),te=f(K*P);return H===G&&ue===te}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:x}=e,{ex:C,ey:L,ez:P}=this,F=f(C*C),K=f(L*L),Y=f(Uo*f(P*P)),H=f(x*F),G=C+L,ue=f(f(G*G)-F-K),te=H+K,xe=te-Y,ve=H-K,pe=f(ue*xe),Be=f(te*ve),At=f(ue*ve),hr=f(xe*te);return new v(pe,Be,hr,At)}add(x){A(x);let{a:C,d:L}=e,{ex:P,ey:F,ez:K,et:Y}=this,{ex:H,ey:G,ez:ue,et:te}=x;if(C===BigInt(-1)){let Cl=f((F-P)*(G+H)),Tl=f((F+P)*(G-H)),Ki=f(Tl-Cl);if(Ki===st)return this.double();let Nl=f(K*Uo*te),kl=f(Y*Uo*ue),Ll=kl+Nl,Dl=Tl+Cl,Pl=kl-Nl,Hd=f(Ll*Ki),qd=f(Dl*Pl),zd=f(Ll*Pl),Gd=f(Ki*Dl);return new v(Hd,qd,Gd,zd)}let xe=f(P*H),ve=f(F*G),pe=f(Y*L*te),Be=f(K*ue),At=f((P+F)*(H+G)-xe-ve),hr=Be-pe,Nn=Be+pe,Bl=f(ve-C*xe),Fd=f(At*hr),Vd=f(Nn*Bl),Kd=f(At*Bl),$d=f(hr*Nn);return new v(Fd,Vd,$d,Kd)}subtract(x){return this.add(x.negate())}wNAF(x){return N.wNAFCached(this,b,x,v.normalizeZ)}multiply(x){let{p:C,f:L}=this.wNAF(y(x,n));return v.normalizeZ([C,L])[0]}multiplyUnsafe(x){let C=w(x);return C===st?T:this.equals(T)||C===ze?this:this.equals(R)?this.wNAF(C).p:N.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(x){let{ex:C,ey:L,ez:P}=this,F=this.is0();x==null&&(x=F?Jm:t.inv(P));let K=f(C*x),Y=f(L*x),H=f(P*x);if(F)return{x:st,y:ze};if(H!==ze)throw new Error("invZ was invalid");return{x:K,y:Y}}clearCofactor(){let{h:x}=e;return x===ze?this:this.multiplyUnsafe(x)}static fromHex(x,C=!1){let{d:L,a:P}=e,F=t.BYTES;x=oe("pointHex",x,F);let K=x.slice(),Y=x[F-1];K[F-1]=Y&-129;let H=Xt(K);H===st||(C?y(H,u):y(H,t.ORDER));let G=f(H*H),ue=f(G-ze),te=f(L*G-P),{isValid:xe,value:ve}=l(ue,te);if(!xe)throw new Error("Point.fromHex: invalid y coordinate");let pe=(ve&ze)===ze,Be=(Y&128)!==0;if(!C&&ve===st&&Be)throw new Error("Point.fromHex: x=0 and x_0=1");return Be!==pe&&(ve=f(-ve)),v.fromAffine({x:ve,y:H})}static fromPrivateKey(x){return U(x).point}toRawBytes(){let{x,y:C}=this.toAffine(),L=yr(C,t.BYTES);return L[L.length-1]|=x&ze?128:0,L}toHex(){return St(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),v.ZERO=new v(st,ze,ze,st);let{BASE:R,ZERO:T}=v,N=Oo(v,a*8);function q(_){return X(_,n)}function z(_){return q(Xt(_))}function U(_){let x=a;_=oe("private key",_,x);let C=oe("hashed private key",s(_),2*x),L=p(C.slice(0,x)),P=C.slice(x,2*x),F=z(L),K=R.multiply(F),Y=K.toRawBytes();return{head:L,prefix:P,scalar:F,point:K,pointBytes:Y}}function le(_){return U(_).pointBytes}function ie(_=new Uint8Array,...x){let C=Ct(...x);return z(s(h(C,oe("context",_),!!o)))}function We(_,x,C={}){_=oe("message",_),o&&(_=o(_));let{prefix:L,scalar:P,pointBytes:F}=U(x),K=ie(C.context,L,_),Y=R.multiply(K).toRawBytes(),H=ie(C.context,Y,F,_),G=q(K+H*P);w(G);let ue=Ct(Y,yr(G,t.BYTES));return oe("result",ue,a*2)}let I=Qm;function k(_,x,C,L=I){let{context:P,zip215:F}=L,K=t.BYTES;_=oe("signature",_,2*K),x=oe("message",x),o&&(x=o(x));let Y=Xt(_.slice(K,2*K)),H,G,ue;try{H=v.fromHex(C,F),G=v.fromHex(_.slice(0,K),F),ue=R.multiplyUnsafe(Y)}catch{return!1}if(!F&&H.isSmallOrder())return!1;let te=ie(P,G.toRawBytes(),H.toRawBytes(),x);return G.add(H.multiplyUnsafe(te)).subtract(ue).clearCofactor().equals(v.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:le,sign:We,verify:k,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,x=v.BASE){return x._setWindowSize(_),x.multiply(BigInt(3)),x}}}}var Ca=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),xu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),hE=BigInt(0),tg=BigInt(1),Ba=BigInt(2),rg=BigInt(5),vu=BigInt(10),ng=BigInt(20),og=BigInt(40),Au=BigInt(80);function sg(r){let e=Ca,n=r*r%e*r%e,o=J(n,Ba,e)*n%e,s=J(o,tg,e)*r%e,i=J(s,rg,e)*s%e,a=J(i,vu,e)*i%e,c=J(a,ng,e)*a%e,u=J(c,og,e)*c%e,f=J(u,Au,e)*u%e,l=J(f,Au,e)*u%e,p=J(l,vu,e)*i%e;return{pow_p_5_8:J(p,Ba,e)*r%e,b2:n}}function ig(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ag(r,e){let t=Ca,n=X(e*e*e,t),o=X(n*n*e,t),s=sg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*xu,t),f=a===r,l=a===X(-r,t),p=a===X(-r*xu,t);return f&&(i=c),(l||p)&&(i=u),yu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Tt=Po(Ca,void 0,!0),Ta={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Tt,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xr,randomBytes:Yr,adjustScalarBytes:ig,uvRatio:ag},Zr=Mo(Ta);function Ru(r,e,t){if(e.length>255)throw new Error("Context is too big");return Co(ya("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var dE=Mo({...Ta,domain:Ru}),pE=Mo({...Ta,domain:Ru,prehash:Xr});var cg=(Tt.ORDER+BigInt(3))/BigInt(8),mE=Tt.pow(Ba,cg),gE=Tt.sqrt(Tt.neg(Tt.ONE)),yE=(Tt.ORDER-BigInt(5))/BigInt(8),wE=BigInt(486662);var bE=wu(Tt,Tt.neg(BigInt(486664)));var EE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),xE=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),vE=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),AE=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var RE=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Jr=32,Nt=64,Fo=32;function Iu(){let r=Zr.utils.randomPrivateKey(),e=Zr.getPublicKey(r);return{privateKey:Cu(r,e),publicKey:e}}function _u(r){if(r.length!==Fo)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=Zr.getPublicKey(e);return{privateKey:Cu(e,t),publicKey:t}}function Su(r,e){let t=r.subarray(0,Fo);return Zr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Bu(r,e,t){return Zr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Cu(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Fo;n++)t[n]=r[n],t[Fo+n]=e[n];return t}var Pe={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 Na={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Tu(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=Pe.get();t*=8;async function c(l,p){let h=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:d};typeof p=="string"&&(p=D(p));let m;if(p.length===0){m=await a.subtle.importKey("jwk",Na,{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"]);m=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",Na,{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"]);m=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(g,m,l);return Re([h,g.iv,new Uint8Array(y)])}async function u(l,p){let h=l.subarray(0,s),d=l.subarray(s,s+n),g=l.subarray(s+n),m={name:e,iv:d};typeof p=="string"&&(p=D(p));let y;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",Na,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let w=await a.subtle.decrypt(m,y,g);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function Qr(r,e){let n=await Tu().encrypt(r,e);return Dn.encode(n)}var ka=new Float32Array([-0]),Jt=new Uint8Array(ka.buffer);function Nu(r,e,t){ka[0]=r,e[t]=Jt[0],e[t+1]=Jt[1],e[t+2]=Jt[2],e[t+3]=Jt[3]}function ku(r,e){return Jt[0]=r[e],Jt[1]=r[e+1],Jt[2]=r[e+2],Jt[3]=r[e+3],ka[0]}var La=new Float64Array([-0]),Te=new Uint8Array(La.buffer);function Lu(r,e,t){La[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function Du(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],La[0]}var fg=BigInt(Number.MAX_SAFE_INTEGER),hg=BigInt(Number.MIN_SAFE_INTEGER),Ke=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 br;if(e<fg&&e>hg)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>Pu&&(o=0n,++n>Pu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return br;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):br}},br=new Ke(0,0);br.toBigInt=function(){return 0n};br.zzEncode=br.zzDecode=function(){return this};br.length=function(){return 1};var Pu=4294967296n;function Ou(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 Uu(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 Da(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 it(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Vo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Pa=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,it(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 it(this,4);return Vo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw it(this,4);return Vo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw it(this,4);let e=ku(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw it(this,4);let e=Du(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 it(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Uu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw it(this,e);this.pos+=e}else do if(this.pos>=this.len)throw it(this);while(this.buf[this.pos++]&128);return this}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 Ke(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 it(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 it(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 it(this,8);let e=Vo(this.buf,this.pos+=4),t=Vo(this.buf,this.pos+=4);return new Ke(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}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 Oa(r){return new Pa(r instanceof Uint8Array?r:r.subarray())}function Oe(r,e){let t=Oa(r);return e.decode(t)}function Ua(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ce(i);o+i>e&&(n=Ce(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Er=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ma(){}var Va=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},dg=Ua();function pg(r){return globalThis.Buffer!=null?Ce(r):dg(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Er(Ma,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Er(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ka((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(Mn,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ke.fromBigInt(e);return this._push(Mn,t.length(),t)}uint64Number(e){let t=Ke.fromNumber(e);return this._push(Mn,t.length(),t)}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=Ke.fromBigInt(e).zzEncode();return this._push(Mn,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push(Mn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Fa,1,e?1:0)}fixed32(e){return this._push(Fn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(Fn,4,t.lo)._push(Fn,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(Nu,4,e)}double(e){return this._push(Lu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Fa,1,0):this.uint32(t)._push(gg,t,e)}string(e){let t=Ou(e);return t!==0?this.uint32(t)._push(Da,t,e):this._push(Fa,1,0)}fork(){return this.states=new Va(this),this.head=this.tail=new Er(Ma,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 Er(Ma,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 Fa(r,e,t){e[t]=r&255}function mg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ka=class extends Er{next;constructor(e,t){super(mg,e,t),this.next=void 0}};function Mn(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 Fn(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 gg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(yg,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wg,e,r),this});function yg(r,e,t){e.set(r,t)}function wg(r,e,t){r.length<40?Da(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function $a(){return new Vn}function Ue(r,e){let t=$a();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var en;(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"})(en||(en={}));function Ko(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ha(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 Ko("enum",en.VARINT,t,n)}function Me(r,e){return Ko("message",en.LENGTH_DELIMITED,r,e)}var Q;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Q||(Q={}));var qa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(qa||(qa={}));(function(r){r.codec=()=>Ha(qa)})(Q||(Q={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.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=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(gt||(gt={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.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=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(yt||(yt={}));var Kn=class{_key;constructor(e){this._key=tn(e,Jr)}verify(e,t){return Bu(this._key,t,e)}marshal(){return this._key}get bytes(){return gt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},xr=class{_key;_publicKey;constructor(e,t){this._key=tn(e,Nt),this._publicKey=tn(t,Jr)}sign(e){return Su(this._key,e)}get public(){return new Kn(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Ae.digest(this.bytes),t;return Ze(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=qt.digest(this.public.bytes);return ee.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Qr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function bg(r){if(r.length>Nt){r=tn(r,Nt+Jr);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new xr(n,o)}r=tn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(Jr);return new xr(e,t)}function Eg(r){return r=tn(r,Jr),new Kn(r)}async function xg(){let{privateKey:r,publicKey:e}=Iu();return new xr(r,e)}async function Fu(r){let{privateKey:e,publicKey:t}=_u(r);return new xr(e,t)}function tn(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 V(r,e="utf8"){let t=_o[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var tc={};we(tc,{MAX_RSA_KEY_SIZE:()=>Qn,RsaPrivateKey:()=>an,RsaPublicKey:()=>Jn,fromJwk:()=>Yg,generateKeyPair:()=>Wg,unmarshalRsaPrivateKey:()=>Qa,unmarshalRsaPublicKey:()=>jg});function vr(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Yr(r)}var rr={};we(rr,{exportToPem:()=>$g,importFromPem:()=>Hg,jwkToPkcs1:()=>Mg,jwkToPkix:()=>Vg,pkcs1ToJwk:()=>Ug,pkixToJwk:()=>Fg});var Ho=class extends Gr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,So(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 zr(this),this.iHash.update(e),this}digestInto(e){zr(this),ga(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 Ho(r,e).update(t).digest();$n.create=(r,e)=>new Ho(r,e);function vg(r,e,t,n){So(r);let o=lu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(qr(s),qr(i),qr(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 Ag(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function Ga(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,g=0;g<s;d++,g+=c.outputLen){let m=a.subarray(g,g+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),m.set(h.subarray(0,m.length)),await cu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let y=0;y<m.length;y++)m[y]^=h[y]})}return Ag(c,u,a,f,h)}var $=dt(Vu());function Ar(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 Qt(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 Go(...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 Ya(){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=Ar(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,Ar(s,8)-n}function Ku(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=Qt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Qt(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 $u(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 Cx=Math.log(2);function jo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Wa(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ot(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var qn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wa(this.items)}},Hn=[new Uint8Array([1])],Hu="0123456789";var on="",ct=new ArrayBuffer(0),Xa=new Uint8Array(0),zn="EndOfContent",zu="OCTET STRING",Gu="BIT STRING";function Ut(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?$.BufferSourceConverter.toUint8Array(s.valueHex):Xa}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ct)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:$.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=on,warnings:n=[],valueBeforeDecode:o=Xa}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=$.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:$.Convert.ToHex(this.valueBeforeDecodeView)}}};Lt.NAME="baseBlock";var Ne=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Ne.NAME="valueBlock";var Yo=class extends Ut(Lt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?$.BufferSourceConverter.toUint8Array(e.valueHex):Xa,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",ct}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=Qt(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=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let p=0;p<c;p++)l[p]=u[p];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Ar(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}}};Yo.NAME="identificationBlock";var Wo=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ar(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=Qt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ct;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}}};Wo.NAME="lengthBlock";var S={},Ie=class extends Lt{constructor({name:e=on,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Yo(o),this.lenBlock=new Wo(o),this.valueBlock=s?new s(o):new Ne(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 qn;t||ju(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?ct: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():$.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${$.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 $u(t,n)}};Ie.NAME="BaseBlock";function ju(r){if(r instanceof S.Constructed)for(let e of r.valueBlock.value)ju(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Xo=class extends Ie{constructor({value:e=on,...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}'`}};Xo.NAME="BaseStringBlock";var Zo=class extends Ut(Ne){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Zo.NAME="PrimitiveValueBlock";var Yu,Jo=class extends Ie{constructor(e={}){super(e,Zo),this.idBlock.isConstructed=!1}};Yu=Jo;S.Primitive=Yu;Jo.NAME="PRIMITIVE";function kg(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 Ns(r,e=0,t=r.length){let n=e,o=new Ie({},Ne),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ie;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=S.EndOfContent;break;case 1:c=S.Boolean;break;case 2:c=S.Integer;break;case 3:c=S.BitString;break;case 4:c=S.OctetString;break;case 5:c=S.Null;break;case 6:c=S.ObjectIdentifier;break;case 10:c=S.Enumerated;break;case 12:c=S.Utf8String;break;case 13:c=S.RelativeObjectIdentifier;break;case 14:c=S.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=S.Sequence;break;case 17:c=S.Set;break;case 18:c=S.NumericString;break;case 19:c=S.PrintableString;break;case 20:c=S.TeletexString;break;case 21:c=S.VideotexString;break;case 22:c=S.IA5String;break;case 23:c=S.UTCTime;break;case 24:c=S.GeneralizedTime;break;case 25:c=S.GraphicString;break;case 26:c=S.VisibleString;break;case 27:c=S.GeneralString;break;case 28:c=S.UniversalString;break;case 29:c=S.CharacterString;break;case 30:c=S.BmpString;break;case 31:c=S.DATE;break;case 32:c=S.TimeOfDay;break;case 33:c=S.DateTime;break;case 34:c=S.Duration;break;default:{let u=o.idBlock.isConstructed?new S.Constructed:new S.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?S.Constructed:S.Primitive}return o=kg(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 sn(r){if(!r.byteLength){let e=new Ie({},Ne);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ns($.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Lg(r,e){return r?1:e}var wt=class extends Ne{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;Lg(this.isIndefiniteForm,n)>0;){let i=Ns(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===zn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===zn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new qn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ct:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wt.NAME="ConstructedValueBlock";var Wu,er=class extends Ie{constructor(e={}){super(e,wt),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 kd=Object.create;var wo=Object.defineProperty;var Dd=Object.getOwnPropertyDescriptor;var Pd=Object.getOwnPropertyNames;var Od=Object.getPrototypeOf,Ud=Object.prototype.hasOwnProperty;var ut=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),we=(r,e)=>{for(var t in e)wo(r,t,{get:e[t],enumerable:!0})},Cl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pd(e))!Ud.call(r,o)&&o!==t&&wo(r,o,{get:()=>e[o],enumerable:!(n=Dd(e,o))||n.enumerable});return r};var xt=(r,e,t)=>(t=r!=null?kd(Od(r)):{},Cl(e||!r||!r.__esModule?wo(t,"default",{value:r,enumerable:!0}):t,r)),Md=r=>Cl(wo({},"__esModule",{value:!0}),r);var Du=ut(Jr=>{"use strict";var ug="[object ArrayBuffer]",Ct=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===ug}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}},Ha="string",fg=/^[0-9a-f]+$/i,hg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,dg=/^[a-zA-Z0-9-_]+$/,Ko=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=Ct.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Ze=class{static toString(e,t=!1){let n=Ct.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}},Ho=class r{static isHex(e){return typeof e===Ha&&fg.test(e)}static isBase64(e){return typeof e===Ha&&hg.test(e)}static isBase64Url(e){return typeof e===Ha&&dg.test(e)}static ToString(e,t="utf8"){let n=Ct.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 Ze.toString(n,!0);case"utf16":case"utf16be":return Ze.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 Ze.fromString(e,!0);case"utf16":case"utf16be":return Ze.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Ct.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 Ko.fromString(e);case"utf16":case"utf16be":return Ze.fromString(e);case"utf16le":case"usc2":return Ze.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 Ko.toString(e);case"utf16":case"utf16be":return Ze.toString(e);case"utf16le":case"usc2":return Ze.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=Ct.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Ct.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 Ze.toString(e,t)}static FromUtf16String(e,t=!1){return Ze.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,"")||""}};Ho.DEFAULT_UTF8_ENCODING="utf8";function pg(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 mg(...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 gg(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}Jr.BufferSourceConverter=Ct;Jr.Convert=Ho;Jr.assign=pg;Jr.combine=mg;Jr.isEqual=gg});var oc=ut((av,$f)=>{var nn=1e3,on=nn*60,sn=on*60,vr=sn*24,Zg=vr*7,Jg=vr*365.25;$f.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Qg(r);if(t==="number"&&isFinite(r))return e.long?t0(r):e0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Qg(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*Jg;case"weeks":case"week":case"w":return t*Zg;case"days":case"day":case"d":return t*vr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*sn;case"minutes":case"minute":case"mins":case"min":case"m":return t*on;case"seconds":case"second":case"secs":case"sec":case"s":return t*nn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function e0(r){var e=Math.abs(r);return e>=vr?Math.round(r/vr)+"d":e>=sn?Math.round(r/sn)+"h":e>=on?Math.round(r/on)+"m":e>=nn?Math.round(r/nn)+"s":r+"ms"}function t0(r){var e=Math.abs(r);return e>=vr?Cs(r,e,vr,"day"):e>=sn?Cs(r,e,sn,"hour"):e>=on?Cs(r,e,on,"minute"):e>=nn?Cs(r,e,nn,"second"):r+" ms"}function Cs(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Gf=ut((cv,qf)=>{function r0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=oc(),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 h=0;h<f.length;h++)l=(l<<5)-l+f.charCodeAt(h),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,h=null,g,d;function p(...m){if(!p.enabled)return;let y=p,x=Number(new Date),b=x-(l||x);y.diff=b,y.prev=l,y.curr=x,l=x,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(S,C)=>{if(S==="%%")return"%";A++;let N=t.formatters[C];if(typeof N=="function"){let q=m[A];S=N.call(y,q),m.splice(A,1),A--}return S}),t.formatArgs.call(y,m),(y.log||t.log).apply(y,m)}return p.namespace=f,p.useColors=t.useColors(),p.color=t.selectColor(f),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==t.namespaces&&(g=t.namespaces,d=t.enabled(f)),d),set:m=>{h=m}}),typeof t.init=="function"&&t.init(p),p}function n(f,l){let h=t(this.namespace+(typeof l>"u"?":":l)+f);return h.log=this.log,h}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,h=(typeof f=="string"?f:"").split(/[\s,]+/),g=h.length;for(l=0;l<g;l++)h[l]&&(f=h[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,h;for(l=0,h=t.skips.length;l<h;l++)if(t.skips[l].test(f))return!1;for(l=0,h=t.names.length;l<h;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}qf.exports=r0});var sc=ut((Ge,Ns)=>{Ge.formatArgs=o0;Ge.save=s0;Ge.load=i0;Ge.useColors=n0;Ge.storage=a0();Ge.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`."))}})();Ge.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 n0(){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 o0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ns.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)}Ge.log=console.debug||console.log||(()=>{});function s0(r){try{r?Ge.storage.setItem("debug",r):Ge.storage.removeItem("debug")}catch{}}function i0(){let r;try{r=Ge.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function a0(){try{return localStorage}catch{}}Ns.exports=Gf()(Ge);var{formatters:c0}=Ns.exports;c0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var yh=ut((PA,Rc)=>{"use strict";var $0=Object.prototype.hasOwnProperty,Ve="~";function so(){}Object.create&&(so.prototype=Object.create(null),new so().__proto__||(Ve=!1));function q0(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function gh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new q0(t,n||r,o),i=Ve?Ve+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 Fs(r,e){--r._eventsCount===0?r._events=new so:delete r._events[e]}function De(){this._events=new so,this._eventsCount=0}De.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)$0.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};De.prototype.listeners=function(e){var t=Ve?Ve+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};De.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};De.prototype.emit=function(e,t,n,o,s,i){var a=Ve?Ve+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 h=c.length,g;for(l=0;l<h;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(g=1,f=new Array(u-1);g<u;g++)f[g-1]=arguments[g];c[l].fn.apply(c[l].context,f)}}return!0};De.prototype.on=function(e,t,n){return gh(this,e,t,n,!1)};De.prototype.once=function(e,t,n){return gh(this,e,t,n,!0)};De.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return Fs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Fs(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:Fs(this,s)}return this};De.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&Fs(this,t)):(this._events=new so,this._eventsCount=0),this};De.prototype.off=De.prototype.removeListener;De.prototype.addListener=De.prototype.on;De.prefixed=Ve;De.EventEmitter=De;typeof Rc<"u"&&(Rc.exports=De)});var Kc=ut((eR,Nh)=>{"use strict";function Ch(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function ay(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 Ch(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Ch(new o,t)}}Nh.exports=ay});var Oh=ut(lo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,h;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,h=c&255,[u,f,l,h].join(".")},i=function(c){var u,f,l,h,g,d;for(u=[],l=h=0;h<=3&&c.length!==0;l=++h){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),g=d[0],f=d[1],c=c.substring(f),u.push(g)}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,h,g;for(h=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")),g=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)h=h*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")h=h*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")h=h*u+(10+t(c[l])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");l++}if(l===g)throw new Error("empty octet");return[h,l]},r=function(){function c(u,f){var l,h,g,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(p){throw l=p,new Error("Invalid mask: "+f)}for(h=g=32;g>=0;h=--g)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;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(p){throw l=p,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,h;for(h=i(this.first),l=i(this.last),f=0;h<=l;)u(a(h),h,f),f++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),lo.ip2long=i,lo.long2ip=a,lo.Netmask=r}).call(lo)});var Xh=ut((zR,Wh)=>{"use strict";Wh.exports=jh;var Ry=oc(),ar=jh.prototype,_y=new Date%1e9;function Sy(){return(Math.random()*1e9>>>0)+_y++}function jh(r){r=r||{},this.id=r.id||Sy(),this.max=r.max||1/0,this.items=r.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(r.lastModified||new Date);for(var e,t,n=this.items.length;n--;)e=this.items[n],t=new Date(e.expires)-new Date,this._lookup[e.key]=e,t>0?this.expire(e.key,t):t<=0&&this.delete(e.key)}ar.has=function(r){return r in this._lookup};ar.get=function(r){if(!this.has(r))return null;var e=this._lookup[r];return e.refresh&&this.expire(r,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};ar.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};ar.set=function(r,e,t){var n=this._lookup[r],o=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,o)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(o),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(o.meta=t.meta),t.refresh&&(o.refresh=t.ttl)),this};ar.delete=function(r){var e=this._lookup[r];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[r],this.size--,this):!1};ar.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=Ry(e)),typeof t!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),t),n.expires=Number(new Date)+t,this};ar.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};ar.toJSON=function(){for(var r=new Array(this.items.length),e,t=r.length;t--;)e=this.items[t],r[t]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:r}}});var td=ut((QR,ed)=>{"use strict";ed.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var ad=ut((sd,id)=>{"use strict";var oi=td(),{hasOwnProperty:nd}=Object.prototype,{propertyIsEnumerable:Ty}=Object,vn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Cy=sd,rd={concatArrays:!1,ignoreUndefined:!1},si=r=>{let e=[];for(let t in r)nd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ty.call(r,n)&&e.push(n)}return e};function An(r){return Array.isArray(r)?Ny(r):oi(r)?Ly(r):r}function Ny(r){let e=r.slice(0,0);return si(r).forEach(t=>{vn(e,t,An(r[t]))}),e}function Ly(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return si(r).forEach(t=>{vn(e,t,An(r[t]))}),e}var od=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?vn(r,o,tl(r[o],e[o],n)):vn(r,o,An(e[o])))}),r),ky=(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++)nd.call(s,a)&&(i.push(String(a)),s===r?vn(n,o++,s[a]):vn(n,o++,An(s[a])));n=od(n,s,si(s).filter(a=>!i.includes(a)),t)}),n};function tl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?ky(r,e,t):!oi(e)||!oi(r)?An(e):od(r,e,si(e),t)}id.exports=function(...r){let e=tl(An(rd),this!==Cy&&this||{},rd),t={_:{}};for(let n of r)if(n!==void 0){if(!oi(n))throw new TypeError("`"+n+"` is not an Option Object");t=tl(t,{_:n},e)}return t._}});var aw={};we(aw,{createLibp2p:()=>iw});var Nl=Symbol.for("@libp2p/connection");var Ui=Symbol.for("@libp2p/content-routing");var Mi=Symbol.for("@libp2p/peer-discovery");var Fi=Symbol.for("@libp2p/peer-id");function bo(r){return r!=null&&!!r[Fi]}var Vi=Symbol.for("@libp2p/peer-routing");var Ll="keep-alive";var mw=Symbol.for("@libp2p/transport");var Ft;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ft||(Ft={}));var Vt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},w=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},Eo=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 xo="ERR_TIMEOUT";var ur=class extends EventTarget{#e=new Map;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 Hi(e,t))}},Ki=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Hi=globalThis.CustomEvent??Ki;var We=(r,...e)=>{try{[...e]}catch{}};function kl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Va={};we(Va,{Ed25519PrivateKey:()=>wr,Ed25519PublicKey:()=>Mn,generateKeyPair:()=>ag,generateKeyPairFromSeed:()=>ku,unmarshalEd25519PrivateKey:()=>sg,unmarshalEd25519PublicKey:()=>ig});var Yi={};we(Yi,{base58btc:()=>ee,base58flickr:()=>qd});var xw=new Uint8Array(0);function Dl(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 vt(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 Pl(r){return new TextEncoder().encode(r)}function Ol(r){return new TextDecoder().decode(r)}function Fd(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 p=0,m=0,y=0,x=d.length;y!==x&&d[y]===0;)y++,p++;for(var b=(x-y)*f+1>>>0,A=new Uint8Array(b);y!==x;){for(var v=d[y],S=0,C=b-1;(v!==0||S<m)&&C!==-1;C--,S++)v+=256*A[C]>>>0,A[C]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=S,y++}for(var N=b-m;N!==b&&A[N]===0;)N++;for(var q=c.repeat(p);N<b;++N)q+=r.charAt(A[N]);return q}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var p=0;if(d[p]!==" "){for(var m=0,y=0;d[p]===c;)m++,p++;for(var x=(d.length-p)*u+1>>>0,b=new Uint8Array(x);d[p];){var A=t[d.charCodeAt(p)];if(A===255)return;for(var v=0,S=x-1;(A!==0||v<y)&&S!==-1;S--,v++)A+=a*b[S]>>>0,b[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=v,p++}if(d[p]!==" "){for(var C=x-y;C!==x&&b[C]===0;)C++;for(var N=new Uint8Array(m+(x-C)),q=m;C!==x;)N[q++]=b[C++];return N}}}function g(d){var p=h(d);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:h,decode:g}}var Vd=Fd,Kd=Vd,Ml=Kd;var $i=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")}},qi=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 Fl(this,e)}},Gi=class{decoders;constructor(e){this.decoders=e}or(e){return Fl(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 Fl(r,e){return new Gi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var zi=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 $i(e,t,n),this.decoder=new qi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Or({name:r,prefix:e,encode:t,decode:n}){return new zi(r,e,t,n)}function Kt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Ml(t,r);return Or({prefix:e,name:r,encode:n,decode:s=>vt(o(s))})}function Hd(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 $d(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 re({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Or({prefix:e,name:r,encode(o){return $d(o,n,t)},decode(o){return Hd(o,n,t,r)}})}var ee=Kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),qd=Kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wi={};we(Wi,{identity:()=>Ht});var Gd=Hl,Vl=128,zd=127,Yd=~zd,jd=Math.pow(2,31);function Hl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jd;)e[t++]=r&255|Vl,r/=128;for(;r&Yd;)e[t++]=r&255|Vl,r>>>=7;return e[t]=r|0,Hl.bytes=t-n+1,e}var Wd=ji,Xd=128,Kl=127;function ji(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ji.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Kl)<<o:(i&Kl)*Math.pow(2,o),o+=7}while(i>=Xd);return ji.bytes=s-n,t}var Zd=Math.pow(2,7),Jd=Math.pow(2,14),Qd=Math.pow(2,21),ep=Math.pow(2,28),tp=Math.pow(2,35),rp=Math.pow(2,42),np=Math.pow(2,49),op=Math.pow(2,56),sp=Math.pow(2,63),ip=function(r){return r<Zd?1:r<Jd?2:r<Qd?3:r<ep?4:r<tp?5:r<rp?6:r<np?7:r<op?8:r<sp?9:10},ap={encode:Gd,decode:Wd,encodingLength:ip},cp=ap,Tn=cp;function Cn(r,e=0){return[Tn.decode(r,e),Tn.decode.bytes]}function Ur(r,e,t=0){return Tn.encode(r,e,t),e}function Mr(r){return Tn.encodingLength(r)}function ft(r,e){let t=e.byteLength,n=Mr(r),o=n+Mr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new Fr(r,t,e,s)}function fr(r){let e=vt(r),[t,n]=Cn(e),[o,s]=Cn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Fr(t,o,i,e)}function $l(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Dl(r.bytes,t.bytes)}}var Fr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var ql=0,lp="identity",Gl=vt;function up(r){return ft(ql,Gl(r))}var Ht={code:ql,name:lp,encode:Gl,digest:up};var Ji={};we(Ji,{sha256:()=>ve,sha512:()=>fp});function Zi({name:r,code:e,encode:t}){return new Xi(r,e,t)}var Xi=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?ft(this.code,t):t.then(n=>ft(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Yl(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ve=Zi({name:"sha2-256",code:18,encode:Yl("SHA-256")}),fp=Zi({name:"sha2-512",code:19,encode:Yl("SHA-512")});function ne(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 $t(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function At(r=0){return globalThis.Buffer?.alloc!=null?$t(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Be(r=0){return globalThis.Buffer?.allocUnsafe!=null?$t(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Ae(r,e){if(globalThis.Buffer!=null)return $t(globalThis.Buffer.concat(r,e));e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Be(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return $t(t)}var Qi={};we(Qi,{base10:()=>hp});var hp=Kt({prefix:"9",name:"base10",alphabet:"0123456789"});var ea={};we(ea,{base16:()=>dp,base16upper:()=>pp});var dp=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pp=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ta={};we(ta,{base2:()=>mp});var mp=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ra={};we(ra,{base256emoji:()=>Ep});var jl=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}"),gp=jl.reduce((r,e,t)=>(r[t]=e,r),[]),yp=jl.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function wp(r){return r.reduce((e,t)=>(e+=gp[t],e),"")}function bp(r){let e=[];for(let t of r){let n=yp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Ep=Or({prefix:"\u{1F680}",name:"base256emoji",encode:wp,decode:bp});var na={};we(na,{base32:()=>$e,base32hex:()=>Rp,base32hexpad:()=>Sp,base32hexpadupper:()=>Ip,base32hexupper:()=>_p,base32pad:()=>vp,base32padupper:()=>Ap,base32upper:()=>xp,base32z:()=>Bp});var $e=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xp=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),vp=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ap=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Rp=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_p=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Sp=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ip=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Bp=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var oa={};we(oa,{base36:()=>Tp,base36upper:()=>Cp});var Tp=Kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cp=Kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ia={};we(ia,{base64:()=>Nn,base64pad:()=>Np,base64url:()=>sa,base64urlpad:()=>Lp});var Nn=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Np=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sa=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lp=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var aa={};we(aa,{base8:()=>kp});var kp=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ca={};we(ca,{identity:()=>Dp});var Dp=Or({prefix:"\0",name:"identity",encode:r=>Ol(r),decode:r=>Pl(r)});var Ww=new TextEncoder,Xw=new TextDecoder;function Wl(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Mp(t,la(r),e??ee.encoder);default:return Fp(t,la(r),e??$e.encoder)}}var Xl=new WeakMap;function la(r){let e=Xl.get(r);if(e==null){let t=new Map;return Xl.set(r,t),t}return e}var et=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ln)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Vp)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=ft(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&&$l(e.multihash,n.multihash)}toString(e){return Wl(this,e)}toJSON(){return{"/":Wl(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??Zl(n,o,s.bytes))}else if(t[Kp]===!0){let{version:n,multihash:o,code:s}=t,i=fr(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!==Ln)throw new Error(`Version 0 CID must use dag-pb (code: ${Ln}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Zl(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ln,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=vt(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 Fr(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,h]=Cn(e.subarray(t));return t+=h,l},o=n(),s=Ln;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]=Up(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return la(s).set(n,e),s}};function Up(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case $e.prefix:{let t=e??$e;return[$e.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 Mp(r,e,t){let{prefix:n}=t;if(n!==ee.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 Fp(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 Ln=112,Vp=18;function Zl(r,e,t){let n=Mr(r),o=n+Mr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var Kp=Symbol.for("@ipld/js-cid/CID");var qt={...ca,...ta,...aa,...Qi,...ea,...na,...oa,...Yi,...ia,...ra},hb={...Ji,...Wi};function Ql(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Jl=Ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ua=Ql("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=Be(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hp={utf8:Jl,"utf-8":Jl,hex:qt.base16,latin1:ua,ascii:ua,binary:ua,...qt},Ao=Hp;function D(r,e="utf8"){let t=Ao[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?$t(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function Xe(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Vr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function $p(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function fa(r,...e){if(!$p(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function Ro(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Vr(r.outputLen),Vr(r.blockLen)}function Kr(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 eu(r,e){fa(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var _o=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function tu(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var $r=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),tt=(r,e)=>r<<32-e|r>>>e,qp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!qp)throw new Error("Non little-endian hardware is not supported");var Gp=async()=>{};async function ru(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 Gp(),n+=s)}}function ha(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gt(r){if(typeof r=="string"&&(r=ha(r)),!tu(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function So(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];if(!tu(o))throw new Error("Uint8Array expected");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 Hr=class{clone(){return this._cloneInto()}},zp={}.toString;function nu(r,e){if(e!==void 0&&zp.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Io(r){let e=n=>r().update(Gt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function qr(r=32){if(_o&&typeof _o.getRandomValues=="function")return _o.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Yp(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 Gr=class extends Hr{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=$r(this.buffer)}update(e){Kr(this);let{view:t,buffer:n,blockLen:o}=this;e=Gt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=$r(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){Kr(this),eu(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;Yp(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=$r(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 Bo=BigInt(4294967295),da=BigInt(32);function ou(r,e=!1){return e?{h:Number(r&Bo),l:Number(r>>da&Bo)}:{h:Number(r>>da&Bo)|0,l:Number(r&Bo)|0}}function jp(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}=ou(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Wp=(r,e)=>BigInt(r>>>0)<<da|BigInt(e>>>0),Xp=(r,e,t)=>r>>>t,Zp=(r,e,t)=>r<<32-t|e>>>t,Jp=(r,e,t)=>r>>>t|e<<32-t,Qp=(r,e,t)=>r<<32-t|e>>>t,em=(r,e,t)=>r<<64-t|e>>>t-32,tm=(r,e,t)=>r>>>t-32|e<<64-t,rm=(r,e)=>e,nm=(r,e)=>r,om=(r,e,t)=>r<<t|e>>>32-t,sm=(r,e,t)=>e<<t|r>>>32-t,im=(r,e,t)=>e<<t-32|r>>>64-t,am=(r,e,t)=>r<<t-32|e>>>64-t;function cm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var lm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),um=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,fm=(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,dm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),pm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var mm={fromBig:ou,split:jp,toBig:Wp,shrSH:Xp,shrSL:Zp,rotrSH:Jp,rotrSL:Qp,rotrBH:em,rotrBL:tm,rotr32H:rm,rotr32L:nm,rotlSH:om,rotlSL:sm,rotlBH:im,rotlBL:am,add:cm,add3L:lm,add3H:um,add4L:fm,add4H:hm,add5H:pm,add5L:dm},O=mm;var[gm,ym]=O.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))),zt=new Uint32Array(80),Yt=new Uint32Array(80),pa=class extends Gr{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:h,Gh:g,Gl:d,Hh:p,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m]}set(e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m){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=h|0,this.Gh=g|0,this.Gl=d|0,this.Hh=p|0,this.Hl=m|0}process(e,t){for(let b=0;b<16;b++,t+=4)zt[b]=e.getUint32(t),Yt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=zt[b-15]|0,v=Yt[b-15]|0,S=O.rotrSH(A,v,1)^O.rotrSH(A,v,8)^O.shrSH(A,v,7),C=O.rotrSL(A,v,1)^O.rotrSL(A,v,8)^O.shrSL(A,v,7),N=zt[b-2]|0,q=Yt[b-2]|0,G=O.rotrSH(N,q,19)^O.rotrBH(N,q,61)^O.shrSH(N,q,6),U=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),le=O.add4L(C,U,Yt[b-7],Yt[b-16]),ie=O.add4H(le,S,G,zt[b-7],zt[b-16]);zt[b]=ie|0,Yt[b]=le|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:h,Fh:g,Fl:d,Gh:p,Gl:m,Hh:y,Hl:x}=this;for(let b=0;b<80;b++){let A=O.rotrSH(l,h,14)^O.rotrSH(l,h,18)^O.rotrBH(l,h,41),v=O.rotrSL(l,h,14)^O.rotrSL(l,h,18)^O.rotrBL(l,h,41),S=l&g^~l&p,C=h&d^~h&m,N=O.add5L(x,v,C,ym[b],Yt[b]),q=O.add5H(N,y,A,S,gm[b],zt[b]),G=N|0,U=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),le=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),ie=n&s^n&a^s&a,je=o&i^o&c^i&c;y=p|0,x=m|0,p=g|0,m=d|0,g=l|0,d=h|0,{h:l,l:h}=O.add(u|0,f|0,q|0,G|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let R=O.add3L(G,le,je);n=O.add3H(R,q,U,ie),o=R|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:h}=O.add(this.Eh|0,this.El|0,l|0,h|0),{h:g,l:d}=O.add(this.Fh|0,this.Fl|0,g|0,d|0),{h:p,l:m}=O.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:x}=O.add(this.Hh|0,this.Hl|0,y|0,x|0),this.set(n,o,s,i,a,c,u,f,l,h,g,d,p,m,y,x)}roundClean(){zt.fill(0),Yt.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 zr=Io(()=>new pa);var Co={};we(Co,{bitGet:()=>Rm,bitLen:()=>Am,bitMask:()=>kn,bitSet:()=>_m,bytesToHex:()=>_t,bytesToNumberBE:()=>St,bytesToNumberLE:()=>jt,concatBytes:()=>It,createHmacDrbg:()=>ya,ensureBytes:()=>oe,equalBytes:()=>xm,hexToBytes:()=>dr,hexToNumber:()=>ga,isBytes:()=>rt,numberToBytesBE:()=>Wt,numberToBytesLE:()=>pr,numberToHexUnpadded:()=>cu,numberToVarBytesBE:()=>Em,utf8ToBytes:()=>vm,validateObject:()=>ht});var au=BigInt(0),To=BigInt(1),wm=BigInt(2);function rt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var bm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function _t(r){if(!rt(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=bm[r[t]];return e}function cu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function ga(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var Rt={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function su(r){if(r>=Rt._0&&r<=Rt._9)return r-Rt._0;if(r>=Rt._A&&r<=Rt._F)return r-(Rt._A-10);if(r>=Rt._a&&r<=Rt._f)return r-(Rt._a-10)}function dr(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=su(r.charCodeAt(s)),a=su(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 St(r){return ga(_t(r))}function jt(r){if(!rt(r))throw new Error("Uint8Array expected");return ga(_t(Uint8Array.from(r).reverse()))}function Wt(r,e){return dr(r.toString(16).padStart(e*2,"0"))}function pr(r,e){return Wt(r,e).reverse()}function Em(r){return dr(cu(r))}function oe(r,e,t){let n;if(typeof e=="string")try{n=dr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(rt(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 It(...r){let e=0;for(let o=0;o<r.length;o++){let s=r[o];if(!rt(s))throw new Error("Uint8Array expected");e+=s.length}let t=new Uint8Array(e),n=0;for(let o=0;o<r.length;o++){let s=r[o];t.set(s,n),n+=s.length}return t}function xm(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 vm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Am(r){let e;for(e=0;r>au;r>>=To,e+=1);return e}function Rm(r,e){return r>>BigInt(e)&To}var _m=(r,e,t)=>r|(t?To:au)<<BigInt(e),kn=r=>(wm<<BigInt(r-1))-To,ma=r=>new Uint8Array(r),iu=r=>Uint8Array.from(r);function ya(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=ma(r),o=ma(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=ma())=>{o=a(iu([0]),l),n=a(),l.length!==0&&(o=a(iu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,h=[];for(;l<e;){n=a();let g=n.slice();h.push(g),l+=n.length}return It(...h)};return(l,h)=>{i(),c(l);let g;for(;!(g=h(u()));)c();return i(),g}}var Sm={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"||rt(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 ht(r,e,t={}){let n=(o,s,i)=>{let a=Sm[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 pe=BigInt(0),Z=BigInt(1),mr=BigInt(2),Im=BigInt(3),wa=BigInt(4),lu=BigInt(5),uu=BigInt(8),Bm=BigInt(9),Tm=BigInt(16);function X(r,e){let t=r%e;return t>=pe?t:e+t}function Cm(r,e,t){if(t<=pe||e<pe)throw new Error("Expected power/modulo > 0");if(t===Z)return pe;let n=Z;for(;e>pe;)e&Z&&(n=n*r%t),r=r*r%t,e>>=Z;return n}function J(r,e,t){let n=r;for(;e-- >pe;)n*=n,n%=t;return n}function No(r,e){if(r===pe||e<=pe)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=pe,s=Z,i=Z,a=pe;for(;t!==pe;){let u=n/t,f=n%t,l=o-i*u,h=s-a*u;n=t,t=f,o=i,s=a,i=l,a=h}if(n!==Z)throw new Error("invert: does not exist");return X(o,e)}function Nm(r){let e=(r-Z)/mr,t,n,o;for(t=r-Z,n=0;t%mr===pe;t/=mr,n++);for(o=mr;o<r&&Cm(o,e,r)!==r-Z;o++);if(n===1){let i=(r+Z)/wa;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+Z)/mr;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),h=a.pow(c,t);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let g=1;for(let p=a.sqr(h);g<u&&!a.eql(p,a.ONE);g++)p=a.sqr(p);let d=a.pow(f,Z<<BigInt(u-g-1));f=a.sqr(d),l=a.mul(l,d),h=a.mul(h,f),u=g}return l}}function Lm(r){if(r%wa===Im){let e=(r+Z)/wa;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%uu===lu){let e=(r-lu)/uu;return function(n,o){let s=n.mul(o,mr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,mr),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%Tm,Nm(r)}var fu=(r,e)=>(X(r,e)&Z)===Z,km=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ba(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=km.reduce((n,o)=>(n[o]="function",n),e);return ht(r,t)}function Dm(r,e,t){if(t<pe)throw new Error("Expected power > 0");if(t===pe)return r.ONE;if(t===Z)return e;let n=r.ONE,o=e;for(;t>pe;)t&Z&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Z;return n}function Pm(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 Ea(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Lo(r,e,t=!1,n={}){if(r<=pe)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ea(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Lm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:kn(o),ZERO:pe,ONE:Z,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return pe<=c&&c<r},is0:c=>c===pe,isOdd:c=>(c&Z)===Z,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>Dm(a,c,u),div:(c,u)=>X(c*No(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>No(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Pm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?pr(c,s):Wt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?jt(c):St(c)}});return Object.freeze(a)}function hu(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 du(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 xa(r){let e=du(r);return e+Math.ceil(e/2)}function pu(r,e,t=!1){let n=r.length,o=du(e),s=xa(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?St(r):jt(r),a=X(i,e-Z)+Z;return t?pr(a,o):Wt(a,o)}var Um=BigInt(0),va=BigInt(1);function ko(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>Um;)s&va&&(i=i.add(a)),a=a.double(),s>>=va;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 h=1;h<a;h++)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),h=2**o,g=BigInt(o);for(let d=0;d<a;d++){let p=d*c,m=Number(i&l);i>>=g,m>c&&(m-=h,i+=va);let y=p,x=p+Math.abs(m)-1,b=d%2!==0,A=m<0;m===0?f=f.add(t(b,s[y])):u=u.add(t(A,s[x]))}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 Dn(r){return ba(r.Fp),ht(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ea(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var nt=BigInt(0),qe=BigInt(1),Do=BigInt(2),Mm=BigInt(8),Fm={zip215:!0};function Vm(r){let e=Dn(r);return ht(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Po(r){let e=Vm(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Do<<BigInt(a*8)-qe,f=t.create,l=e.uvRatio||((_,E)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(E))}}catch{return{isValid:!1,value:nt}}}),h=e.adjustScalarBytes||(_=>_),g=e.domain||((_,E,T)=>{if(E.length||T)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&nt<_,p=(_,E)=>d(_)&&d(E)&&_<E,m=_=>_===nt||p(_,u);function y(_,E){if(p(_,E))return _;throw new Error(`Expected valid scalar < ${E}, got ${typeof _} ${_}`)}function x(_){return _===nt?_:y(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(E,T,k,P){if(this.ex=E,this.ey=T,this.ez=k,this.et=P,!m(E))throw new Error("x required");if(!m(T))throw new Error("y required");if(!m(k))throw new Error("z required");if(!m(P))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof v)throw new Error("extended point not allowed");let{x:T,y:k}=E||{};if(!m(T)||!m(k))throw new Error("invalid affine point");return new v(T,k,qe,f(T*k))}static normalizeZ(E){let T=t.invertBatch(E.map(k=>k.ez));return E.map((k,P)=>k.toAffine(T[P])).map(v.fromAffine)}_setWindowSize(E){this._WINDOW_SIZE=E,b.delete(this)}assertValidity(){let{a:E,d:T}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:k,ey:P,ez:F,et:K}=this,j=f(k*k),$=f(P*P),z=f(F*F),ue=f(z*z),te=f(j*E),Ee=f(z*f(te+$)),xe=f(ue+f(T*f(j*$)));if(Ee!==xe)throw new Error("bad point: equation left != right (1)");let de=f(k*P),Ie=f(F*K);if(de!==Ie)throw new Error("bad point: equation left != right (2)")}equals(E){A(E);let{ex:T,ey:k,ez:P}=this,{ex:F,ey:K,ez:j}=E,$=f(T*j),z=f(F*P),ue=f(k*j),te=f(K*P);return $===z&&ue===te}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:T,ey:k,ez:P}=this,F=f(T*T),K=f(k*k),j=f(Do*f(P*P)),$=f(E*F),z=T+k,ue=f(f(z*z)-F-K),te=$+K,Ee=te-j,xe=$-K,de=f(ue*Ee),Ie=f(te*xe),Et=f(ue*xe),lr=f(Ee*te);return new v(de,Ie,lr,Et)}add(E){A(E);let{a:T,d:k}=e,{ex:P,ey:F,ez:K,et:j}=this,{ex:$,ey:z,ez:ue,et:te}=E;if(T===BigInt(-1)){let Al=f((F-P)*(z+$)),Rl=f((F+P)*(z-$)),Oi=f(Rl-Al);if(Oi===nt)return this.double();let _l=f(K*Do*te),Sl=f(j*Do*ue),Il=Sl+_l,Bl=Rl+Al,Tl=Sl-_l,Td=f(Il*Oi),Cd=f(Bl*Tl),Nd=f(Il*Tl),Ld=f(Oi*Bl);return new v(Td,Cd,Ld,Nd)}let Ee=f(P*$),xe=f(F*z),de=f(j*k*te),Ie=f(K*ue),Et=f((P+F)*($+z)-Ee-xe),lr=Ie-de,Bn=Ie+de,vl=f(xe-T*Ee),_d=f(Et*lr),Sd=f(Bn*vl),Id=f(Et*vl),Bd=f(lr*Bn);return new v(_d,Sd,Bd,Id)}subtract(E){return this.add(E.negate())}wNAF(E){return N.wNAFCached(this,b,E,v.normalizeZ)}multiply(E){let{p:T,f:k}=this.wNAF(y(E,n));return v.normalizeZ([T,k])[0]}multiplyUnsafe(E){let T=x(E);return T===nt?C:this.equals(C)||T===qe?this:this.equals(S)?this.wNAF(T).p:N.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(E){let{ex:T,ey:k,ez:P}=this,F=this.is0();E==null&&(E=F?Mm:t.inv(P));let K=f(T*E),j=f(k*E),$=f(P*E);if(F)return{x:nt,y:qe};if($!==qe)throw new Error("invZ was invalid");return{x:K,y:j}}clearCofactor(){let{h:E}=e;return E===qe?this:this.multiplyUnsafe(E)}static fromHex(E,T=!1){let{d:k,a:P}=e,F=t.BYTES;E=oe("pointHex",E,F);let K=E.slice(),j=E[F-1];K[F-1]=j&-129;let $=jt(K);$===nt||(T?y($,u):y($,t.ORDER));let z=f($*$),ue=f(z-qe),te=f(k*z-P),{isValid:Ee,value:xe}=l(ue,te);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let de=(xe&qe)===qe,Ie=(j&128)!==0;if(!T&&xe===nt&&Ie)throw new Error("Point.fromHex: x=0 and x_0=1");return Ie!==de&&(xe=f(-xe)),v.fromAffine({x:xe,y:$})}static fromPrivateKey(E){return U(E).point}toRawBytes(){let{x:E,y:T}=this.toAffine(),k=pr(T,t.BYTES);return k[k.length-1]|=E&qe?128:0,k}toHex(){return _t(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,qe,f(e.Gx*e.Gy)),v.ZERO=new v(nt,qe,qe,nt);let{BASE:S,ZERO:C}=v,N=ko(v,a*8);function q(_){return X(_,n)}function G(_){return q(jt(_))}function U(_){let E=a;_=oe("private key",_,E);let T=oe("hashed private key",s(_),2*E),k=h(T.slice(0,E)),P=T.slice(E,2*E),F=G(k),K=S.multiply(F),j=K.toRawBytes();return{head:k,prefix:P,scalar:F,point:K,pointBytes:j}}function le(_){return U(_).pointBytes}function ie(_=new Uint8Array,...E){let T=It(...E);return G(s(g(T,oe("context",_),!!o)))}function je(_,E,T={}){_=oe("message",_),o&&(_=o(_));let{prefix:k,scalar:P,pointBytes:F}=U(E),K=ie(T.context,k,_),j=S.multiply(K).toRawBytes(),$=ie(T.context,j,F,_),z=q(K+$*P);x(z);let ue=It(j,pr(z,t.BYTES));return oe("result",ue,a*2)}let R=Fm;function L(_,E,T,k=R){let{context:P,zip215:F}=k,K=t.BYTES;_=oe("signature",_,2*K),E=oe("message",E),o&&(E=o(E));let j=jt(_.slice(K,2*K)),$,z,ue;try{$=v.fromHex(T,F),z=v.fromHex(_.slice(0,K),F),ue=S.multiplyUnsafe(j)}catch{return!1}if(!F&&$.isSmallOrder())return!1;let te=ie(P,z.toRawBytes(),$.toRawBytes(),E);return z.add($.multiplyUnsafe(te)).subtract(ue).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:le,sign:je,verify:L,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,E=v.BASE){return E._setWindowSize(_),E.multiply(BigInt(3)),E}}}}var Ra=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),mu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Yb=BigInt(0),Km=BigInt(1),Aa=BigInt(2),Hm=BigInt(5),gu=BigInt(10),$m=BigInt(20),qm=BigInt(40),yu=BigInt(80);function Gm(r){let e=Ra,n=r*r%e*r%e,o=J(n,Aa,e)*n%e,s=J(o,Km,e)*r%e,i=J(s,Hm,e)*s%e,a=J(i,gu,e)*i%e,c=J(a,$m,e)*a%e,u=J(c,qm,e)*c%e,f=J(u,yu,e)*u%e,l=J(f,yu,e)*u%e,h=J(l,gu,e)*i%e;return{pow_p_5_8:J(h,Aa,e)*r%e,b2:n}}function zm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Ym(r,e){let t=Ra,n=X(e*e*e,t),o=X(n*n*e,t),s=Gm(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*mu,t),f=a===r,l=a===X(-r,t),h=a===X(-r*mu,t);return f&&(i=c),(l||h)&&(i=u),fu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Bt=Lo(Ra,void 0,!0),_a={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Bt,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:zr,randomBytes:qr,adjustScalarBytes:zm,uvRatio:Ym},Yr=Po(_a);function wu(r,e,t){if(e.length>255)throw new Error("Context is too big");return So(ha("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var jb=Po({..._a,domain:wu}),Wb=Po({..._a,domain:wu,prehash:zr});var jm=(Bt.ORDER+BigInt(3))/BigInt(8),Xb=Bt.pow(Aa,jm),Zb=Bt.sqrt(Bt.neg(Bt.ONE)),Jb=(Bt.ORDER-BigInt(5))/BigInt(8),Qb=BigInt(486662);var eE=hu(Bt,Bt.neg(BigInt(486664)));var tE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),rE=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),nE=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),oE=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var sE=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var jr=32,Tt=64,Oo=32;function bu(){let r=Yr.utils.randomPrivateKey(),e=Yr.getPublicKey(r);return{privateKey:Au(r,e),publicKey:e}}function Eu(r){if(r.length!==Oo)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=Yr.getPublicKey(e);return{privateKey:Au(e,t),publicKey:t}}function xu(r,e){let t=r.subarray(0,Oo);return Yr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function vu(r,e,t){return Yr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Au(r,e){let t=new Uint8Array(Tt);for(let n=0;n<Oo;n++)t[n]=r[n],t[Oo+n]=e[n];return t}var Pe={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 Sa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Ru(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=Pe.get();t*=8;async function c(l,h){let g=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),p={name:e,iv:d};typeof h=="string"&&(h=D(h));let m;if(h.length===0){m=await a.subtle.importKey("jwk",Sa,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",Sa,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(p,m,l);return Ae([g,p.iv,new Uint8Array(y)])}async function u(l,h){let g=l.subarray(0,s),d=l.subarray(s,s+n),p=l.subarray(s+n),m={name:e,iv:d};typeof h=="string"&&(h=D(h));let y;if(h.length===0)try{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",Sa,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(m,y,p);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function Wr(r,e){let n=await Ru().encrypt(r,e);return Nn.encode(n)}var Ia=new Float32Array([-0]),Xt=new Uint8Array(Ia.buffer);function _u(r,e,t){Ia[0]=r,e[t]=Xt[0],e[t+1]=Xt[1],e[t+2]=Xt[2],e[t+3]=Xt[3]}function Su(r,e){return Xt[0]=r[e],Xt[1]=r[e+1],Xt[2]=r[e+2],Xt[3]=r[e+3],Ia[0]}var Ba=new Float64Array([-0]),Te=new Uint8Array(Ba.buffer);function Iu(r,e,t){Ba[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function Bu(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],Ba[0]}var Zm=BigInt(Number.MAX_SAFE_INTEGER),Jm=BigInt(Number.MIN_SAFE_INTEGER),Ke=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 gr;if(e<Zm&&e>Jm)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>Tu&&(o=0n,++n>Tu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gr;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):gr}},gr=new Ke(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var Tu=4294967296n;function Cu(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 Nu(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 Ta(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 ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Uo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ca=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,ot(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 ot(this,4);return Uo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return Uo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=Su(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=Bu(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 ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Nu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(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 Ke(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 ot(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 ot(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 ot(this,8);let e=Uo(this.buf,this.pos+=4),t=Uo(this.buf,this.pos+=4);return new Ke(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}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 Na(r){return new Ca(r instanceof Uint8Array?r:r.subarray())}function Oe(r,e){let t=Na(r);return e.decode(t)}function La(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Be(i);o+i>e&&(n=Be(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var yr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ka(){}var Pa=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Qm=La();function eg(r){return globalThis.Buffer!=null?Be(r):Qm(r)}var Un=class{len;head;tail;states;constructor(){this.len=0,this.head=new yr(ka,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Oa((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(Pn,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ke.fromBigInt(e);return this._push(Pn,t.length(),t)}uint64Number(e){let t=Ke.fromNumber(e);return this._push(Pn,t.length(),t)}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=Ke.fromBigInt(e).zzEncode();return this._push(Pn,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push(Pn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Da,1,e?1:0)}fixed32(e){return this._push(On,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(On,4,t.lo)._push(On,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(On,4,t.lo)._push(On,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(_u,4,e)}double(e){return this._push(Iu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Da,1,0):this.uint32(t)._push(rg,t,e)}string(e){let t=Cu(e);return t!==0?this.uint32(t)._push(Ta,t,e):this._push(Da,1,0)}fork(){return this.states=new Pa(this),this.head=this.tail=new yr(ka,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 yr(ka,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=eg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Da(r,e,t){e[t]=r&255}function tg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Oa=class extends yr{next;constructor(e,t){super(tg,e,t),this.next=void 0}};function Pn(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 On(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 rg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ng,e,r),this},Un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(og,e,r),this});function ng(r,e,t){e.set(r,t)}function og(r,e,t){r.length<40?Ta(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function Ua(){return new Un}function Ue(r,e){let t=Ua();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Xr;(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"})(Xr||(Xr={}));function Mo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ma(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 Mo("enum",Xr.VARINT,t,n)}function Me(r,e){return Mo("message",Xr.LENGTH_DELIMITED,r,e)}var Q;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Q||(Q={}));var Fa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Fa||(Fa={}));(function(r){r.codec=()=>Ma(Fa)})(Q||(Q={}));var dt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.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=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(dt||(dt={}));var pt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.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=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(pt||(pt={}));var Mn=class{_key;constructor(e){this._key=Zr(e,jr)}verify(e,t){return vu(this._key,t,e)}marshal(){return this._key}get bytes(){return dt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ve.digest(this.bytes);return Xe(e)?e.then(({bytes:t})=>t):e.bytes}},wr=class{_key;_publicKey;constructor(e,t){this._key=Zr(e,Tt),this._publicKey=Zr(t,jr)}sign(e){return xu(this._key,e)}get public(){return new Mn(this._publicKey)}marshal(){return this._key}get bytes(){return pt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=ve.digest(this.bytes),t;return Xe(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Ht.digest(this.public.bytes);return ee.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Wr(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function sg(r){if(r.length>Tt){r=Zr(r,Tt+jr);let n=r.subarray(0,Tt),o=r.subarray(Tt,r.length);return new wr(n,o)}r=Zr(r,Tt);let e=r.subarray(0,Tt),t=r.subarray(jr);return new wr(e,t)}function ig(r){return r=Zr(r,jr),new Mn(r)}async function ag(){let{privateKey:r,publicKey:e}=bu();return new wr(r,e)}async function ku(r){let{privateKey:e,publicKey:t}=Eu(r);return new wr(e,t)}function Zr(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new w(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function V(r,e="utf8"){let t=Ao[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Xa={};we(Xa,{MAX_RSA_KEY_SIZE:()=>Xn,RsaPrivateKey:()=>rn,RsaPublicKey:()=>Wn,fromJwk:()=>Dg,generateKeyPair:()=>Pg,unmarshalRsaPrivateKey:()=>ja,unmarshalRsaPublicKey:()=>kg});function br(r){if(isNaN(r)||r<=0)throw new w("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return qr(r)}var er={};we(er,{exportToPem:()=>Bg,importFromPem:()=>Tg,jwkToPkcs1:()=>Rg,jwkToPkix:()=>Sg,pkcs1ToJwk:()=>Ag,pkixToJwk:()=>_g});var Vo=class extends Hr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ro(e);let n=Gt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),fa(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()}},Fn=(r,e,t)=>new Vo(r,e).update(t).digest();Fn.create=(r,e)=>new Vo(r,e);function cg(r,e,t,n){Ro(r);let o=nu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Vr(s),Vr(i),Vr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gt(e),u=Gt(t),f=new Uint8Array(i),l=Fn.create(r,c),h=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:h}}function lg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function Ka(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=cg(r,e,t,n),f,l=new Uint8Array(4),h=$r(l),g=new Uint8Array(c.outputLen);for(let d=1,p=0;p<s;d++,p+=c.outputLen){let m=a.subarray(p,p+c.outputLen);h.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(g),m.set(g.subarray(0,m.length)),await ru(o-1,i,()=>{c._cloneInto(f).update(g).digestInto(g);for(let y=0;y<m.length;y++)m[y]^=g[y]})}return lg(c,u,a,f,g)}var H=xt(Du());function Er(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 Zt(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 $o(...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 $a(){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=Er(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,Er(s,8)-n}function Pu(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=Zt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Zt(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 Ou(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 He(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 ux=Math.log(2);function qo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function qa(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 Dt(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 Kn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return qa(this.items)}},Vn=[new Uint8Array([1])],Uu="0123456789";var en="",it=new ArrayBuffer(0),Ga=new Uint8Array(0),Hn="EndOfContent",Fu="OCTET STRING",Vu="BIT STRING";function Pt(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?H.BufferSourceConverter.toUint8Array(s.valueHex):Ga}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(!Dt(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",it)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:H.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Nt=class{constructor({blockLength:e=0,error:t=en,warnings:n=[],valueBeforeDecode:o=Ga}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=H.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:H.Convert.ToHex(this.valueBeforeDecodeView)}}};Nt.NAME="baseBlock";var Ce=class extends Nt{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'")}};Ce.NAME="valueBlock";var Go=class extends Pt(Nt){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?H.BufferSourceConverter.toUint8Array(e.valueHex):Ga,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",it}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=Zt(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=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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 h=new Uint8Array(f);for(let g=0;g<u.length;g++)h[g]=u[g];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=u[h];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Er(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}}};Go.NAME="identificationBlock";var zo=class extends Nt{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=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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=Er(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=Zt(this.length,8);if(o.byteLength>127)return this.error="Too big length",it;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}}};zo.NAME="lengthBlock";var I={},Re=class extends Nt{constructor({name:e=en,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Go(o),this.lenBlock=new zo(o),this.valueBlock=s?new s(o):new Ce(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 Kn;t||Ku(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?it: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():H.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${H.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 Ou(t,n)}};Re.NAME="BaseBlock";function Ku(r){if(r instanceof I.Constructed)for(let e of r.valueBlock.value)Ku(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Yo=class extends Re{constructor({value:e=en,...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}'`}};Yo.NAME="BaseStringBlock";var jo=class extends Pt(Ce){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};jo.NAME="PrimitiveValueBlock";var Hu,Wo=class extends Re{constructor(e={}){super(e,jo),this.idBlock.isConstructed=!1}};Hu=Wo;I.Primitive=Hu;Wo.NAME="PRIMITIVE";function wg(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 Bs(r,e=0,t=r.length){let n=e,o=new Re({},Ce),s=new Nt;if(!Dt(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=Re;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=I.EndOfContent;break;case 1:c=I.Boolean;break;case 2:c=I.Integer;break;case 3:c=I.BitString;break;case 4:c=I.OctetString;break;case 5:c=I.Null;break;case 6:c=I.ObjectIdentifier;break;case 10:c=I.Enumerated;break;case 12:c=I.Utf8String;break;case 13:c=I.RelativeObjectIdentifier;break;case 14:c=I.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=I.Sequence;break;case 17:c=I.Set;break;case 18:c=I.NumericString;break;case 19:c=I.PrintableString;break;case 20:c=I.TeletexString;break;case 21:c=I.VideotexString;break;case 22:c=I.IA5String;break;case 23:c=I.UTCTime;break;case 24:c=I.GeneralizedTime;break;case 25:c=I.GraphicString;break;case 26:c=I.VisibleString;break;case 27:c=I.GeneralString;break;case 28:c=I.UniversalString;break;case 29:c=I.CharacterString;break;case 30:c=I.BmpString;break;case 31:c=I.DATE;break;case 32:c=I.TimeOfDay;break;case 33:c=I.DateTime;break;case 34:c=I.Duration;break;default:{let u=o.idBlock.isConstructed?new I.Constructed:new I.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?I.Constructed:I.Primitive}return o=wg(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 tn(r){if(!r.byteLength){let e=new Re({},Ce);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Bs(H.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function bg(r,e){return r?1:e}var mt=class extends Ce{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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(;bg(this.isIndefiniteForm,n)>0;){let i=Bs(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===Hn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Hn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Kn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?it:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};mt.NAME="ConstructedValueBlock";var $u,Jt=class extends Re{constructor(e={}){super(e,mt),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} :`}};Wu=er;S.Constructed=Wu;er.NAME="CONSTRUCTED";var Qo=class extends Ne{fromBER(e,t,n){return t}toBER(e){return ct}};Qo.override="EndOfContentValueBlock";var Xu,es=class extends Ie{constructor(e={}){super(e,Qo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Xu=es;S.EndOfContent=Xu;es.NAME=zn;var Zu,tr=class extends Ie{constructor(e={}){super(e,Ne),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}`}};Zu=tr;S.Null=Zu;tr.NAME="NULL";var ts=class extends Ut(Ne){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=$.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=$.BufferSourceConverter.toUint8Array(e);return Ot(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ya.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ts.NAME="BooleanValueBlock";var Ju,rs=class extends Ie{constructor(e={}){super(e,ts),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}`}};Ju=rs;S.Boolean=Ju;rs.NAME="BOOLEAN";var ns=class extends Ut(wt){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=wt.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===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==zu)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?wt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ns.NAME="OctetStringValueBlock";var Qu,Dt=class r extends Ie{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ns),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=Ns(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${$.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 $.BufferSourceConverter.concat(e)}};Qu=Dt;S.OctetString=Qu;Dt.NAME=zu;var os=class extends Ut(wt){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=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Gu)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=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ns(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 wt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ct;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}}};os.NAME="BitStringValueBlock";var ef,nn=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},os),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return er.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ef=nn;S.BitString=ef;nn.NAME=Gu;var tf;function Dg(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=Go(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Go(t,s)),s}function qu(r){if(r>=Hn.length)for(let e=Hn.length;e<=r;e++){let t=new Uint8Array([0]),n=Hn[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=Go(t,n)),Hn.push(n)}return Hn[r]}function Pg(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 Gn=class extends Ut(Ne){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=Ya.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ku(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=Pg(qu(n),t),i="-";break;default:t=Dg(t,qu(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Hu.charAt(t[c]));return a===!1&&(i+=Hu.charAt(0)),i}};tf=Gn;Gn.NAME="IntegerValueBlock";Object.defineProperty(tf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var rf,fe=class r extends Ie{constructor(e={}){super(e,Gn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return jo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){jo();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array($.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${$.Convert.ToHex(a)}`)+t,f=$.BufferSourceConverter.toUint8Array($.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()}`}};rf=fe;S.Integer=rf;fe.NAME="INTEGER";var nf,ss=class extends fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};nf=ss;S.Enumerated=nf;ss.NAME="ENUMERATED";var jn=class extends Ut(Ne){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=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){jo();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=Qt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;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=$.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 is=class extends Ne{constructor({value:e=on,...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,ct;t.push(o)}return Wa(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){jo();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}};is.NAME="ObjectIdentifierValueBlock";var of,at=class extends Ie{constructor(e={}){super(e,is),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()}}};of=at;S.ObjectIdentifier=of;at.NAME="OBJECT IDENTIFIER";var Yn=class extends Ut(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(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=Qt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;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=$.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Yn.NAME="relativeSidBlock";var as=class extends Ne{constructor({value:e=on,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Yn;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,ct;n.push(s)}return Wa(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 Yn;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}};as.NAME="RelativeObjectIdentifierValueBlock";var sf,cs=class extends Ie{constructor(e={}){super(e,as),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=cs;S.RelativeObjectIdentifier=sf;cs.NAME="RelativeObjectIdentifier";var af,be=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};af=be;S.Sequence=af;be.NAME="SEQUENCE";var cf,ls=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};cf=ls;S.Set=cf;ls.NAME="SET";var us=class extends Ut(Ne){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=on}toJSON(){return{...super.toJSON(),value:this.value}}};us.NAME="StringValueBlock";var fs=class extends us{};fs.NAME="SimpleStringValueBlock";var Fe=class extends Xo{constructor({...e}={}){super(e,fs)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,$.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}};Fe.NAME="SIMPLE STRING";var hs=class extends Fe{fromBuffer(e){this.valueBlock.valueHexView=$.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=$.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=$.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array($.Convert.FromUtf8String(e)),this.valueBlock.value=e}};hs.NAME="Utf8StringValueBlock";var lf,Pt=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};lf=Pt;S.Utf8String=lf;Pt.NAME="UTF8String";var ds=class extends Fe{fromBuffer(e){this.valueBlock.value=$.Convert.ToUtf16String(e),this.valueBlock.valueHexView=$.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array($.Convert.FromUtf16String(e))}};ds.NAME="BmpStringValueBlock";var uf,ps=class extends ds{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};uf=ps;S.BmpString=uf;ps.NAME="BMPString";var ms=class extends Fe{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=Qt(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}};ms.NAME="UniversalStringValueBlock";var ff,gs=class extends ms{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ff=gs;S.UniversalString=ff;gs.NAME="UniversalString";var hf,ys=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};hf=ys;S.NumericString=hf;ys.NAME="NumericString";var df,ws=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};df=ws;S.PrintableString=df;ws.NAME="PrintableString";var pf,bs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};pf=bs;S.TeletexString=pf;bs.NAME="TeletexString";var mf,Es=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};mf=Es;S.VideotexString=mf;Es.NAME="VideotexString";var gf,xs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};gf=xs;S.IA5String=gf;xs.NAME="IA5String";var yf,vs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};yf=vs;S.GraphicString=yf;vs.NAME="GraphicString";var wf,Wn=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};wf=Wn;S.VisibleString=wf;Wn.NAME="VisibleString";var bf,As=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};bf=As;S.GeneralString=bf;As.NAME="GeneralString";var Ef,Rs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Ef=Rs;S.CharacterString=Ef;Rs.NAME="CharacterString";var xf,Xn=class extends Wn{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,$.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}}};xf=Xn;S.UTCTime=xf;Xn.NAME="UTCTime";var vf,Is=class extends Xn{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}}};vf=Is;S.GeneralizedTime=vf;Is.NAME="GeneralizedTime";var Af,_s=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Af=_s;S.DATE=Af;_s.NAME="DATE";var Rf,Ss=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Rf=Ss;S.TimeOfDay=Rf;Ss.NAME="TimeOfDay";var If,Bs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};If=Bs;S.DateTime=If;Bs.NAME="DateTime";var _f,Cs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};_f=Cs;S.Duration=_f;Cs.NAME="Duration";var Sf,Ts=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Sf=Ts;S.TIME=Sf;Ts.NAME="TIME";function Ug(r){let{result:e}=sn(r),t=e.valueBlock.value;return{n:V(bt(t[1].toBigInt()),"base64url"),e:V(bt(t[2].toBigInt()),"base64url"),d:V(bt(t[3].toBigInt()),"base64url"),p:V(bt(t[4].toBigInt()),"base64url"),q:V(bt(t[5].toBigInt()),"base64url"),dp:V(bt(t[6].toBigInt()),"base64url"),dq:V(bt(t[7].toBigInt()),"base64url"),qi:V(bt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Mg(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 be({value:[new fe({value:0}),fe.fromBigInt(Et(D(r.n,"base64url"))),fe.fromBigInt(Et(D(r.e,"base64url"))),fe.fromBigInt(Et(D(r.d,"base64url"))),fe.fromBigInt(Et(D(r.p,"base64url"))),fe.fromBigInt(Et(D(r.q,"base64url"))),fe.fromBigInt(Et(D(r.dp,"base64url"))),fe.fromBigInt(Et(D(r.dq,"base64url"))),fe.fromBigInt(Et(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Fg(r){let{result:e}=sn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:V(bt(t[0].toBigInt()),"base64url"),e:V(bt(t[1].toBigInt()),"base64url")}}function Vg(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new be({value:[new be({value:[new at({value:"1.2.840.113549.1.1.1"}),new tr]}),new nn({valueHex:new be({value:[fe.fromBigInt(Et(D(r.n,"base64url"))),fe.fromBigInt(Et(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bt(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 Et(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 Kg=16,Za=32,Ja=1e4;async function $g(r,e){let t=Pe.get(),o=new be({value:[new fe({value:0}),new be({value:[new at({value:"1.2.840.113549.1.1.1"}),new tr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=vr(Kg),a=await Ga(Xr,e,i,{c:Ja,dkLen:Za}),c=vr(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 be({value:[new Dt({valueHex:i}),new fe({value:Ja}),new fe({value:Za}),new be({value:[new at({value:"1.2.840.113549.2.11"}),new tr]})]}),p=new be({value:[new at({value:"1.2.840.113549.1.5.13"}),new be({value:[new be({value:[new at({value:"1.2.840.113549.1.5.12"}),l]}),new be({value:[new at({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new be({value:[p,new Dt({valueHex:f})]}).toBER(),g=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...V(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function Hg(r,e){let t=Pe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=qg(s),l=await Ga(Xr,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Zn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=sn(h);n=Bf(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o);n=Bf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Qa(n)}function qg(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=Zn(s.valueBlock.value[0].getValue()),a=Ja,c=Za;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=Zn(u.valueBlock.value[1].getValue());return{cipherText:Zn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Bf(r){return Zn(r.valueBlock.value[2].getValue())}function Zn(r){return new Uint8Array(r,0,r.byteLength)}async function Cf(r){let e=await Pe.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 kf(e);return{privateKey:t[0],publicKey:t[1]}}async function ec(r){let t=[await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await zg(r)],n=await kf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Tf(r,e){let t=await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Pe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Nf(r,e,t){let n=await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Pe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function kf(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Pe.get().subtle.exportKey("jwk",r.privateKey),Pe.get().subtle.exportKey("jwk",r.publicKey)])}async function zg(r){return Pe.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 D(r.n,"base64url").length*8}var Qn=8192,Jn=class{_key;constructor(e){this._key=e}verify(e,t){return Nf(this._key,t,e)}marshal(){return rr.jwkToPkix(this._key)}get bytes(){return gt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},an=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return vr(16)}sign(e){return Tf(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Jn(this._publicKey)}marshal(){return rr.jwkToPkcs1(this._key)}get bytes(){return yt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return rr.exportToPem(this,e);if(t==="libp2p-key")return Qr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Qa(r){let e=rr.pkcs1ToJwk(r);if(ks(e)>Qn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ec(e);return new an(t.privateKey,t.publicKey)}function jg(r){let e=rr.pkixToJwk(r);if(ks(e)>Qn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Jn(e)}async function Yg(r){if(ks(r)>Qn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ec(r);return new an(e.privateKey,e.publicKey)}async function Wg(r){if(r>Qn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Cf(r);return new an(e.privateKey,e.publicKey)}var ic={};we(ic,{Secp256k1PrivateKey:()=>to,Secp256k1PublicKey:()=>eo,generateKeyPair:()=>u0,unmarshalSecp256k1PrivateKey:()=>c0,unmarshalSecp256k1PublicKey:()=>l0});var Xg=(r,e,t)=>r&e^~r&t,Zg=(r,e,t)=>r&e^r&t^e&t,Jg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),rc=class extends Wr{constructor(){super(64,32,8,!1),this.A=nr[0]|0,this.B=nr[1]|0,this.C=nr[2]|0,this.D=nr[3]|0,this.E=nr[4]|0,this.F=nr[5]|0,this.G=nr[6]|0,this.H=nr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=or[l-15],h=or[l-2],d=nt(p,7)^nt(p,18)^p>>>3,g=nt(h,17)^nt(h,19)^h>>>10;or[l]=g+or[l-7]+d+or[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let p=nt(a,6)^nt(a,11)^nt(a,25),h=f+p+Xg(a,c,u)+Jg[l]+or[l]|0,g=(nt(n,2)^nt(n,13)^nt(n,22))+Zg(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Lf=To(()=>new rc);function Qg(r){let e=Un(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:e0,hexToBytes:t0}=Lo,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:e0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?t0(r):r;if(!ot(t))throw new Error("ui8a expected");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}`}},Mt=BigInt(0),Qe=BigInt(1),tv=BigInt(2),Df=BigInt(3),rv=BigInt(4);function r0(r){let e=Qg(r),{Fp:t}=e,n=e.toBytes||((d,g,m)=>{let y=g.toAffine();return Ct(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),o=e.fromBytes||(d=>{let g=d.subarray(1),m=t.fromBytes(g.subarray(0,t.BYTES)),y=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:m,y}});function s(d){let{a:g,b:m}=e,y=t.sqr(d),w=t.mul(y,d);return t.add(t.add(w,t.mul(d,g)),m)}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"&&Mt<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:g,nByteLength:m,wrapPrivateKey:y,n:w}=e;if(g&&typeof d!="bigint"){if(ot(d)&&(d=St(d)),typeof d!="string"||!g.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(oe("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return y&&(b=X(b,w)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(g,m,y){if(this.px=g,this.py=m,this.pz=y,g==null||!t.isValid(g))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required")}static fromAffine(g){let{x:m,y}=g||{};if(!g||!t.isValid(m)||!t.isValid(y))throw new Error("invalid affine point");if(g instanceof l)throw new Error("projective point not allowed");let w=b=>t.eql(b,t.ZERO);return w(m)&&w(y)?l.ZERO:new l(m,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let m=t.invertBatch(g.map(y=>y.pz));return g.map((y,w)=>y.toAffine(m[w])).map(l.fromAffine)}static fromHex(g){let m=l.fromAffine(o(oe("pointHex",g)));return m.assertValidity(),m}static fromPrivateKey(g){return l.BASE.multiply(c(g))}_setWindowSize(g){this._WINDOW_SIZE=g,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:g,y:m}=this.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not FE");let y=t.sqr(m),w=s(g);if(!t.eql(y,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:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){f(g);let{px:m,py:y,pz:w}=this,{px:b,py:A,pz:v}=g,R=t.eql(t.mul(m,v),t.mul(b,w)),T=t.eql(t.mul(y,v),t.mul(A,w));return R&&T}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:m}=e,y=t.mul(m,Df),{px:w,py:b,pz:A}=this,v=t.ZERO,R=t.ZERO,T=t.ZERO,N=t.mul(w,w),q=t.mul(b,b),z=t.mul(A,A),U=t.mul(w,b);return U=t.add(U,U),T=t.mul(w,A),T=t.add(T,T),v=t.mul(g,T),R=t.mul(y,z),R=t.add(v,R),v=t.sub(q,R),R=t.add(q,R),R=t.mul(v,R),v=t.mul(U,v),T=t.mul(y,T),z=t.mul(g,z),U=t.sub(N,z),U=t.mul(g,U),U=t.add(U,T),T=t.add(N,N),N=t.add(T,N),N=t.add(N,z),N=t.mul(N,U),R=t.add(R,N),z=t.mul(b,A),z=t.add(z,z),N=t.mul(z,U),v=t.sub(v,N),T=t.mul(z,q),T=t.add(T,T),T=t.add(T,T),new l(v,R,T)}add(g){f(g);let{px:m,py:y,pz:w}=this,{px:b,py:A,pz:v}=g,R=t.ZERO,T=t.ZERO,N=t.ZERO,q=e.a,z=t.mul(e.b,Df),U=t.mul(m,b),le=t.mul(y,A),ie=t.mul(w,v),We=t.add(m,y),I=t.add(b,A);We=t.mul(We,I),I=t.add(U,le),We=t.sub(We,I),I=t.add(m,w);let k=t.add(b,v);return I=t.mul(I,k),k=t.add(U,ie),I=t.sub(I,k),k=t.add(y,w),R=t.add(A,v),k=t.mul(k,R),R=t.add(le,ie),k=t.sub(k,R),N=t.mul(q,I),R=t.mul(z,ie),N=t.add(R,N),R=t.sub(le,N),N=t.add(le,N),T=t.mul(R,N),le=t.add(U,U),le=t.add(le,U),ie=t.mul(q,ie),I=t.mul(z,I),le=t.add(le,ie),ie=t.sub(U,ie),ie=t.mul(q,ie),I=t.add(I,ie),U=t.mul(le,I),T=t.add(T,U),U=t.mul(k,I),R=t.mul(We,R),R=t.sub(R,U),U=t.mul(We,le),N=t.mul(k,N),N=t.add(N,U),new l(R,T,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(l.ZERO)}wNAF(g){return h.wNAFCached(this,u,g,m=>{let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(l.fromAffine)})}multiplyUnsafe(g){let m=l.ZERO;if(g===Mt)return m;if(a(g),g===Qe)return this;let{endo:y}=e;if(!y)return h.unsafeLadder(this,g);let{k1neg:w,k1:b,k2neg:A,k2:v}=y.splitScalar(g),R=m,T=m,N=this;for(;b>Mt||v>Mt;)b&Qe&&(R=R.add(N)),v&Qe&&(T=T.add(N)),N=N.double(),b>>=Qe,v>>=Qe;return w&&(R=R.negate()),A&&(T=T.negate()),T=new l(t.mul(T.px,y.beta),T.py,T.pz),R.add(T)}multiply(g){a(g);let m=g,y,w,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:R,k2:T}=b.splitScalar(m),{p:N,f:q}=this.wNAF(v),{p:z,f:U}=this.wNAF(T);N=h.constTimeNegate(A,N),z=h.constTimeNegate(R,z),z=new l(t.mul(z.px,b.beta),z.py,z.pz),y=N.add(z),w=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);y=A,w=v}return l.normalizeZ([y,w])[0]}multiplyAndAddUnsafe(g,m,y){let w=l.BASE,b=(v,R)=>R===Mt||R===Qe||!v.equals(w)?v.multiplyUnsafe(R):v.multiply(R),A=b(this,m).add(b(g,y));return A.is0()?void 0:A}toAffine(g){let{px:m,py:y,pz:w}=this,b=this.is0();g==null&&(g=b?t.ONE:t.inv(w));let A=t.mul(m,g),v=t.mul(y,g),R=t.mul(w,g);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:g,isTorsionFree:m}=e;if(g===Qe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:m}=e;return g===Qe?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return this.assertValidity(),n(l,this,g)}toHex(g=!0){return St(this.toRawBytes(g))}}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=Oo(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function n0(r){let e=Un(r);return mt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Pf(r){let e=n0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Mt<I&&I<t.ORDER}function a(I){return X(I,n)}function c(I){return Do(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=r0({...e,toBytes(I,k,M){let _=k.toAffine(),x=t.toBytes(_.x),C=Ct;return M?C(Uint8Array.from([k.hasEvenY()?2:3]),x):C(Uint8Array.from([4]),x,t.toBytes(_.y))},fromBytes(I){let k=I.length,M=I[0],_=I.subarray(1);if(k===o&&(M===2||M===3)){let x=Bt(_);if(!i(x))throw new Error("Point is not on curve");let C=l(x),L=t.sqrt(C),P=(L&Qe)===Qe;return(M&1)===1!==P&&(L=t.neg(L)),{x,y:L}}else if(k===s&&M===4){let x=t.fromBytes(_.subarray(0,t.BYTES)),C=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x,y:C}}else throw new Error(`Point of length ${k} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>St(Zt(I,e.nByteLength));function d(I){let k=n>>Qe;return I>k}function g(I){return d(I)?a(-I):I}let m=(I,k,M)=>Bt(I.slice(k,M));class y{constructor(k,M,_){this.r=k,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(k){let M=e.nByteLength;return k=oe("compactSignature",k,M*2),new y(m(k,0,M),m(k,M,2*M))}static fromDER(k){let{r:M,s:_}=Rr.toSig(oe("DER",k));return new y(M,_)}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(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:M,s:_,recovery:x}=this,C=T(oe("msgHash",k));if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");let L=x===2||x===3?M+e.n:M;if(L>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=x&1?"03":"02",F=u.fromHex(P+h(L)),K=c(L),Y=a(-C*K),H=a(_*K),G=u.BASE.multiplyAndAddUnsafe(F,Y,H);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return gr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return gr(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=_a(e.n);return Eu(e.randomBytes(I),e.n)},precompute(I=8,k=u.BASE){return k._setWindowSize(I),k.multiply(BigInt(3)),k}};function b(I,k=!0){return u.fromPrivateKey(I).toRawBytes(k)}function A(I){let k=ot(I),M=typeof I=="string",_=(k||M)&&I.length;return k?_===o||_===s:M?_===2*o||_===2*s:I instanceof u}function v(I,k,M=!0){if(A(I))throw new Error("first arg must be private key");if(!A(k))throw new Error("second arg must be public key");return u.fromHex(k).multiply(f(I)).toRawBytes(M)}let R=e.bits2int||function(I){let k=Bt(I),M=I.length*8-e.nBitLength;return M>0?k>>BigInt(M):k},T=e.bits2int_modN||function(I){return a(R(I))},N=On(e.nBitLength);function q(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Mt<=I&&I<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Zt(I,e.nByteLength)}function z(I,k,M=U){if(["recovered","canonical"].some(te=>te in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:x}=e,{lowS:C,prehash:L,extraEntropy:P}=M;C==null&&(C=!0),I=oe("msgHash",I),L&&(I=oe("prehashed msgHash",_(I)));let F=T(I),K=f(k),Y=[q(K),q(F)];if(P!=null){let te=P===!0?x(t.BYTES):P;Y.push(oe("extraEntropy",te))}let H=Ct(...Y),G=F;function ue(te){let xe=R(te);if(!p(xe))return;let ve=c(xe),pe=u.BASE.multiply(xe).toAffine(),Be=a(pe.x);if(Be===Mt)return;let At=a(ve*a(G+Be*K));if(At===Mt)return;let hr=(pe.x===Be?0:2)|Number(pe.y&Qe),Nn=At;return C&&d(At)&&(Nn=g(At),hr^=1),new y(Be,Nn,hr)}return{seed:H,k2sig:ue}}let U={lowS:e.lowS,prehash:!1},le={lowS:e.lowS,prehash:!1};function ie(I,k,M=U){let{seed:_,k2sig:x}=z(I,k,M),C=e;return va(C.hash.outputLen,C.nByteLength,C.hmac)(_,x)}u.BASE._setWindowSize(8);function We(I,k,M,_=le){let x=I;if(k=oe("msgHash",k),M=oe("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:C,prehash:L}=_,P,F;try{if(typeof x=="string"||ot(x))try{P=y.fromDER(x)}catch(pe){if(!(pe instanceof Rr.Err))throw pe;P=y.fromCompact(x)}else if(typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint"){let{r:pe,s:Be}=x;P=new y(pe,Be)}else throw new Error("PARSE");F=u.fromHex(M)}catch(pe){if(pe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(C&&P.hasHighS())return!1;L&&(k=e.hash(k));let{r:K,s:Y}=P,H=T(k),G=c(Y),ue=a(H*G),te=a(K*G),xe=u.BASE.multiplyAndAddUnsafe(F,ue,te)?.toAffine();return xe?a(xe.x)===K:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ie,verify:We,ProjectivePoint:u,Signature:y,utils:w}}function o0(r){return{hash:r,hmac:(e,...t)=>$n(r,e,Co(...t)),randomBytes:Yr}}function Of(r,e){let t=n=>Pf({...r,...o0(n)});return Object.freeze({...t(e),create:t})}var Ff=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Uf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),s0=BigInt(1),nc=BigInt(2),Mf=(r,e)=>(r+e/nc)/e;function i0(r){let e=Ff,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=J(f,t,e)*f%e,p=J(l,t,e)*f%e,h=J(p,nc,e)*u%e,d=J(h,o,e)*h%e,g=J(d,s,e)*d%e,m=J(g,a,e)*g%e,y=J(m,c,e)*m%e,w=J(y,a,e)*g%e,b=J(w,t,e)*f%e,A=J(b,i,e)*d%e,v=J(A,n,e)*u%e,R=J(v,nc,e);if(!oc.eql(oc.sqr(R),r))throw new Error("Cannot find square root");return R}var oc=Po(Ff,void 0,void 0,{sqrt:i0}),lt=Of({a:BigInt(0),b:BigInt(7),Fp:oc,n:Uf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Uf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-s0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Mf(s*r,e),c=Mf(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,p=f>i;if(l&&(u=e-u),p&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},Lf),fv=BigInt(0);var hv=lt.ProjectivePoint;function Vf(){return lt.utils.randomPrivateKey()}function Kf(r,e){let t=Ae.digest(e instanceof Uint8Array?e:e.subarray());if(Ze(t))return t.then(({digest:n})=>lt.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return lt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function $f(r,e,t){let n=Ae.digest(t instanceof Uint8Array?t:t.subarray());if(Ze(n))return n.then(({digest:o})=>lt.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return lt.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function Hf(r){return lt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function qf(r){try{lt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function sc(r){try{lt.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function zf(r){try{return lt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var eo=class{_key;constructor(e){sc(e),this._key=e}verify(e,t){return $f(this._key,t,e)}marshal(){return Hf(this._key)}get bytes(){return gt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Ae.digest(this.bytes),t;return Ze(e)?{bytes:t}=await e:t=e.bytes,t}},to=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??zf(e),qf(this._key),sc(this._publicKey)}sign(e){return Kf(this._key,e)}get public(){return new eo(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Qr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function c0(r){return new to(r)}function l0(r){return new eo(r)}async function u0(){let r=Vf();return new to(r)}var sr={rsa:tc,ed25519:za,secp256k1:ic};function ac(r){let e=Object.keys(sr).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function cc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return sr[r];throw ac(r)}async function Gf(r,e){return cc(r).generateKeyPair(e??2048)}function ro(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return sr.rsa.unmarshalRsaPublicKey(t);case Q.Ed25519:return sr.ed25519.unmarshalEd25519PublicKey(t);case Q.Secp256k1:return sr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw ac(e.Type??"unknown")}}function jf(r,e){return e=(e??"rsa").toLowerCase(),cc(e),r.bytes}async function no(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return sr.rsa.unmarshalRsaPrivateKey(t);case Q.Ed25519:return sr.ed25519.unmarshalEd25519PrivateKey(t);case Q.Secp256k1:return sr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw ac(e.Type??"RSA")}}function Yf(r,e){return e=(e??"rsa").toLowerCase(),cc(e),r.bytes}var je=dt(uc(),1);je.default.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":qe.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Dn.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 A0(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 Ps(){return{forComponent(r){return R0(r)}}}function R0(r){let e=A0(`${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 I0=Symbol.for("nodejs.util.inspect.custom"),Jf=Object.values(Gt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Gt.identity.decoder),Qf=114,fc=36,hc=37,oo=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()})`}[qi]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return rt.createV1(Qf,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return ge(e).equals(this);if(e?.multihash?.bytes!=null)return ne(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[I0](){return`PeerId(${this.toString()})`}},_r=class extends oo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sr=class extends oo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends oo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function eh(r){if(r.type==="RSA")return new _r(r);if(r.type==="Ed25519")return new Sr(r);if(r.type==="secp256k1")return new Br(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function ge(r,e){if(e=e??Jf,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=pr(ee.decode(`z${r}`));return r.startsWith("12D")?new Sr({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new _r({multihash:t})}return fn(Jf.decode(r))}function fn(r){try{let e=pr(r);if(e.code===qt.code){if(e.digest.length===fc)return new Sr({multihash:e});if(e.digest.length===hc)return new Br({multihash:e})}if(e.code===Ae.code)return new _r({multihash:e})}catch{return _0(rt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function _0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qf)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ae.code)return new _r({multihash:r.multihash});if(e.code===qt.code){if(e.digest.length===fc)return new Sr({multihash:r.multihash});if(e.digest.length===hc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function hn(r,e){return r.length===fc?new Sr({multihash:pt(qt.code,r),privateKey:e}):r.length===hc?new Br({multihash:pt(qt.code,r),privateKey:e}):new _r({multihash:await Ae.digest(r),publicKey:r,privateKey:e})}function dn(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 Ye=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 dn(this.map.entries(),e=>[ge(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ge(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 dn(this.map.keys(),e=>ge(e))}values(){return this.map.values()}get size(){return this.map.size}};var ut=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 dn(this.set.entries(),e=>{let t=ge(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ge(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return dn(this.set.values(),e=>ge(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 th=async()=>{let r=await Gf("Ed25519"),e=await S0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function S0(r){return hn(jf(r.public),Yf(r))}var B0=Math.pow(2,7),C0=Math.pow(2,14),T0=Math.pow(2,21),dc=Math.pow(2,28),pc=Math.pow(2,35),mc=Math.pow(2,42),gc=Math.pow(2,49),j=128,ke=127;function Le(r){if(r<B0)return 1;if(r<C0)return 2;if(r<T0)return 3;if(r<dc)return 4;if(r<pc)return 5;if(r<mc)return 6;if(r<gc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function N0(r,e,t=0){switch(Le(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function k0(r,e,t=0){switch(Le(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function L0(r,e){let t=r[e],n=0;if(n+=t&ke,t<j||(t=r[e+1],n+=(t&ke)<<7,t<j)||(t=r[e+2],n+=(t&ke)<<14,t<j)||(t=r[e+3],n+=(t&ke)<<21,t<j)||(t=r[e+4],n+=(t&ke)*dc,t<j)||(t=r[e+5],n+=(t&ke)*pc,t<j)||(t=r[e+6],n+=(t&ke)*mc,t<j)||(t=r[e+7],n+=(t&ke)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function D0(r,e){let t=r.get(e),n=0;if(n+=t&ke,t<j||(t=r.get(e+1),n+=(t&ke)<<7,t<j)||(t=r.get(e+2),n+=(t&ke)<<14,t<j)||(t=r.get(e+3),n+=(t&ke)<<21,t<j)||(t=r.get(e+4),n+=(t&ke)*dc,t<j)||(t=r.get(e+5),n+=(t&ke)*pc,t<j)||(t=r.get(e+6),n+=(t&ke)*mc,t<j)||(t=r.get(e+7),n+=(t&ke)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function He(r,e,t=0){return e==null&&(e=Ce(Le(r))),e instanceof Uint8Array?N0(r,e,t):k0(r,e,t)}function ft(r,e=0){return r instanceof Uint8Array?L0(r,e):D0(r,e)}var nh=Symbol.for("@achingbrain/uint8arraylist");function rh(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 Os(r){return!!r?.[nh]}var Ee=class r{bufs;length;[nh]=!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(Os(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(Os(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=rh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=rh(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(Os(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(!Os(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=Ce(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=Ce(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(!ne(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 oh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var so;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(so||(so={}));var pn=class r{static createFromProtobuf=async e=>{let t=so.decode(e),n=await hn(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=sh(n,o,s),c=await(await no(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new E("envelope signature is not valid for the given domain",oh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=so.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ne(this.marshal(),e.marshal())}async validate(e){let t=sh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return ro(this.peerId.publicKey).verify(t.subarray(),this.signature)}},sh=(r,e,t)=>{let n=D(r),o=He(n.byteLength),s=He(e.length),i=He(t.length);return new Ee(o,n,s,e,i,t)};function ih(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 Us=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 ah=45,P0=15,mn=new Us;function yc(r){if(!(r.length>P0))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function wc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ah))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function Ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ah))return mn.new(r).parseWith(()=>mn.readIPAddr())}var T1=parseInt("0xFFFF",16),N1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Fs(r){return!!yc(r)}function Vs(r){return!!wc(r)}function gn(r){return!!Ms(r)}var uh=Fs,V0=Vs,bc=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(V0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=uh(t[n]),i;s&&(i=bc(t[n]),t[n]=V(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,V(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},fh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var yn={},Ec={},$0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];$0.forEach(r=>{let e=H0(...r);Ec[e.code]=e,yn[e.name]=e});function H0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Ec[r]!=null)return Ec[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yn[r]!=null)return yn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var pA=W("ip4"),mA=W("ip6"),gA=W("ipcidr");function vc(r,e){switch(W(r).code){case 4:case 41:return z0(e);case 42:return ph(e);case 6:case 273:case 33:case 132:return gh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ph(e);case 421:return W0(e);case 444:return mh(e);case 445:return mh(e);case 466:return Y0(e);default:return V(e,"base16")}}function Ac(r,e){switch(W(r).code){case 4:return hh(e);case 41:return hh(e);case 42:return dh(e);case 6:case 273:case 33:case 132:return Rc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dh(e);case 421:return G0(e);case 444:return X0(e);case 445:return Z0(e);case 466:return j0(e);default:return D(e,"base16")}}var xc=Object.values(Gt).map(r=>r.decoder),q0=function(){let r=xc[0].or(xc[1]);return xc.slice(2).forEach(e=>r=r.or(e)),r}();function hh(r){if(!gn(r))throw new Error("invalid ip address");return bc(r)}function z0(r){let e=fh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!gn(e))throw new Error("invalid ip address");return e}function Rc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function gh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function dh(r){let e=D(r),t=Uint8Array.from(He(e.length));return Re([t,e],t.length+e.length)}function ph(r){let e=ft(r);if(r=r.slice(Le(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function G0(r){let e;r[0]==="Q"||r[0]==="1"?e=pr(ee.decode(`z${r}`)).bytes:e=rt.parse(r).multihash.bytes;let t=Uint8Array.from(He(e.length));return Re([t,e],t.length+e.length)}function j0(r){let e=q0.decode(r),t=Uint8Array.from(He(e.length));return Re([t,e],t.length+e.length)}function Y0(r){let e=ft(r),t=r.slice(Le(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function W0(r){let e=ft(r),t=r.slice(Le(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function X0(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=qe.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=Rc(n);return Re([t,o],t.length+o.length)}function Z0(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=qe.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=Rc(n);return Re([t,o],t.length+o.length)}function mh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=gh(t);return`${n}:${o}`}function yh(r){r=Ic(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw bh("invalid address: "+r);if(a.path===!0){n=Ic(o.slice(s).join("/")),e.push([a.code,Ac(a.code,n)]),t.push([a.code,n]);break}let c=Ac(a.code,o[s]);e.push([a.code,c]),t.push([a.code,vc(a.code,c)])}return{string:wh(t),bytes:Sc(e),tuples:e,stringTuples:t,path:n}}function _c(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=ft(r,o),i=Le(s),a=W(s),c=J0(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 bh("Invalid address Uint8Array: "+V(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:wh(t),tuples:e,stringTuples:t,path:n}}function wh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Ic(e.join("/"))}function Sc(r){return Re(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(He(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function J0(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=ft(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Le(t)}}function Ic(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function bh(r){return new Error("Error parsing address: "+r)}var Q0=Symbol.for("nodejs.util.inspect.custom"),Bc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),ey=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Ks=class r{bytes;#e;#t;#s;#a;[Bc]=!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=yh(e)}else if(ir(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=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),ey.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=W(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({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Sc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===yn.p2p.code&&e.push([n,o]),n===yn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ee.decode(`z${n}`),"base58btc"):V(rt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ne(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=$s.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=>new r(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)}[Q0](){return`Multiaddr(${this.#e})`}};var $s=new Map;function ir(r){return!!r?.[Bc]}function se(r){return new Ks(r)}var Eh="libp2p-peer-record",xh=Uint8Array.from([3,1]);var io;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Me((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=>Ue(s,n.codec()),n.decode=s=>Oe(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Me((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=>Ue(n,r.codec()),r.decode=n=>Oe(n,r.codec())})(io||(io={}));var Tr=class r{static createFromProtobuf=e=>{let t=io.decode(e),n=fn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Eh;static CODEC=xh;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=io.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||!ih(this.multiaddrs,e.multiaddrs))}};function ty(r){return r[Symbol.asyncIterator]!=null}function ry(r){if(ty(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var ao=ry;var Tc=dt(Ah(),1);var lo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rh=r=>globalThis.DOMException===void 0?new Nc(r):new DOMException(r),Ih=r=>{let e=r.reason===void 0?Rh("This operation was aborted."):r.reason;return e instanceof Error?e:Rh(e)};function uo(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(Ih(p)),p.addEventListener("abort",()=>{f(Ih(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new lo;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 kc(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 fo=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=kc(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 wn=class extends Tc.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:fo,...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#A(){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.#A;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#R(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=uo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof lo&&!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 ar={},bn=r=>{r.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)})};bn.addEventListener=(r,e)=>{ar[r]==null&&(ar[r]=[]),ar[r].push(e)};bn.removeEventListener=(r,e)=>{ar[r]!=null&&(ar[r]=ar[r].filter(t=>t===e))};bn.dispatchEvent=function(r,e,t){ar[r]!=null&&ar[r].forEach(n=>n(e,t))};var Lc=bn;var Dc="lock:worker:request-read",Pc="lock:worker:release-read",Oc="lock:master:grant-read",Uc="lock:worker:request-write",Mc="lock:worker:release-write",Fc="lock:master:grant-write";var _h=(r=21)=>Math.random().toString().substring(2);var Sh=(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)})}}}))},Bh=(r,e,t,n)=>async()=>{let o=_h();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)})},sy={singleProcess:!1},Ch=r=>{if(r=Object.assign({},sy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Lc.addEventListener("message",Sh(t,"requestReadLock",Dc,Pc,Oc)),Lc.addEventListener("message",Sh(t,"requestWriteLock",Uc,Mc,Fc)),t}return{isWorker:!0,readLock:t=>Bh(t,Dc,Oc,Pc),writeLock:t=>Bh(t,Uc,Fc,Mc)}};var Nr={},cr;async function Vc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>uo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var iy=(r,e)=>{if(cr.isWorker===!0)return{readLock:cr.readLock(r,e),writeLock:cr.writeLock(r,e)};let t=new wn({concurrency:1}),n;return{async readLock(){if(n!=null)return Vc(n,e);n=new wn({concurrency:e.concurrency,autoStart:!1});let o=n,s=Vc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Vc(t,e)}}},ay={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Kc(r){let e=Object.assign({},ay,r);return cr==null&&(cr=Ch(e),cr.isWorker!==!0&&(cr.addEventListener("requestReadLock",t=>{Nr[t.data.name]!=null&&Nr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),cr.addEventListener("requestWriteLock",async t=>{Nr[t.data.name]!=null&&Nr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Nr[e.name]==null&&(Nr[e.name]=iy(e.name,e)),Nr[e.name]}var _e={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var En;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Me((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=>Ue(i,o.codec()),o.decode=i=>Oe(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Me((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),zs.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=zs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ue(i,o.codec()),o.decode=i=>Oe(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Me((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),qs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(qs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ue(o,r.codec()),r.decode=o=>Oe(o,r.codec())})(En||(En={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(qs||(qs={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(zs||(zs={}));function xn(r,e){let t=En.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=eh({...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 Ft="/",Th=new TextEncoder().encode(Ft),Gs=Th[0],kr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==Gs)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Th),this._buf[0]!==Gs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Gs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Gs;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return cy(this.baseNamespace())}name(){return ly(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...uy(e.map(t=>t.namespaces()))])}};function cy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function ly(r){let e=r.split(":");return e[e.length-1]}function uy(r){return[].concat(...r)}var $c="/peers/";function vn(r){if(!vo(r)||r.type==null)throw new E("Invalid PeerId",_e.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new kr(`${$c}${e}`)}async function Nh(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)),!ir(o.multiaddr))throw new E("Multiaddr was invalid",_e.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 Ys(r,e,t,n){if(e==null)throw new E("Invalid PeerData",_e.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ne(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",_e.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",_e.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=js(l,{validate:kh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=js(l,{validate:Lh,map:Dh})}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=js([...a.entries()],{validate:kh})}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=js([...p.entries()],{validate:Lh,map:Dh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Nh(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 js(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 kh(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",_e.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",_e.ERR_INVALID_PARAMETERS)}function Lh(r,e){if(typeof r!="string")throw new E("Tag name must be a string",_e.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",_e.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",_e.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",_e.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",_e.ERR_INVALID_PARAMETERS)}}function Dh(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 Ws(r,e,t){let n=r.toString().split("/")[2],o=qe.decode(n),s=fn(o),i=t.get(s);if(i!=null)return i;let a=xn(s,e);return t.set(s,a),a}function fy(r,e){return r==null?{}:{prefix:$c,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ws(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ws(n.key,n.value,e),Ws(o.key,o.value,e)))}}var Xs=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Kc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(vn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",_e.ERR_INVALID_PARAMETERS);await this.datastore.delete(vn(e))}async load(e){let t=await this.datastore.get(vn(e));return xn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(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 Ys(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 Ys(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Ye;for await(let{key:n,value:o}of this.datastore.query(fy(e??{},t))){let s=Ws(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(vn(e)),n=xn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=En.encode(t);return n!=null&&ne(s,n)?{peer:xn(e,s),previous:o,updated:!1}:(await this.datastore.put(vn(e),s),{peer:xn(e,s),previous:o,updated:!0})}};var Zs=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 Xs(e,t)}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 ao(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 pn.openAndCertify(e,Tr.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=Tr.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 pn.createFromProtobuf(s.peerRecordEnvelope),a=Tr.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 hy(r){return r[Symbol.asyncIterator]!=null}function dy(r){if(hy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Hc=dy;function py(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 Ph=py;function my(r){return r[Symbol.asyncIterator]!=null}function gy(r,e){if(my(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Ph(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let i=e;return function*(){s===!0&&(yield n);for(let a of t)i(a)&&(yield a)}()}var Lr=gy;function yy(r){return r[Symbol.asyncIterator]!=null}function wy(r,e){return yy(r)?async function*(){yield*(await ao(r)).sort(e)}():function*(){yield*ao(r).sort(e)}()}var qc=wy;function by(r){return r[Symbol.asyncIterator]!=null}function Ey(r,e){return by(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 zc=Ey;var Js=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 Hc(this.putMany(e,n)),e=[],await Hc(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=Lr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>qc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=zc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>qc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=zc(n,e.limit)),n}};var Mh=dt(Gc(),1);function Fh(r){return r=r??new Error("Not Found"),(0,Mh.default)(r,"ERR_NOT_FOUND")}var Qs=class extends Js{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 Fh();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 kr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new kr(e)}};function Vh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Ay=r=>r;function jc(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var ei=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??Ay,this._updatePeerStoreAddresses=Vh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([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=jc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=jc(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=jc(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 Yc=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=Ps())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fl(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")}},Ry=["metrics","connectionProtector"],Iy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Kh(r={}){let e=new Yc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Iy.includes(o)){let i=e.components[o];if(i==null&&!Ry.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}})}var Yh=dt($h(),1);var Hh="[a-fA-F\\d:]",lr=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Hh})|(?<=${Hh})(?=\\s|$))`:"",ht="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",he="[a-fA-F\\d]{1,4}",ti=`
8
- (?:
9
- (?:${he}:){7}(?:${he}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
10
- (?:${he}:){6}(?:${ht}|:${he}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
11
- (?:${he}:){5}(?::${ht}|(?::${he}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
12
- (?:${he}:){4}(?:(?::${he}){0,1}:${ht}|(?::${he}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
13
- (?:${he}:){3}(?:(?::${he}){0,2}:${ht}|(?::${he}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
14
- (?:${he}:){2}(?:(?::${he}){0,3}:${ht}|(?::${he}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
15
- (?:${he}:){1}(?:(?::${he}){0,4}:${ht}|(?::${he}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
16
- (?::(?:(?::${he}){0,5}:${ht}|(?::${he}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
17
- )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
18
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),_y=new RegExp(`(?:^${ht}$)|(?:^${ti}$)`),Sy=new RegExp(`^${ht}$`),By=new RegExp(`^${ti}$`),Wc=r=>r&&r.exact?_y:new RegExp(`(?:${lr(r)}${ht}${lr(r)})|(?:${lr(r)}${ti}${lr(r)})`,"g");Wc.v4=r=>r&&r.exact?Sy:new RegExp(`${lr(r)}${ht}${lr(r)}`,"g");Wc.v6=r=>r&&r.exact?By:new RegExp(`${lr(r)}${ti}${lr(r)}`,"g");var qh=Wc;var Wh=dt(Gh(),1),{isValid:Cy,parse:Ty}=Wh.default,Ny=["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"],ky=Ny.map(r=>new Yh.Netmask(r));function Ly(r){for(let e of ky)if(e.contains(r))return!0;return!1}function jh(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)}var Xh=r=>{if(Cy(r)){let e=Ty(r);if(e.kind()==="ipv4")return Ly(e.toNormalizedString());if(e.kind()==="ipv6")return jh(r)}else if(gn(r)&&qh.v6().test(r))return jh(r)};var ni=Xh;function Zh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ni(`${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 Dy=r=>r.toString().split("/").slice(1),po=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),ae=r=>({match:e=>po(t=>t===r).match(e),pattern:r}),ii=()=>({match:r=>po(e=>typeof e=="string").match(r),pattern:"{string}"}),Jh=()=>({match:r=>po(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),et=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ee.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),oi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ua.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),xt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),vt=(...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(", ")})`}),ce=(...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 ye(...r){function e(o){let s=Dy(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 Zc=ce(ae("dns4"),ii()),Jc=ce(ae("dns6"),ii()),Qc=ce(ae("dnsaddr"),ii()),Qh=ce(ae("dns"),ii()),zR=ye(Zc),GR=ye(Jc),jR=ye(Qc),YR=ye(vt(Qh,Qc,Zc,Jc)),ed=ce(ae("ip4"),po(Fs)),td=ce(ae("ip6"),po(Vs)),rd=vt(ed,td),mo=vt(rd,Qh,Zc,Jc,Qc),WR=ye(mo),XR=ye(ed),ZR=ye(td),JR=ye(rd),ai=ce(mo,ae("tcp"),Jh()),go=ce(mo,ae("udp"),Jh()),Py=vt(ai,go),QR=ye(ai),eI=ye(go),el=ce(go,ae("quic")),ci=ce(go,ae("quic-v1")),Oy=vt(el,ci),tI=ye(el),rI=ye(ci),Xc=vt(mo,ai,go,el,ci),nd=vt(ce(Xc,ae("ws"),xt(et()))),nI=ye(nd),od=vt(ce(Xc,ae("wss"),xt(et())),ce(Xc,ae("tls"),ae("ws"),xt(et()))),oI=ye(od),sd=ce(Py,ae("webrtc-direct"),oi(),xt(oi()),xt(et())),sI=ye(sd),id=ce(ci,ae("webtransport"),oi(),oi(),xt(et())),iI=ye(id),si=vt(nd,od,ce(ai,xt(et())),ce(Oy,xt(et())),ce(mo,xt(et())),sd,id,et()),aI=ye(si),Uy=ce(si,ae("p2p-circuit"),et()),tl=ye(Uy),My=vt(ce(si,ae("p2p-circuit"),ae("webrtc"),et()),ce(si,ae("webrtc"),xt(et())),ae("webrtc")),cI=ye(My);function rl(r){try{let{address:e}=r.nodeAddress();return!!ni(e)}catch{return!0}}function Fy(r,e){let t=rl(r.multiaddr),n=rl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Vy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Ky(r,e){let t=tl.exactMatch(r.multiaddr),n=tl.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function An(r,e){let t=Fy(r,e);if(t!==0)return t;let n=Ky(r,e);return n!==0?n:Vy(r,e)}var ol=dt(uc(),1),sl=dt(ld(),1);function li(r,e,t){return`${r}?name=${e}&type=${t}`}async function ud(r,e){return await(await fetch(r,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function Dr(r,e){return`${e}_${r}`}var nl=Object.assign((0,ol.default)("dns-over-http-resolver"),{error:(0,ol.default)("dns-over-http-resolver:error")}),il=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new sl.default({max:e?.maxCache??100}),this._TXTcache=new sl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??ud,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),o=e[t];e[t]=e[n],e[n]=o}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(Dr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(li(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Dr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),nl.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(Dr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(li(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Dr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),nl.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(Dr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(li(s,e,t),i.signal),c=a.Answer.map(f=>[f.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(f=>f.TTL));return this._TXTcache.set(Dr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),nl.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},fd=il;var hd=fd;var{code:Gy}=W("dnsaddr");async function Rn(r,e={}){let t=new hd;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,o]=r.stringTuples().find(([a])=>a===Gy)??[];if(o==null)throw new Error("No hostname found in multiaddr");let i=(await t.resolveTxt(`_dnsaddr.${o}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(i=i.filter(a=>a.includes(n))),i}var xd=dt(Ed(),1),hi=xd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var B;(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"})(B||(B={}));var Jy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Rn},addressSorter:An},transportManager:{faultTolerance:Kt.FATAL_ALL}};async function vd(r){let e=hi(Jy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await hn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var Ad=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Qy=new WeakMap;function ew({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Ad());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Ad())},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}),Qy.set(l,()=>{c(s),s=null,i()}),l}}var tw=ew(),Rd=tw;var di=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 cl}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 Rd(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)}},cl=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 pi(r){if(vo(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:ge(t),r.forEach(n=>{if(!ir(n))throw new E("Invalid Multiaddr",B.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",B.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function de(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var mi=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}},Sn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new mi(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 mi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ll=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gi(r={}){return rw(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 rw(r,e){e=e??{};let t=e.onEnd,n=new Sn,o,s,i,a=de(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(b){y(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=de()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Sn,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},p=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),h=()=>(n=new Sn,p(),{done:!0}),d=m=>(p(m),{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 m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,b;y!=null&&(w=new Promise((A,v)=>{b=()=>{v(new ll)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var ul=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function yi(r,e,t,n){let o=new ul(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{let a=u=>{n?.filter?.(u)!==!1&&(r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(u))},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var wi=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 Bn(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new wi(t?.errorMessage,t?.errorCode));let n,o=new wi(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 bi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=de(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function nw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ei=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=nw(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Xe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new $t)}async join(e={}){let t=new bi(new Error("where").stack,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 Bn(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.signal?.removeEventListener("abort",this.onAbort)})}};function ow(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 Cn=class extends dr{concurrency;queue;pending;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.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){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=ow(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new Ei(e,t,t?.priority),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),s)).catch(s=>{throw this.safeDispatchEvent("error",{detail:s}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new $t)}),this.clear()}async onEmpty(e){this.size!==0&&await yi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await yi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await yi(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=gi({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 xi=class extends Cn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var vi="last-dial-failure";var Ai=5,Ri=100,Ii=50,Id=1e3*60*7;var Pr={minConnections:Ai,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Id,autoDialDiscoveredPeersDebounce:10},_i=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??Pr.minConnections,this.autoDialPriority=t.autoDialPriority??Pr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Pr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Pr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Pr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Pr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new xi({concurrency:t.autoDialConcurrency??Pr.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 ut(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 Ye;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(vi);if(f==null)return!0;let l=parseInt(V(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _d={maxConnections:Ri,allow:[]},Si=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,n=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let o=new Ye;for(let a of e){let c=a.remotePeer;if(!o.has(c)){o.set(c,0);try{let u=await this.peerStore.get(c);o.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 s=e.sort((a,c)=>{let u=o.get(a.remotePeer)??0,f=o.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let l=a.timeline.open,p=c.timeline.open;return l<p?1:l>p?-1:0}),i=[];for(let a of s)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===n)break;await Promise.all(i.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:i})}};function Sd(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 pl(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await aw(r,e),i=(await Promise.all(n.map(async a=>pl(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",r,i.map(a=>a.toString())),i}async function aw(r,e){try{return r=se(r.toString()),await r.resolve(e)}catch(t){return e.log.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}var Bi={addressSorter:An,maxParallelDials:Ii,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:Rn}},Ci=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Bi.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Bi.maxPeerAddrsToDial,this.dialTimeout=t.dialTimeout??Bi.dialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,Xe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))$s.set(n,o);this.queue=new Cn({concurrency:t.maxParallelDials??Bi.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}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=pi(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)}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",B.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:{[vi]:D(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,Ro);l.push(h)}}throw l.length===1?l[0]:new Ao(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Sd([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return Xe(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",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",B.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!==B.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!==B.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 pl(l.multiaddr,{...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.transportForMultiaddr(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",B.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",B.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}};var uw=50,Or={minConnections:Ai,maxConnections:Ri,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ti=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Or.maxConnections;let n=t.minConnections??Or.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Ye,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??Or.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new di({points:t.inboundConnectionThreshold??Or.inboundConnectionThreshold,duration:1}),this.autoDial=new _i({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Or.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Or.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Or.autoDialMaxQueueLength}),this.connectionPruner=new Si({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ci(e,{addressSorter:t.addressSorter??An,maxParallelDials:t.maxParallelDials??Ii,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:Rn},connections:this.connections})}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(Ml)]});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",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=pi(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??uw}),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))}))}};function fw(r){return r[Symbol.asyncIterator]!=null}function hw(...r){let e=[];for(let t of r)fw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=gi({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 yo=hw;var Ni=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ut;for await(let s of yo(...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",B.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ki=globalThis.CustomEvent??Event;async function*yl(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=de(),a=de(),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=de(),await i.promise),f)break;let g={done:!1};s.push(g),d().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new ki("task-complete"))},m=>{g.done=!0,g.err=m,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 g=s[d];if(s.splice(d,1),d--,g.ok)yield g.value;else throw f=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(l()||(a=de(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var Li=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??[]}async findPeer(e,t){if(this.routers.length===0)throw new E("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=yo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Vt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ut;for await(let s of yl(async function*(){let i=yo(...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)&&(o.add(s.id),yield s))}};var wl=32,bl=64,Di=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)}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}`,B.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}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=hi.bind({ignoreUndefined:!0})({maxInboundStreams:wl,maxOutboundStreams:bl},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",B.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.onDisconnect?.(t)}}).catch(n=>{n.code!==B.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.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.onConnect?.(o,n)}}};var El=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 Bd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new El({name:e,metrics:t}):n=new Map,n}var Pi=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=Bd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Kt.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new E("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,B.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.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.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()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new E("Not started",B.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.filter(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!==Kt.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Kt.FATAL_ALL)throw new E(n,B.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 Se="/multistream/1.0.0";var xl=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=de(),this.haveNext=de()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=de(),e}async throw(e){return this.ended=!0,e!=null&&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");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=de(),await Bn(this.needNext.promise,t?.signal,t)}};function Cd(){return new xl}var Oi=class extends Error{code;constructor(e,t){super(e),this.code=t}},vl=class extends Oi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Td(r,e){let t=Cd();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 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 Ee:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Oi("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}}}function Ui(r){return r[Symbol.asyncIterator]!=null}var Mi=r=>{let e=Le(r),t=Ce(e);return He(r,t),Mi.bytes=e,t};Mi.bytes=0;function Ur(r,e){e=e??{};let t=e.lengthEncoder??Mi;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ui(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Ur.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mi;return new Ee(t(r.byteLength),r)};var Tn=dt(Gc(),1);var dw=8,pw=1024*1024*4,Mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Mr||(Mr={}));var Rl=r=>{let e=ft(r);return Rl.bytes=Le(e),e};Rl.bytes=0;function Al(r,e){let t=new Ee,n=Mr.LENGTH,o=-1,s=e?.lengthDecoder??Rl,i=e?.maxLengthLength??dw,a=e?.maxDataLength??pw;function*c(){for(;t.byteLength>0;){if(n===Mr.LENGTH)try{if(o=s(t),o<0)throw(0,Tn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Tn.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=Mr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Tn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Mr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Mr.LENGTH}}}return Ui(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Tn.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,Tn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Al.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 Al(n,{...e??{},onLength:s=>{t=s}})};var Fi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Nd=r=>ft(r);Nd.bytes=0;function wo(r,e={}){let t=Td(r,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength)),{read:async o=>{let s=-1,i=new Ee,a=e?.lengthDecoder??Nd;for(;;){i.append(await t.read(1,o));try{s=a(i)}catch(c){if(c instanceof RangeError)continue;throw c}if(e?.maxLengthLength!=null&&i.byteLength>e.maxLengthLength)throw new Fi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new Fi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(s,o)},write:async(o,s)=>{await t.write(Ur.single(o,e),s)},writeV:async(o,s)=>{let i=new Ee(...o.map(a=>Ur.single(a,e)));await t.write(i,s)},unwrap:()=>t.unwrap()}}var gw=D(`
19
- `);async function Fr(r,e,t){await r.write(e,t)}async function kd(r,e,t){await r.writeV(e,t)}async function yw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==gw[0])throw e.log.error("Invalid mss message - missing newline",t),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function fr(r,e){let t=await yw(r,e);return V(t.subarray())}async function bo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return ww(r,e[0],t);let n=wo(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"]',Se,o);let s=D(`${Se}
6
+ `)}`:`${t} :`}};$u=Jt;I.Constructed=$u;Jt.NAME="CONSTRUCTED";var Xo=class extends Ce{fromBER(e,t,n){return t}toBER(e){return it}};Xo.override="EndOfContentValueBlock";var qu,Zo=class extends Re{constructor(e={}){super(e,Xo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};qu=Zo;I.EndOfContent=qu;Zo.NAME=Hn;var Gu,Qt=class extends Re{constructor(e={}){super(e,Ce),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}`}};Gu=Qt;I.Null=Gu;Qt.NAME="NULL";var Jo=class extends Pt(Ce){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.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=H.BufferSourceConverter.toUint8Array(e);return Dt(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,$a.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Jo.NAME="BooleanValueBlock";var zu,Qo=class extends Re{constructor(e={}){super(e,Jo),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}`}};zu=Qo;I.Boolean=zu;Qo.NAME="BOOLEAN";var es=class extends Pt(mt){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=mt.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===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Fu)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?mt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};es.NAME="OctetStringValueBlock";var Yu,Lt=class r extends Re{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},es),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=Bs(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?Jt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.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 H.BufferSourceConverter.concat(e)}};Yu=Lt;I.OctetString=Yu;Lt.NAME=Fu;var ts=class extends Pt(mt){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=mt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Vu)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=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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=Bs(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 mt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return it;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}}};ts.NAME="BitStringValueBlock";var ju,Qr=class extends Re{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},ts),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 Jt.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)}`}}};ju=Qr;I.BitString=ju;Qr.NAME=Vu;var Wu;function Eg(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 h=f;h>=0;h--,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=$o(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=$o(t,s)),s}function Mu(r){if(r>=Vn.length)for(let e=Vn.length;e<=r;e++){let t=new Uint8Array([0]),n=Vn[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=$o(t,n)),Vn.push(n)}return Vn[r]}function xg(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 $n=class extends Pt(Ce){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=$a.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Pu(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=xg(Mu(n),t),i="-";break;default:t=Eg(t,Mu(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Uu.charAt(t[c]));return a===!1&&(i+=Uu.charAt(0)),i}};Wu=$n;$n.NAME="IntegerValueBlock";Object.defineProperty(Wu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Xu,fe=class r extends Re{constructor(e={}){super(e,$n),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return qo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){qo();let t=BigInt(e),n=new Kn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(H.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${H.Convert.ToHex(a)}`)+t,f=H.BufferSourceConverter.toUint8Array(H.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()}`}};Xu=fe;I.Integer=Xu;fe.NAME="INTEGER";var Zu,rs=class extends fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Zu=rs;I.Enumerated=Zu;rs.NAME="ENUMERATED";var qn=class extends Pt(Ce){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=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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=Er(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){qo();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=Zt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;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=H.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};qn.NAME="sidBlock";var ns=class extends Ce{constructor({value:e=en,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new qn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,it;t.push(o)}return qa(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new qn;if(o>Number.MAX_SAFE_INTEGER){qo();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}};ns.NAME="ObjectIdentifierValueBlock";var Ju,st=class extends Re{constructor(e={}){super(e,ns),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()}}};Ju=st;I.ObjectIdentifier=Ju;st.NAME="OBJECT IDENTIFIER";var Gn=class extends Pt(Nt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=H.BufferSourceConverter.toUint8Array(e);if(!Dt(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=Er(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=Zt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;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=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Gn.NAME="relativeSidBlock";var os=class extends Ce{constructor({value:e=en,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Gn;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,it;n.push(s)}return qa(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 Gn;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}};os.NAME="RelativeObjectIdentifierValueBlock";var Qu,ss=class extends Re{constructor(e={}){super(e,os),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()}}};Qu=ss;I.RelativeObjectIdentifier=Qu;ss.NAME="RelativeObjectIdentifier";var ef,be=class extends Jt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ef=be;I.Sequence=ef;be.NAME="SEQUENCE";var tf,is=class extends Jt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};tf=is;I.Set=tf;is.NAME="SET";var as=class extends Pt(Ce){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=en}toJSON(){return{...super.toJSON(),value:this.value}}};as.NAME="StringValueBlock";var cs=class extends as{};cs.NAME="SimpleStringValueBlock";var Fe=class extends Yo{constructor({...e}={}){super(e,cs)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.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}};Fe.NAME="SIMPLE STRING";var ls=class extends Fe{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ls.NAME="Utf8StringValueBlock";var rf,kt=class extends ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};rf=kt;I.Utf8String=rf;kt.NAME="UTF8String";var us=class extends Fe{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};us.NAME="BmpStringValueBlock";var nf,fs=class extends us{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};nf=fs;I.BmpString=nf;fs.NAME="BMPString";var hs=class extends Fe{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=Zt(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}};hs.NAME="UniversalStringValueBlock";var of,ds=class extends hs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};of=ds;I.UniversalString=of;ds.NAME="UniversalString";var sf,ps=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};sf=ps;I.NumericString=sf;ps.NAME="NumericString";var af,ms=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};af=ms;I.PrintableString=af;ms.NAME="PrintableString";var cf,gs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};cf=gs;I.TeletexString=cf;gs.NAME="TeletexString";var lf,ys=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};lf=ys;I.VideotexString=lf;ys.NAME="VideotexString";var uf,ws=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};uf=ws;I.IA5String=uf;ws.NAME="IA5String";var ff,bs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};ff=bs;I.GraphicString=ff;bs.NAME="GraphicString";var hf,zn=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};hf=zn;I.VisibleString=hf;zn.NAME="VisibleString";var df,Es=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};df=Es;I.GeneralString=df;Es.NAME="GeneralString";var pf,xs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};pf=xs;I.CharacterString=pf;xs.NAME="CharacterString";var mf,Yn=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,H.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]=He(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=He(this.month,2),t[2]=He(this.day,2),t[3]=He(this.hour,2),t[4]=He(this.minute,2),t[5]=He(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}}};mf=Yn;I.UTCTime=mf;Yn.NAME="UTCTime";var gf,vs=class extends Yn{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,h=n.indexOf("+"),g="";if(h===-1&&(h=n.indexOf("-"),l=-1),h!==-1){if(g=n.substring(h+1),n=n.substring(0,h),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(g.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,g.length===4){if(d=parseInt(g.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(He(this.year,4)),t.push(He(this.month,2)),t.push(He(this.day,2)),t.push(He(this.hour,2)),t.push(He(this.minute,2)),t.push(He(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(He(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};gf=vs;I.GeneralizedTime=gf;vs.NAME="GeneralizedTime";var yf,As=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};yf=As;I.DATE=yf;As.NAME="DATE";var wf,Rs=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};wf=Rs;I.TimeOfDay=wf;Rs.NAME="TimeOfDay";var bf,_s=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};bf=_s;I.DateTime=bf;_s.NAME="DateTime";var Ef,Ss=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Ef=Ss;I.Duration=Ef;Ss.NAME="Duration";var xf,Is=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};xf=Is;I.TIME=xf;Is.NAME="TIME";function Ag(r){let{result:e}=tn(r),t=e.valueBlock.value;return{n:V(gt(t[1].toBigInt()),"base64url"),e:V(gt(t[2].toBigInt()),"base64url"),d:V(gt(t[3].toBigInt()),"base64url"),p:V(gt(t[4].toBigInt()),"base64url"),q:V(gt(t[5].toBigInt()),"base64url"),dp:V(gt(t[6].toBigInt()),"base64url"),dq:V(gt(t[7].toBigInt()),"base64url"),qi:V(gt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Rg(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 w("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new be({value:[new fe({value:0}),fe.fromBigInt(yt(D(r.n,"base64url"))),fe.fromBigInt(yt(D(r.e,"base64url"))),fe.fromBigInt(yt(D(r.d,"base64url"))),fe.fromBigInt(yt(D(r.p,"base64url"))),fe.fromBigInt(yt(D(r.q,"base64url"))),fe.fromBigInt(yt(D(r.dp,"base64url"))),fe.fromBigInt(yt(D(r.dq,"base64url"))),fe.fromBigInt(yt(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function _g(r){let{result:e}=tn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:V(gt(t[0].toBigInt()),"base64url"),e:V(gt(t[1].toBigInt()),"base64url")}}function Sg(r){if(r.n==null||r.e==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new be({value:[new be({value:[new st({value:"1.2.840.113549.1.1.1"}),new Qt]}),new Qr({valueHex:new be({value:[fe.fromBigInt(yt(D(r.n,"base64url"))),fe.fromBigInt(yt(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function gt(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 yt(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 Ig=16,za=32,Ya=1e4;async function Bg(r,e){let t=Pe.get(),o=new be({value:[new fe({value:0}),new be({value:[new st({value:"1.2.840.113549.1.1.1"}),new Qt]}),new Lt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=br(Ig),a=await Ka(zr,e,i,{c:Ya,dkLen:za}),c=br(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 be({value:[new Lt({valueHex:i}),new fe({value:Ya}),new fe({value:za}),new be({value:[new st({value:"1.2.840.113549.2.11"}),new Qt]})]}),h=new be({value:[new st({value:"1.2.840.113549.1.5.13"}),new be({value:[new be({value:[new st({value:"1.2.840.113549.1.5.12"}),l]}),new be({value:[new st({value:"2.16.840.1.101.3.4.1.42"}),new Lt({valueHex:c})]})]})]}),d=new be({value:[h,new Lt({valueHex:f})]}).toBER(),p=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...V(p,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
+ `)}async function Tg(r,e){let t=Pe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=tn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Cg(s),l=await Ka(zr,e,a,{c,dkLen:u}),h=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),g=jn(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,f)),{result:d}=tn(g);n=vf(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=tn(o);n=vf(s)}else throw new w("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return ja(n)}function Cg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new w("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 w("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=jn(s.valueBlock.value[0].getValue()),a=Ya,c=za;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 w("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 w("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 vf(r){return jn(r.valueBlock.value[2].getValue())}function jn(r){return new Uint8Array(r,0,r.byteLength)}async function Af(r){let e=await Pe.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 Sf(e);return{privateKey:t[0],publicKey:t[1]}}async function Wa(r){let t=[await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Ng(r)],n=await Sf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Rf(r,e){let t=await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Pe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function _f(r,e,t){let n=await Pe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Pe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Sf(r){if(r.privateKey==null||r.publicKey==null)throw new w("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Pe.get().subtle.exportKey("jwk",r.privateKey),Pe.get().subtle.exportKey("jwk",r.publicKey)])}async function Ng(r){return Pe.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 Ts(r){if(r.kty!=="RSA")throw new w("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new w("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var Xn=8192,Wn=class{_key;constructor(e){this._key=e}verify(e,t){return _f(this._key,t,e)}marshal(){return er.jwkToPkix(this._key)}get bytes(){return dt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ve.digest(this.bytes);return Xe(e)?e.then(({bytes:t})=>t):e.bytes}},rn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return br(16)}sign(e){return Rf(this._key,e)}get public(){if(this._publicKey==null)throw new w("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Wn(this._publicKey)}marshal(){return er.jwkToPkcs1(this._key)}get bytes(){return pt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ve.digest(this.bytes);return Xe(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return er.exportToPem(this,e);if(t==="libp2p-key")return Wr(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function ja(r){let e=er.pkcs1ToJwk(r);if(Ts(e)>Xn)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Wa(e);return new rn(t.privateKey,t.publicKey)}function kg(r){let e=er.pkixToJwk(r);if(Ts(e)>Xn)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Wn(e)}async function Dg(r){if(Ts(r)>Xn)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Wa(r);return new rn(e.privateKey,e.publicKey)}async function Pg(r){if(r>Xn)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Af(r);return new rn(e.privateKey,e.publicKey)}var tc={};we(tc,{Secp256k1PrivateKey:()=>Jn,Secp256k1PublicKey:()=>Zn,generateKeyPair:()=>Xg,unmarshalSecp256k1PrivateKey:()=>jg,unmarshalSecp256k1PublicKey:()=>Wg});var Og=(r,e,t)=>r&e^~r&t,Ug=(r,e,t)=>r&e^r&t^e&t,Mg=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]),tr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),rr=new Uint32Array(64),Za=class extends Gr{constructor(){super(64,32,8,!1),this.A=tr[0]|0,this.B=tr[1]|0,this.C=tr[2]|0,this.D=tr[3]|0,this.E=tr[4]|0,this.F=tr[5]|0,this.G=tr[6]|0,this.H=tr[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)rr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=rr[l-15],g=rr[l-2],d=tt(h,7)^tt(h,18)^h>>>3,p=tt(g,17)^tt(g,19)^g>>>10;rr[l]=p+rr[l-7]+d+rr[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 h=tt(a,6)^tt(a,11)^tt(a,25),g=f+h+Og(a,c,u)+Mg[l]+rr[l]|0,p=(tt(n,2)^tt(n,13)^tt(n,22))+Ug(n,o,s)|0;f=u,u=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+p|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(){rr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var If=Io(()=>new Za);function Fg(r){let e=Dn(r);ht(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:Vg,hexToBytes:Kg}=Co,xr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=xr;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:Vg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=xr,t=typeof r=="string"?Kg(r):r;if(!rt(t))throw new Error("ui8a expected");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}=xr._parseInt(t.subarray(2)),{d:i,l:a}=xr._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}`}},Ot=BigInt(0),Je=BigInt(1),Ox=BigInt(2),Bf=BigInt(3),Ux=BigInt(4);function Hg(r){let e=Fg(r),{Fp:t}=e,n=e.toBytes||((d,p,m)=>{let y=p.toAffine();return It(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),o=e.fromBytes||(d=>{let p=d.subarray(1),m=t.fromBytes(p.subarray(0,t.BYTES)),y=t.fromBytes(p.subarray(t.BYTES,2*t.BYTES));return{x:m,y}});function s(d){let{a:p,b:m}=e,y=t.sqr(d),x=t.mul(y,d);return t.add(t.add(x,t.mul(d,p)),m)}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"&&Ot<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:p,nByteLength:m,wrapPrivateKey:y,n:x}=e;if(p&&typeof d!="bigint"){if(rt(d)&&(d=_t(d)),typeof d!="string"||!p.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:St(oe("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return y&&(b=X(b,x)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,y){if(this.px=p,this.py=m,this.pz=y,p==null||!t.isValid(p))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required")}static fromAffine(p){let{x:m,y}=p||{};if(!p||!t.isValid(m)||!t.isValid(y))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(m)&&x(y)?l.ZERO:new l(m,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=t.invertBatch(p.map(y=>y.pz));return p.map((y,x)=>y.toAffine(m[x])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(o(oe("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!t.isValid(p)||!t.isValid(m))throw new Error("bad point: x or y not FE");let y=t.sqr(m),x=s(p);if(!t.eql(y,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(t.isOdd)return!t.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:y,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.eql(t.mul(m,v),t.mul(b,x)),C=t.eql(t.mul(y,v),t.mul(A,x));return S&&C}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:p,b:m}=e,y=t.mul(m,Bf),{px:x,py:b,pz:A}=this,v=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(x,x),q=t.mul(b,b),G=t.mul(A,A),U=t.mul(x,b);return U=t.add(U,U),C=t.mul(x,A),C=t.add(C,C),v=t.mul(p,C),S=t.mul(y,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),C=t.mul(y,C),G=t.mul(p,G),U=t.sub(N,G),U=t.mul(p,U),U=t.add(U,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,G),N=t.mul(N,U),S=t.add(S,N),G=t.mul(b,A),G=t.add(G,G),N=t.mul(G,U),v=t.sub(v,N),C=t.mul(G,q),C=t.add(C,C),C=t.add(C,C),new l(v,S,C)}add(p){f(p);let{px:m,py:y,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.ZERO,C=t.ZERO,N=t.ZERO,q=e.a,G=t.mul(e.b,Bf),U=t.mul(m,b),le=t.mul(y,A),ie=t.mul(x,v),je=t.add(m,y),R=t.add(b,A);je=t.mul(je,R),R=t.add(U,le),je=t.sub(je,R),R=t.add(m,x);let L=t.add(b,v);return R=t.mul(R,L),L=t.add(U,ie),R=t.sub(R,L),L=t.add(y,x),S=t.add(A,v),L=t.mul(L,S),S=t.add(le,ie),L=t.sub(L,S),N=t.mul(q,R),S=t.mul(G,ie),N=t.add(S,N),S=t.sub(le,N),N=t.add(le,N),C=t.mul(S,N),le=t.add(U,U),le=t.add(le,U),ie=t.mul(q,ie),R=t.mul(G,R),le=t.add(le,ie),ie=t.sub(U,ie),ie=t.mul(q,ie),R=t.add(R,ie),U=t.mul(le,R),C=t.add(C,U),U=t.mul(L,R),S=t.mul(je,S),S=t.sub(S,U),U=t.mul(je,le),N=t.mul(L,N),N=t.add(N,U),new l(S,C,N)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return g.wNAFCached(this,u,p,m=>{let y=t.invertBatch(m.map(x=>x.pz));return m.map((x,b)=>x.toAffine(y[b])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===Ot)return m;if(a(p),p===Je)return this;let{endo:y}=e;if(!y)return g.unsafeLadder(this,p);let{k1neg:x,k1:b,k2neg:A,k2:v}=y.splitScalar(p),S=m,C=m,N=this;for(;b>Ot||v>Ot;)b&Je&&(S=S.add(N)),v&Je&&(C=C.add(N)),N=N.double(),b>>=Je,v>>=Je;return x&&(S=S.negate()),A&&(C=C.negate()),C=new l(t.mul(C.px,y.beta),C.py,C.pz),S.add(C)}multiply(p){a(p);let m=p,y,x,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:S,k2:C}=b.splitScalar(m),{p:N,f:q}=this.wNAF(v),{p:G,f:U}=this.wNAF(C);N=g.constTimeNegate(A,N),G=g.constTimeNegate(S,G),G=new l(t.mul(G.px,b.beta),G.py,G.pz),y=N.add(G),x=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);y=A,x=v}return l.normalizeZ([y,x])[0]}multiplyAndAddUnsafe(p,m,y){let x=l.BASE,b=(v,S)=>S===Ot||S===Je||!v.equals(x)?v.multiplyUnsafe(S):v.multiply(S),A=b(this,m).add(b(p,y));return A.is0()?void 0:A}toAffine(p){let{px:m,py:y,pz:x}=this,b=this.is0();p==null&&(p=b?t.ONE:t.inv(x));let A=t.mul(m,p),v=t.mul(y,p),S=t.mul(x,p);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=e;if(p===Je)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=e;return p===Je?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return _t(this.toRawBytes(p))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,g=ko(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function $g(r){let e=Dn(r);return ht(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Tf(r){let e=$g(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(R){return Ot<R&&R<t.ORDER}function a(R){return X(R,n)}function c(R){return No(R,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=Hg({...e,toBytes(R,L,M){let _=L.toAffine(),E=t.toBytes(_.x),T=It;return M?T(Uint8Array.from([L.hasEvenY()?2:3]),E):T(Uint8Array.from([4]),E,t.toBytes(_.y))},fromBytes(R){let L=R.length,M=R[0],_=R.subarray(1);if(L===o&&(M===2||M===3)){let E=St(_);if(!i(E))throw new Error("Point is not on curve");let T=l(E),k=t.sqrt(T),P=(k&Je)===Je;return(M&1)===1!==P&&(k=t.neg(k)),{x:E,y:k}}else if(L===s&&M===4){let E=t.fromBytes(_.subarray(0,t.BYTES)),T=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:E,y:T}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),g=R=>_t(Wt(R,e.nByteLength));function d(R){let L=n>>Je;return R>L}function p(R){return d(R)?a(-R):R}let m=(R,L,M)=>St(R.slice(L,M));class y{constructor(L,M,_){this.r=L,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(L){let M=e.nByteLength;return L=oe("compactSignature",L,M*2),new y(m(L,0,M),m(L,M,2*M))}static fromDER(L){let{r:M,s:_}=xr.toSig(oe("DER",L));return new y(M,_)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new y(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:_,recovery:E}=this,T=C(oe("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let k=E===2||E===3?M+e.n:M;if(k>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=E&1?"03":"02",F=u.fromHex(P+g(k)),K=c(k),j=a(-T*K),$=a(_*K),z=u.BASE.multiplyAndAddUnsafe(F,j,$);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return dr(this.toDERHex())}toDERHex(){return xr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let x={isValidPrivateKey(R){try{return f(R),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let R=xa(e.n);return pu(e.randomBytes(R),e.n)},precompute(R=8,L=u.BASE){return L._setWindowSize(R),L.multiply(BigInt(3)),L}};function b(R,L=!0){return u.fromPrivateKey(R).toRawBytes(L)}function A(R){let L=rt(R),M=typeof R=="string",_=(L||M)&&R.length;return L?_===o||_===s:M?_===2*o||_===2*s:R instanceof u}function v(R,L,M=!0){if(A(R))throw new Error("first arg must be private key");if(!A(L))throw new Error("second arg must be public key");return u.fromHex(L).multiply(f(R)).toRawBytes(M)}let S=e.bits2int||function(R){let L=St(R),M=R.length*8-e.nBitLength;return M>0?L>>BigInt(M):L},C=e.bits2int_modN||function(R){return a(S(R))},N=kn(e.nBitLength);function q(R){if(typeof R!="bigint")throw new Error("bigint expected");if(!(Ot<=R&&R<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Wt(R,e.nByteLength)}function G(R,L,M=U){if(["recovered","canonical"].some(te=>te in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:E}=e,{lowS:T,prehash:k,extraEntropy:P}=M;T==null&&(T=!0),R=oe("msgHash",R),k&&(R=oe("prehashed msgHash",_(R)));let F=C(R),K=f(L),j=[q(K),q(F)];if(P!=null){let te=P===!0?E(t.BYTES):P;j.push(oe("extraEntropy",te))}let $=It(...j),z=F;function ue(te){let Ee=S(te);if(!h(Ee))return;let xe=c(Ee),de=u.BASE.multiply(Ee).toAffine(),Ie=a(de.x);if(Ie===Ot)return;let Et=a(xe*a(z+Ie*K));if(Et===Ot)return;let lr=(de.x===Ie?0:2)|Number(de.y&Je),Bn=Et;return T&&d(Et)&&(Bn=p(Et),lr^=1),new y(Ie,Bn,lr)}return{seed:$,k2sig:ue}}let U={lowS:e.lowS,prehash:!1},le={lowS:e.lowS,prehash:!1};function ie(R,L,M=U){let{seed:_,k2sig:E}=G(R,L,M),T=e;return ya(T.hash.outputLen,T.nByteLength,T.hmac)(_,E)}u.BASE._setWindowSize(8);function je(R,L,M,_=le){let E=R;if(L=oe("msgHash",L),M=oe("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:T,prehash:k}=_,P,F;try{if(typeof E=="string"||rt(E))try{P=y.fromDER(E)}catch(de){if(!(de instanceof xr.Err))throw de;P=y.fromCompact(E)}else if(typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint"){let{r:de,s:Ie}=E;P=new y(de,Ie)}else throw new Error("PARSE");F=u.fromHex(M)}catch(de){if(de.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&P.hasHighS())return!1;k&&(L=e.hash(L));let{r:K,s:j}=P,$=C(L),z=c(j),ue=a($*z),te=a(K*z),Ee=u.BASE.multiplyAndAddUnsafe(F,ue,te)?.toAffine();return Ee?a(Ee.x)===K:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ie,verify:je,ProjectivePoint:u,Signature:y,utils:x}}function qg(r){return{hash:r,hmac:(e,...t)=>Fn(r,e,So(...t)),randomBytes:qr}}function Cf(r,e){let t=n=>Tf({...r,...qg(n)});return Object.freeze({...t(e),create:t})}var kf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Nf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Gg=BigInt(1),Ja=BigInt(2),Lf=(r,e)=>(r+e/Ja)/e;function zg(r){let e=kf,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=J(f,t,e)*f%e,h=J(l,t,e)*f%e,g=J(h,Ja,e)*u%e,d=J(g,o,e)*g%e,p=J(d,s,e)*d%e,m=J(p,a,e)*p%e,y=J(m,c,e)*m%e,x=J(y,a,e)*p%e,b=J(x,t,e)*f%e,A=J(b,i,e)*d%e,v=J(A,n,e)*u%e,S=J(v,Ja,e);if(!Qa.eql(Qa.sqr(S),r))throw new Error("Cannot find square root");return S}var Qa=Lo(kf,void 0,void 0,{sqrt:zg}),at=Cf({a:BigInt(0),b:BigInt(7),Fp:Qa,n:Nf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Nf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Gg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Lf(s*r,e),c=Lf(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},If),zx=BigInt(0);var Yx=at.ProjectivePoint;function Df(){return at.utils.randomPrivateKey()}function Pf(r,e){let t=ve.digest(e instanceof Uint8Array?e:e.subarray());if(Xe(t))return t.then(({digest:n})=>at.sign(n,r).toDERRawBytes()).catch(n=>{throw new w(String(n),"ERR_INVALID_INPUT")});try{return at.sign(t.digest,r).toDERRawBytes()}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}function Of(r,e,t){let n=ve.digest(t instanceof Uint8Array?t:t.subarray());if(Xe(n))return n.then(({digest:o})=>at.verify(e,o,r)).catch(o=>{throw new w(String(o),"ERR_INVALID_INPUT")});try{return at.verify(e,n.digest,r)}catch(o){throw new w(String(o),"ERR_INVALID_INPUT")}}function Uf(r){return at.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Mf(r){try{at.getPublicKey(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ec(r){try{at.ProjectivePoint.fromHex(r)}catch(e){throw new w(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Ff(r){try{return at.getPublicKey(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Zn=class{_key;constructor(e){ec(e),this._key=e}verify(e,t){return Of(this._key,t,e)}marshal(){return Uf(this._key)}get bytes(){return dt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=ve.digest(this.bytes),t;return Xe(e)?{bytes:t}=await e:t=e.bytes,t}},Jn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Ff(e),Mf(this._key),ec(this._publicKey)}sign(e){return Pf(this._key,e)}get public(){return new Zn(this._publicKey)}marshal(){return this._key}get bytes(){return pt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ve.digest(this.bytes);return Xe(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Wr(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function jg(r){return new Jn(r)}function Wg(r){return new Zn(r)}async function Xg(){let r=Df();return new Jn(r)}var nr={rsa:Xa,ed25519:Va,secp256k1:tc};function rc(r){let e=Object.keys(nr).join(" / ");return new w(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function nc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return nr[r];throw rc(r)}async function Vf(r,e){return nc(r).generateKeyPair(e??2048)}function Qn(r){let e=dt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return nr.rsa.unmarshalRsaPublicKey(t);case Q.Ed25519:return nr.ed25519.unmarshalEd25519PublicKey(t);case Q.Secp256k1:return nr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw rc(e.Type??"unknown")}}function Kf(r,e){return e=(e??"rsa").toLowerCase(),nc(e),r.bytes}async function eo(r){let e=pt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return nr.rsa.unmarshalRsaPrivateKey(t);case Q.Ed25519:return nr.ed25519.unmarshalEd25519PrivateKey(t);case Q.Secp256k1:return nr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw rc(e.Type??"RSA")}}function Hf(r,e){return e=(e??"rsa").toLowerCase(),nc(e),r.bytes}var ze=xt(sc(),1);ze.default.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);ze.default.formatters.t=r=>r==null?"undefined":$e.baseEncode(r);ze.default.formatters.m=r=>r==null?"undefined":Nn.baseEncode(r);ze.default.formatters.p=r=>r==null?"undefined":r.toString();ze.default.formatters.c=r=>r==null?"undefined":r.toString();ze.default.formatters.k=r=>r==null?"undefined":r.toString();ze.default.formatters.a=r=>r==null?"undefined":r.toString();function l0(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 Ls(){return{forComponent(r){return u0(r)}}}function u0(r){let e=l0(`${r}:trace`);return ze.default.enabled(`${r}:trace`)&&ze.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,ze.default)(`${r}:trace`)),Object.assign((0,ze.default)(r),{error:(0,ze.default)(`${r}:error`),trace:e})}var f0=Symbol.for("nodejs.util.inspect.custom"),zf=Object.values(qt).map(r=>r.decoder).reduce((r,e)=>r.or(e),qt.identity.decoder),Yf=114,ic=36,ac=37,to=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()})`}[Fi]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return et.createV1(Yf,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return me(e).equals(this);if(e?.multihash?.bytes!=null)return ne(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[f0](){return`PeerId(${this.toString()})`}},Ar=class extends to{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Rr=class extends to{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},_r=class extends to{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function jf(r){if(r.type==="RSA")return new Ar(r);if(r.type==="Ed25519")return new Rr(r);if(r.type==="secp256k1")return new _r(r);throw new w("Not a PeerId","ERR_INVALID_PARAMETERS")}function me(r,e){if(e=e??zf,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=fr(ee.decode(`z${r}`));return r.startsWith("12D")?new Rr({multihash:t}):r.startsWith("16U")?new _r({multihash:t}):new Ar({multihash:t})}return an(zf.decode(r))}function an(r){try{let e=fr(r);if(e.code===Ht.code){if(e.digest.length===ic)return new Rr({multihash:e});if(e.digest.length===ac)return new _r({multihash:e})}if(e.code===ve.code)return new Ar({multihash:e})}catch{return h0(et.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function h0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Yf)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===ve.code)return new Ar({multihash:r.multihash});if(e.code===Ht.code){if(e.digest.length===ic)return new Rr({multihash:r.multihash});if(e.digest.length===ac)return new _r({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function cn(r,e){return r.length===ic?new Rr({multihash:ft(Ht.code,r),privateKey:e}):r.length===ac?new _r({multihash:ft(Ht.code,r),privateKey:e}):new Ar({multihash:await ve.digest(r),publicKey:r,privateKey:e})}function ln(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 Ye=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 ln(this.map.entries(),e=>[me(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,me(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 ln(this.map.keys(),e=>me(e))}values(){return this.map.values()}get size(){return this.map.size}};var ct=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 ln(this.set.entries(),e=>{let t=me(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=me(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ln(this.set.values(),e=>me(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 Wf=async()=>{let r=await Vf("Ed25519"),e=await d0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function d0(r){return cn(Kf(r.public),Hf(r))}var p0=Math.pow(2,7),m0=Math.pow(2,14),g0=Math.pow(2,21),cc=Math.pow(2,28),lc=Math.pow(2,35),uc=Math.pow(2,42),fc=Math.pow(2,49),Y=128,Ne=127;function Le(r){if(r<p0)return 1;if(r<m0)return 2;if(r<g0)return 3;if(r<cc)return 4;if(r<lc)return 5;if(r<uc)return 6;if(r<fc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function y0(r,e,t=0){switch(Le(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function w0(r,e,t=0){switch(Le(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function b0(r,e){let t=r[e],n=0;if(n+=t&Ne,t<Y||(t=r[e+1],n+=(t&Ne)<<7,t<Y)||(t=r[e+2],n+=(t&Ne)<<14,t<Y)||(t=r[e+3],n+=(t&Ne)<<21,t<Y)||(t=r[e+4],n+=(t&Ne)*cc,t<Y)||(t=r[e+5],n+=(t&Ne)*lc,t<Y)||(t=r[e+6],n+=(t&Ne)*uc,t<Y)||(t=r[e+7],n+=(t&Ne)*fc,t<Y))return n;throw new RangeError("Could not decode varint")}function E0(r,e){let t=r.get(e),n=0;if(n+=t&Ne,t<Y||(t=r.get(e+1),n+=(t&Ne)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ne)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ne)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ne)*cc,t<Y)||(t=r.get(e+5),n+=(t&Ne)*lc,t<Y)||(t=r.get(e+6),n+=(t&Ne)*uc,t<Y)||(t=r.get(e+7),n+=(t&Ne)*fc,t<Y))return n;throw new RangeError("Could not decode varint")}function ke(r,e,t=0){return e==null&&(e=Be(Le(r))),e instanceof Uint8Array?y0(r,e,t):w0(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?b0(r,e):E0(r,e)}var Zf=Symbol.for("@achingbrain/uint8arraylist");function Xf(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 ks(r){return!!r?.[Zf]}var ge=class r{bufs;length;[Zf]=!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(ks(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(ks(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=Xf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Xf(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(ks(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 Ae(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ae(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(!ks(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 h=u;h>=0;h--){let g=this.get(l+h);if(n[h]!==g){f=Math.max(1,h-a[g]);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=Be(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=At(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=At(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=At(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=Be(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=At(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=At(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=At(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=At(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=At(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(!ne(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 Jf={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var ro;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(ro||(ro={}));var un=class r{static createFromProtobuf=async e=>{let t=ro.decode(e),n=await cn(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=Qf(n,o,s),c=await(await eo(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 w("envelope signature is not valid for the given domain",Jf.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=ro.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ne(this.marshal(),e.marshal())}async validate(e){let t=Qf(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Qn(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Qf=(r,e,t)=>{let n=D(r),o=ke(n.byteLength),s=ke(e.length),i=ke(t.length);return new ge(o,n,s,e,i,t)};function eh(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 Ds=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 h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});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 th=45,x0=15,fn=new Ds;function hc(r){if(!(r.length>x0))return fn.new(r).parseWith(()=>fn.readIPv4Addr())}function dc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>th))return fn.new(r).parseWith(()=>fn.readIPv6Addr())}function Ps(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>th))return fn.new(r).parseWith(()=>fn.readIPAddr())}var f1=parseInt("0xFFFF",16),h1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hn(r){return!!hc(r)}function dn(r){return!!dc(r)}function Os(r){return!!Ps(r)}var oh=hn,S0=dn,pc=function(r){let e=0;if(r=r.toString().trim(),oh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(S0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=oh(t[n]),i;s&&(i=pc(t[n]),t[n]=V(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,V(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},sh=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 pn={},mc={},B0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];B0.forEach(r=>{let e=T0(...r);mc[e.code]=e,pn[e.name]=e});function T0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(mc[r]!=null)return mc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(pn[r]!=null)return pn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var W1=W("ip4"),X1=W("ip6"),Z1=W("ipcidr");function yc(r,e){switch(W(r).code){case 4:case 41:return N0(e);case 42:return ch(e);case 6:case 273:case 33:case 132:return uh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ch(e);case 421:return P0(e);case 444:return lh(e);case 445:return lh(e);case 466:return D0(e);default:return V(e,"base16")}}function wc(r,e){switch(W(r).code){case 4:return ih(e);case 41:return ih(e);case 42:return ah(e);case 6:case 273:case 33:case 132:return bc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ah(e);case 421:return L0(e);case 444:return O0(e);case 445:return U0(e);case 466:return k0(e);default:return D(e,"base16")}}var gc=Object.values(qt).map(r=>r.decoder),C0=function(){let r=gc[0].or(gc[1]);return gc.slice(2).forEach(e=>r=r.or(e)),r}();function ih(r){if(!Os(r))throw new Error("invalid ip address");return pc(r)}function N0(r){let e=sh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Os(e))throw new Error("invalid ip address");return e}function bc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function uh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ah(r){let e=D(r),t=Uint8Array.from(ke(e.length));return Ae([t,e],t.length+e.length)}function ch(r){let e=lt(r);if(r=r.slice(Le(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function L0(r){let e;r[0]==="Q"||r[0]==="1"?e=fr(ee.decode(`z${r}`)).bytes:e=et.parse(r).multihash.bytes;let t=Uint8Array.from(ke(e.length));return Ae([t,e],t.length+e.length)}function k0(r){let e=C0.decode(r),t=Uint8Array.from(ke(e.length));return Ae([t,e],t.length+e.length)}function D0(r){let e=lt(r),t=r.slice(Le(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function P0(r){let e=lt(r),t=r.slice(Le(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function O0(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=$e.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=bc(n);return Ae([t,o],t.length+o.length)}function U0(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=$e.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=bc(n);return Ae([t,o],t.length+o.length)}function lh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=uh(t);return`${n}:${o}`}function fh(r){r=Ec(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw dh("invalid address: "+r);if(a.path===!0){n=Ec(o.slice(s).join("/")),e.push([a.code,wc(a.code,n)]),t.push([a.code,n]);break}let c=wc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,yc(a.code,c)])}return{string:hh(t),bytes:vc(e),tuples:e,stringTuples:t,path:n}}function xc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=Le(s),a=W(s),c=M0(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 dh("Invalid address Uint8Array: "+V(r,"base16"));e.push([s,u]);let f=yc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:hh(t),tuples:e,stringTuples:t,path:n}}function hh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Ec(e.join("/"))}function vc(r){return Ae(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(ke(t.code));return e.length>1&&e[1]!=null&&(n=Ae([n,e[1]])),n}))}function M0(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+Le(t)}}function Ec(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function dh(r){return new Error("Error parsing address: "+r)}var F0=Symbol.for("nodejs.util.inspect.custom"),Ac=Symbol.for("@multiformats/js-multiaddr/multiaddr"),V0=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Us=class r{bytes;#e;#t;#s;#a;[Ac]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=xc(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(or(e))t=xc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[g,d]of this.stringTuples())g===l.code&&(s=`%${d??""}`),V0.includes(g)&&(t=i.name,o=443,n=`${d??""}${s}`,e=g===f.code?6:4),(g===i.code||g===a.code)&&(t=W(g).name,o=parseInt(d??"")),(g===c.code||g===u.code)&&(t=W(g).name,n=`${d??""}${s}`,e=g===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(vc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===pn.p2p.code&&e.push([n,o]),n===pn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ee.decode(`z${n}`),"base58btc"):V(et.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ne(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Ms.get(t.name);if(n==null)throw new w(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new r(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)}[F0](){return`Multiaddr(${this.#e})`}};var Ms=new Map;function or(r){return!!r?.[Ac]}function se(r){return new Us(r)}var ph="libp2p-peer-record",mh=Uint8Array.from([3,1]);var no;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Me((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=>Ue(s,n.codec()),n.decode=s=>Oe(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Me((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=>Ue(n,r.codec()),r.decode=n=>Oe(n,r.codec())})(no||(no={}));var Ir=class r{static createFromProtobuf=e=>{let t=no.decode(e),n=an(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=ph;static CODEC=mh;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=no.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||!eh(this.multiaddrs,e.multiaddrs))}};function K0(r){return r[Symbol.asyncIterator]!=null}function H0(r){if(K0(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 oo=H0;var _c=xt(yh(),1);var io=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Sc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},wh=r=>globalThis.DOMException===void 0?new Sc(r):new DOMException(r),bh=r=>{let e=r.reason===void 0?wh("This operation was aborted."):r.reason;return e instanceof Error?e:wh(e)};function ao(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:h}=e;h.aborted&&f(bh(h)),h.addEventListener("abort",()=>{f(bh(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new io;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}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(h){f(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Ic(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 co=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=Ic(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 mn=class extends _c.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:co,...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#A(){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.#A;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#R(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=ao(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof io&&!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 sr={},gn=r=>{r.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)})};gn.addEventListener=(r,e)=>{sr[r]==null&&(sr[r]=[]),sr[r].push(e)};gn.removeEventListener=(r,e)=>{sr[r]!=null&&(sr[r]=sr[r].filter(t=>t===e))};gn.dispatchEvent=function(r,e,t){sr[r]!=null&&sr[r].forEach(n=>n(e,t))};var Bc=gn;var Tc="lock:worker:request-read",Cc="lock:worker:release-read",Nc="lock:master:grant-read",Lc="lock:worker:request-write",kc="lock:worker:release-write",Dc="lock:master:grant-write";var Eh=(r=21)=>Math.random().toString().substring(2);var xh=(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)})}}}))},vh=(r,e,t,n)=>async()=>{let o=Eh();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)})},G0={singleProcess:!1},Ah=r=>{if(r=Object.assign({},G0,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Bc.addEventListener("message",xh(t,"requestReadLock",Tc,Cc,Nc)),Bc.addEventListener("message",xh(t,"requestWriteLock",Lc,kc,Dc)),t}return{isWorker:!0,readLock:t=>vh(t,Tc,Nc,Cc),writeLock:t=>vh(t,Lc,Dc,kc)}};var Br={},ir;async function Pc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>ao((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var z0=(r,e)=>{if(ir.isWorker===!0)return{readLock:ir.readLock(r,e),writeLock:ir.writeLock(r,e)};let t=new mn({concurrency:1}),n;return{async readLock(){if(n!=null)return Pc(n,e);n=new mn({concurrency:e.concurrency,autoStart:!1});let o=n,s=Pc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Pc(t,e)}}},Y0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Oc(r){let e=Object.assign({},Y0,r);return ir==null&&(ir=Ah(e),ir.isWorker!==!0&&(ir.addEventListener("requestReadLock",t=>{Br[t.data.name]!=null&&Br[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ir.addEventListener("requestWriteLock",async t=>{Br[t.data.name]!=null&&Br[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Br[e.name]==null&&(Br[e.name]=z0(e.name,e)),Br[e.name]}var _e={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var yn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Me((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=>Ue(i,o.codec()),o.decode=i=>Oe(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Me((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),Ks.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=Ks.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ue(i,o.codec()),o.decode=i=>Oe(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Me((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Vs.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(Vs.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=>Ue(o,r.codec()),r.decode=o=>Oe(o,r.codec())})(yn||(yn={}));var Vs;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(Vs||(Vs={}));var Ks;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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=>Ue(t,r.codec()),r.decode=t=>Oe(t,r.codec())})(Ks||(Ks={}));function wn(r,e){let t=yn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=jf({...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 Ut="/",Rh=new TextEncoder().encode(Ut),Hs=Rh[0],Tr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==Hs)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}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=Rh),this._buf[0]!==Hs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Hs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hs;)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(Ut).slice(1)}type(){return j0(this.baseNamespace())}name(){return W0(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?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(),...X0(e.map(t=>t.namespaces()))])}};function j0(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function W0(r){let e=r.split(":");return e[e.length-1]}function X0(r){return[].concat(...r)}var Uc="/peers/";function bn(r){if(!bo(r)||r.type==null)throw new w("Invalid PeerId",_e.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Tr(`${Uc}${e}`)}async function _h(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)),!or(o.multiaddr))throw new w("Multiaddr was invalid",_e.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 qs(r,e,t,n){if(e==null)throw new w("Invalid PeerData",_e.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ne(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",_e.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new w("peer id did not match existing peer id",_e.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=$s(l,{validate:Sh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=$s(l,{validate:Ih,map:Bh})}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[h,g]of l)g==null?a.delete(h):a.set(h,g);a=$s([...a.entries()],{validate:Sh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[g,d]of l)d==null?h.delete(g):h.set(g,d);c=$s([...h.entries()],{validate:Ih,map:Bh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await _h(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,h)=>l.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function $s(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 Sh(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",_e.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",_e.ERR_INVALID_PARAMETERS)}function Ih(r,e){if(typeof r!="string")throw new w("Tag name must be a string",_e.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",_e.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",_e.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",_e.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",_e.ERR_INVALID_PARAMETERS)}}function Bh(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 Gs(r,e,t){let n=r.toString().split("/")[2],o=$e.decode(n),s=an(o),i=t.get(s);if(i!=null)return i;let a=wn(s,e);return t.set(s,a),a}function Z0(r,e){return r==null?{}:{prefix:Uc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Gs(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Gs(n.key,n.value,e),Gs(o.key,o.value,e)))}}var zs=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Oc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(bn(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",_e.ERR_INVALID_PARAMETERS);await this.datastore.delete(bn(e))}async load(e){let t=await this.datastore.get(bn(e));return wn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await qs(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 qs(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 qs(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Ye;for await(let{key:n,value:o}of this.datastore.query(Z0(e??{},t))){let s=Gs(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(bn(e)),n=wn(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=yn.encode(t);return n!=null&&ne(s,n)?{peer:wn(e,s),previous:o,updated:!1}:(await this.datastore.put(bn(e),s),{peer:wn(e,s),previous:o,updated:!0})}};var Ys=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 zs(e,t)}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 oo(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 un.openAndCertify(e,Ir.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=Ir.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 un.createFromProtobuf(s.peerRecordEnvelope),a=Ir.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 J0(r){return r[Symbol.asyncIterator]!=null}function Q0(r){if(J0(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Mc=Q0;function ey(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 Th=ey;function ty(r){return r[Symbol.asyncIterator]!=null}function ry(r,e){if(ty(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Th(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let i=e;return function*(){s===!0&&(yield n);for(let a of t)i(a)&&(yield a)}()}var Cr=ry;function ny(r){return r[Symbol.asyncIterator]!=null}function oy(r,e){return ny(r)?async function*(){yield*(await oo(r)).sort(e)}():function*(){yield*oo(r).sort(e)}()}var Fc=oy;function sy(r){return r[Symbol.asyncIterator]!=null}function iy(r,e){return sy(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 Vc=iy;var js=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 Mc(this.putMany(e,n)),e=[],await Mc(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=Cr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Cr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Fc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Cr(n,()=>o++>=s)}return e.limit!=null&&(n=Vc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Cr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Cr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Fc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Cr(n,()=>s++>=o)}return e.limit!=null&&(n=Vc(n,e.limit)),n}};var Lh=xt(Kc(),1);function kh(r){return r=r??new Error("Not Found"),(0,Lh.default)(r,"ERR_NOT_FOUND")}var Ws=class extends js{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 kh();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 Tr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Tr(e)}};function Dh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var ly=r=>r;function Hc(r,e){let t=r.getPeerId();return t!=null&&me(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Xs=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??ly,this._updatePeerStoreAddresses=Dh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([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=Hc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Hc(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=Hc(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 $c=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=Ls())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>kl(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")}},uy=["metrics","connectionProtector"],fy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ph(r={}){let e=new $c(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!fy.includes(o)){let i=e.components[o];if(i==null&&!uy.includes(o))throw new w(`${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}})}var Uh=xt(Oh(),1),hy=["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"],dy=hy.map(r=>new Uh.Netmask(r));function py(r){for(let e of dy)if(e.contains(r))return!0;return!1}function my(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 Zs(r){return hn(r)?py(r):dn(r)?my(r):void 0}function Mh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Zs(`${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 gy=r=>r.toString().split("/").slice(1),uo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),ae=r=>({match:e=>uo(t=>t===r).match(e),pattern:r}),ei=()=>({match:r=>uo(e=>typeof e=="string").match(r),pattern:"{string}"}),Fh=()=>({match:r=>uo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Qe=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ee.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Js=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{sa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),wt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),bt=(...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(", ")})`}),ce=(...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 ye(...r){function e(o){let s=gy(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 Gc=ce(ae("dns4"),ei()),zc=ce(ae("dns6"),ei()),Yc=ce(ae("dnsaddr"),ei()),Vh=ce(ae("dns"),ei()),vR=ye(Gc),AR=ye(zc),RR=ye(Yc),_R=ye(bt(Vh,Yc,Gc,zc)),Kh=ce(ae("ip4"),uo(hn)),Hh=ce(ae("ip6"),uo(dn)),$h=bt(Kh,Hh),fo=bt($h,Vh,Gc,zc,Yc),SR=ye(fo),IR=ye(Kh),BR=ye(Hh),TR=ye($h),ti=ce(fo,ae("tcp"),Fh()),ho=ce(fo,ae("udp"),Fh()),yy=bt(ti,ho),CR=ye(ti),NR=ye(ho),jc=ce(ho,ae("quic")),ri=ce(ho,ae("quic-v1")),wy=bt(jc,ri),LR=ye(jc),kR=ye(ri),qc=bt(fo,ti,ho,jc,ri),qh=bt(ce(qc,ae("ws"),wt(Qe()))),DR=ye(qh),Gh=bt(ce(qc,ae("wss"),wt(Qe())),ce(qc,ae("tls"),ae("ws"),wt(Qe()))),PR=ye(Gh),zh=ce(yy,ae("webrtc-direct"),Js(),wt(Js()),wt(Qe())),OR=ye(zh),Yh=ce(ri,ae("webtransport"),Js(),Js(),wt(Qe())),UR=ye(Yh),Qs=bt(qh,Gh,ce(ti,wt(Qe())),ce(wy,wt(Qe())),ce(fo,wt(Qe())),zh,Yh,Qe()),MR=ye(Qs),by=ce(Qs,ae("p2p-circuit"),Qe()),Wc=ye(by),Ey=bt(ce(Qs,ae("p2p-circuit"),ae("webrtc"),Qe()),ce(Qs,ae("webrtc"),wt(Qe())),ae("webrtc")),FR=ye(Ey);function Xc(r){try{let{address:e}=r.nodeAddress();return!!Zs(e)}catch{return!0}}function xy(r,e){let t=Xc(r.multiaddr),n=Xc(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Ay(r,e){let t=Wc.exactMatch(r.multiaddr),n=Wc.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function En(r,e){let t=xy(r,e);if(t!==0)return t;let n=Ay(r,e);return n!==0?n:vy(r,e)}var Jc=xt(sc(),1),Qc=xt(Xh(),1);function ni(r,e,t){return`${r}?name=${e}&type=${t}`}async function Zh(r,e){return await(await fetch(r,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function Nr(r,e){return`${e}_${r}`}var Zc=Object.assign((0,Jc.default)("dns-over-http-resolver"),{error:(0,Jc.default)("dns-over-http-resolver:error")}),el=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new Qc.default({max:e?.maxCache??100}),this._TXTcache=new Qc.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Zh,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),o=e[t];e[t]=e[n],e[n]=o}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(Nr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ni(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Nr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),Zc.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(Nr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ni(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Nr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),Zc.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(Nr(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ni(s,e,t),i.signal),c=a.Answer.map(f=>[f.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(f=>f.TTL));return this._TXTcache.set(Nr(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),Zc.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Jh=el;var Qh=Jh;var{code:By}=W("dnsaddr");async function xn(r,e={}){let t=new Qh;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,o]=r.stringTuples().find(([a])=>a===By)??[];if(o==null)throw new Error("No hostname found in multiaddr");let i=(await t.resolveTxt(`_dnsaddr.${o}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(i=i.filter(a=>a.includes(n))),i}var cd=xt(ad(),1),ii=cd.default;var Mt;(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"})(Mt||(Mt={}));var B;(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"})(B||(B={}));var Dy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:xn},addressSorter:En},transportManager:{faultTolerance:Ft.FATAL_ALL}};async function ld(r){let e=ii(Dy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(Mt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await cn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new w("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var ud=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Py=new WeakMap;function Oy({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(ud());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(ud())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((h,g)=>{i=()=>{f(),h(n)},a=g,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Py.set(l,()=>{c(s),s=null,i()}),l}}var Uy=Oy(),fd=Uy;var ai=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 rl}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 w("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)}},rl=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 ci(r){if(bo(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:me(t),r.forEach(n=>{if(!or(n))throw new w("Invalid Multiaddr",B.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}else{let s=me(o);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function he(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var li=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Rn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new li(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 li(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 nl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ui(r={}){return My(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 My(r,e){e=e??{};let t=e.onEnd,n=new Rn,o,s,i,a=he(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=x=>{s=null,n.push(x);try{m(r(n))}catch(b){y(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=he()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Rn,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),g=()=>(n=new Rn,h(),{done:!0}),d=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let x,b;y!=null&&(x=new Promise((A,v)=>{b=()=>{v(new nl)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},o}var ol=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 fi(r,e,t,n){let o=new ol(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{let a=u=>{n?.filter?.(u)!==!1&&(r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(u))},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var hi=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 _n(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new hi(t?.errorMessage,t?.errorCode));let n,o=new hi(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 di=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=he(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Vt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pi=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=Fy(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,We(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 Vt)}async join(e={}){let t=new di(new Error("where").stack,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 _n(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.signal?.removeEventListener("abort",this.onAbort)})}};function Vy(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 Sn=class extends ur{concurrency;queue;pending;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.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){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=Vy(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new pi(e,t,t?.priority),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),s)).catch(s=>{throw this.safeDispatchEvent("error",{detail:s}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Vt)}),this.clear()}async onEmpty(e){this.size!==0&&await fi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await fi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await fi(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=ui({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 w("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 mi=class extends Sn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gi="last-dial-failure";var yi=5,wi=100,bi=50,hd=1e3*60*7;var Lr={minConnections:yi,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:hd,autoDialDiscoveredPeersDebounce:10},Ei=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??Lr.minConnections,this.autoDialPriority=t.autoDialPriority??Lr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Lr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Lr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Lr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Lr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new mi({concurrency:t.autoDialConcurrency??Lr.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 ct(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 Ye;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,h=i.get(f.id)??0;return l>h?-1:l<h?1:0}).filter(u=>{let f=u.metadata.get(gi);if(f==null)return!0;let l=parseInt(V(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var dd={maxConnections:wi,allow:[]},xi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??dd.maxConnections,this.allow=t.allow??dd.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,n=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let o=new Ye;for(let a of e){let c=a.remotePeer;if(!o.has(c)){o.set(c,0);try{let u=await this.peerStore.get(c);o.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 s=e.sort((a,c)=>{let u=o.get(a.remotePeer)??0,f=o.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let l=a.timeline.open,h=c.timeline.open;return l<h?1:l>h?-1:0}),i=[];for(let a of s)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===n)break;await Promise.all(i.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:i})}};function pd(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 cl(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await $y(r,e),i=(await Promise.all(n.map(async a=>cl(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",r,i.map(a=>a.toString())),i}async function $y(r,e){try{return r=se(r.toString()),await r.resolve(e)}catch(t){return e.log.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}var vi={addressSorter:En,maxParallelDials:bi,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:xn}},Ai=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??vi.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??vi.maxPeerAddrsToDial,this.dialTimeout=t.dialTimeout??vi.dialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,We(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Ms.set(n,o);this.queue=new Sn({concurrency:t.maxParallelDials??vi.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}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=ci(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)}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 h of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new w("Peer had more than maxPeerAddrsToDial",B.ERR_TOO_MANY_ADDRESSES);f++;try{let g=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),g}catch(g){if(this.log.error("dial failed to %a",h.multiaddr,g),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[gi]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new w(g.message,xo);l.push(g)}}throw l.length===1?l[0]:new Eo(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=pd([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return We(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 w("Tried to dial self",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",B.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:h})=>h.toString()))}catch(l){if(l.code!==B.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:h})=>h.toString())),o.push(...l.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(l){l.code!==B.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 h=await cl(l.multiaddr,{...n,log:this.log});return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(g=>({multiaddr:g,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h)}let i=s.filter(l=>{if(this.components.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let h=l.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let l of i){let h=l.multiaddr.toString(),g=a.get(h);if(g!=null){g.isCertified=g.isCertified||l.isCertified||!1;continue}a.set(h,l)}let c=[...a.values()];if(c.length===0)throw new w("The dial request has no valid addresses",B.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 w("The connection gater denied all addresses in the dial request",B.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}};var zy=50,kr={minConnections:yi,maxConnections:wi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ri=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??kr.maxConnections;let n=t.minConnections??kr.minConnections;if(this.maxConnections<n)throw new w("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Ye,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??kr.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new ai({points:t.inboundConnectionThreshold??kr.inboundConnectionThreshold,duration:1}),this.autoDial=new Ei({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??kr.autoDialConcurrency,autoDialPriority:t.autoDialPriority??kr.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??kr.autoDialMaxQueueLength}),this.connectionPruner=new xi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ai(e,{addressSorter:t.addressSorter??En,maxParallelDials:t.maxParallelDials??bi,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:xn},connections:this.connections})}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(Ll)]});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 w("Not started",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=ci(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??zy}),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))}))}};function Yy(r){return r[Symbol.asyncIterator]!=null}function jy(...r){let e=[];for(let t of r)Yy(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=ui({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 po=jy;var _i=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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 w("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ct;for await(let s of po(...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 w("No content routers available",B.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 w(Mt.NOT_STARTED_YET,B.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 w(Mt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Si=globalThis.CustomEvent??Event;async function*fl(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=he(),a=he(),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=he(),await i.promise),f)break;let p={done:!1};s.push(p),d().then(m=>{p.done=!0,p.ok=!0,p.value=m,o.dispatchEvent(new Si("task-complete"))},m=>{p.done=!0,p.err=m,o.dispatchEvent(new Si("task-complete"))})}c=!0,o.dispatchEvent(new Si("task-complete"))}catch(d){u=d,o.dispatchEvent(new Si("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*h(){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*g(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let p=s[d];if(s.splice(d,1),d--,p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}for(;;){if(l()||(a=he(),await a.promise),u!=null)throw u;if(n?yield*h():yield*g(),c&&s.length===0)break}}var Ii=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??[]}async findPeer(e,t){if(this.routers.length===0)throw new w("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new w("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=po(...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 w(Mt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new w("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ct;for await(let s of fl(async function*(){let i=po(...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)&&(o.add(s.id),yield s))}};var hl=32,dl=64,Bi=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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new w(`No handler registered for protocol ${e}`,B.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 w(`Handler already registered for protocol ${e}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=ii.bind({ignoreUndefined:!0})({maxInboundStreams:hl,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 w("invalid topology",B.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.onDisconnect?.(t)}}).catch(n=>{n.code!==B.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.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.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 md(r){let{name:e,metrics:t}=r,n;return t!=null?n=new pl({name:e,metrics:t}):n=new Map,n}var Ti=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=md({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new w("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new w(`There is already a transport with the tag ${t}`,B.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.transportForMultiaddr(e);if(n==null)throw new w(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.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()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new w("Not started",B.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.filter(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 h=l.findIndex(g=>g===f);l.splice(h,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!==Ft.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ft.FATAL_ALL)throw new w(n,B.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 Se="/multistream/1.0.0";var ml=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=he(),this.haveNext=he()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=he(),e}async throw(e){return this.ended=!0,e!=null&&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");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=he(),await _n(this.needNext.promise,t?.signal,t)}};function gd(){return new ml}var Ci=class extends Error{code;constructor(e,t){super(e),this.code=t}},gl=class extends Ci{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function yd(r,e){let t=gd();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 ge;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new gl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:h}=await Promise.race([n.next(),u]);return l===!0?new ge:h}for(;o.byteLength<i;){let{value:l,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new Ci("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 Ni=class extends Error{code;constructor(e,t){super(e),this.code=t}};function mo(r,e={}){let t=yd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??ke;return{read:async i=>{let a=-1,c=new ge;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 Ni("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ni("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new ge(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ge(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Wy=D(`
8
+ `);async function Dr(r,e,t){await r.write(e,t)}async function wd(r,e,t){await r.writeV(e,t)}async function Xy(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Wy[0])throw e.log.error("Invalid mss message - missing newline",t),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function cr(r,e){let t=await Xy(r,e);return V(t.subarray())}async function go(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Zy(r,e[0],t);let n=mo(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"]',Se,o);let s=D(`${Se}
20
9
  `),i=D(`${o}
21
- `);await kd(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await fr(n,t);if(t.log.trace('select: read "%s"',a),a===Se&&(t.log.trace("select: reading protocol response"),a=await fr(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,D(`${c}
22
- `),t),t.log.trace("select: reading protocol response");let u=await fr(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 ww(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=de(),c=!1,u=!1,f=de(),l=!1,p=!1,h=de(),d=wo({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async w=>{let{sink:b}=d.unwrap();await b(async function*(){let A=!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',Se,e,v.byteLength);let R=`${e}
23
- `;yield new Ee(Uint8Array.from([19]),D(`${Se}
24
- `),He(R.length),D(R),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Se,e,v.byteLength),c=!0,u=!1,f.resolve(),g().catch(T=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,T)})}A=!0}A||await g()}())};async function g(){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 m()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function m(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Se,e),await d.writeV([D(`${Se}
10
+ `);await wd(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await cr(n,t);if(t.log.trace('select: read "%s"',a),a===Se&&(t.log.trace("select: reading protocol response"),a=await cr(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 Dr(n,D(`${c}
11
+ `),t),t.log.trace("select: reading protocol response");let u=await cr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Zy(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=he(),c=!1,u=!1,f=he(),l=!1,h=!1,g=he(),d=mo({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async x=>{let{sink:b}=d.unwrap();await b(async function*(){let A=!1;for await(let v of x){if(u&&await f.promise,c)yield v;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Se,e,v.byteLength);let S=`${e}
12
+ `;yield new ge(Uint8Array.from([19]),D(`${Se}
13
+ `),ke(S.length),D(S),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Se,e,v.byteLength),c=!0,u=!1,f.resolve(),p().catch(C=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,C)})}A=!0}A||await p()}())};async function p(){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 m()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function m(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Se,e),await d.writeV([D(`${Se}
25
14
  `),D(`${e}
26
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Se,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(p){await h.promise;return}p=!0;try{t.log.trace("optimistic: reading multistream select header");let w=await fr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===Se&&(w=await fr(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 g(),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 g().catch(A=>{t.log.error("could not negotiate protocol before close read",A)}),await w(b)}}if(r.closeWrite!=null){let w=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await g().catch(A=>{t.log.error("could not negotiate protocol before close write",A)}),await w(b)}}if(r.close!=null){let w=r.close.bind(r);r.close=async b=>{let A=[];u&&A.push(f.promise),p&&A.push(h.promise),A.length>0?await Bn(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}async function Eo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=wo(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await fr(n,t);if(t.log.trace('handle: read "%s"',o),o===Se){t.log.trace('handle: respond with "%s" for "%s"',Se,o),await Fr(n,D(`${Se}
27
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Se,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Fr(n,D(`${o}
28
- `),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=>Ur.single(D(`${i}
15
+ `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Se,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(h){await g.promise;return}h=!0;try{t.log.trace("optimistic: reading multistream select header");let x=await cr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',x),x===Se&&(x=await cr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',x,e),x!==e)throw new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,h=!1,g.resolve()}}if(r.source=async function*(){await p(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*d.unwrap().source}(),r.closeRead!=null){let x=r.closeRead.bind(r);r.closeRead=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close read",A)}),await x(b)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close write",A)}),await x(b)}}if(r.close!=null){let x=r.close.bind(r);r.close=async b=>{let A=[];u&&A.push(f.promise),h&&A.push(g.promise),A.length>0?await _n(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await x(b)}}return{stream:r,protocol:e}}function Li(r){return r[Symbol.asyncIterator]!=null}var ki=r=>{let e=Le(r),t=Be(e);return ke(r,t),ki.bytes=e,t};ki.bytes=0;function Di(r,e){e=e??{};let t=e.lengthEncoder??ki;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Li(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Di.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ki;return new ge(t(r.byteLength),r)};var In=xt(Kc(),1);var Jy=8,Qy=1024*1024*4,Pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Pr||(Pr={}));var bl=r=>{let e=lt(r);return bl.bytes=Le(e),e};bl.bytes=0;function wl(r,e){let t=new ge,n=Pr.LENGTH,o=-1,s=e?.lengthDecoder??bl,i=e?.maxLengthLength??Jy,a=e?.maxDataLength??Qy;function*c(){for(;t.byteLength>0;){if(n===Pr.LENGTH)try{if(o=s(t),o<0)throw(0,In.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,In.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=Pr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,In.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Pr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Pr.LENGTH}}}return Li(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,In.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,In.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}wl.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 wl(n,{...e??{},onLength:s=>{t=s}})};async function yo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=mo(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await cr(n,t);if(t.log.trace('handle: read "%s"',o),o===Se){t.log.trace('handle: respond with "%s" for "%s"',Se,o),await Dr(n,D(`${Se}
16
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',Se,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Dr(n,D(`${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 ge(...e.map(i=>Di.single(D(`${i}
29
18
  `))),D(`
30
- `));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,D(`na
31
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var Ew=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";[Ul]=!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(Ew);Xe(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 Dd(r){return new _l(r)}var xw=3e4;function vw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return wl}function Aw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??bl}function Pd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Vi=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??3e4,this.events=e.events}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}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",Ro))};u.addEventListener("abort",f,{once:!0}),Xe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",B.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",B.ERR_INVALID_MULTIADDR);let h=ge(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=ge(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",B.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 g=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await Eo(d,g,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let w=vw(y,this.components.registrar);if(Pd(y,"inbound",l)===w){let A=new E(`Too many inbound protocol streams for protocol "${y}" - limit ${w}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=y,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:y})}).catch(async g=>{l.log.error("error handling incoming stream id %s",d.id,g.message,g.code,g.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,g={})=>{if(u==null)throw new E("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(g.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(xw);Xe(1/0,v),g={...g,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:y,protocol:w}=await bo(m,d,{...g,log:m.log,yieldBytes:!0});m.log("selected protocol %s",w);let b=Aw(w,this.components.registrar,g);if(Pd(w,"outbound",l)>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - limit ${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[w]}),m.source=y.source,m.sink=y.sink,m.protocol=w,y.closeWrite!=null&&(m.closeWrite=y.closeWrite),y.closeRead!=null&&(m.closeRead=y.closeRead),y.close!=null&&(m.close=y.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw l.log.error("could not create new stream for protocols %s",d,y),m.timeline.close==null&&m.abort(y),y.code!=null?y:new E(String(y),B.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(g){l.log.error("error closing connection after timeline close",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(g=>{l.log.error("error thrown while dispatching connection:close event",g)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Dd({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 Eo(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 to %p failed",n),new E(n.message,B.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 bo(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 %p",t),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new E(o.message,B.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 bo(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),B.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 Eo(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),B.ERR_MUXER_UNAVAILABLE)}}};var Od="1.2.0",Ud="libp2p";var Sl=class extends dr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new dr,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new ji(a.type,{detail:a.detail}));return c||u},Xe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ps(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Kh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Ud,version:Od},logger:this.logger,events:t,datastore:e.datastore??new Qs,connectionGater:Zh(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Zs(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 Vi(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 Pi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ti(this.components,e.connectionManager)),this.configureComponent("registrar",new Di(this.components)),this.configureComponent("addressManager",new ei(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 Li(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 Ni(this.components,{routers:i})),(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[$i]!=null&&(this.log("registering service %s for content routing",a),i.push(u[$i])),u[zi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[zi])),u[Hi]!=null&&(this.log("registering service %s for peer discovery",a),u[Hi].addEventListener?.("peer",f=>{this.#e(f)}))}}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 ut;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",B.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",B.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={}){ir(e)&&(e=ge(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!==B.ERR_NOT_FOUND)throw s}let n=Re([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return ro(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)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Md(r={}){let e=r.peerId??=await th();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await no(e.privateKey),new Sl(await vd(r))}async function Iw(r={}){let e=await Md(r);return r.start!==!1&&await e.start(),e}return Jd(_w);})();
19
+ `));t.log.trace('handle: respond with "%s" for %s',e,o),await Dr(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 Dr(n,D(`na
20
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var tw=500,El=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";[Nl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new w("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new w("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(tw);We(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 Ed(r){return new El(r)}var rw=3e4;function nw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return hl}function ow(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??dl}function xd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Pi=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??3e4,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new w(`The multiaddr connection is blocked by gater.${n}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new w("inbound upgrade timeout",xo))};u.addEventListener("abort",f,{once:!0}),We(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",B.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),l=await h.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let h={...l,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new w("inbound connection that skipped encryption must have a peer id",B.ERR_INVALID_MULTIADDR);let g=me(h);c="native",s=g}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...l,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}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=me(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 w("Encryption was skipped but no peer id was passed",B.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 p=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await yo(d,p,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let x=nw(y,this.components.registrar);if(xd(y,"inbound",l)===x){let A=new w(`Too many inbound protocol streams for protocol "${y}" - limit ${x}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=y,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:y})}).catch(async p=>{l.log.error("error handling incoming stream id %s",d.id,p.message,p.code,p.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,p={})=>{if(u==null)throw new w("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(p.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(rw);We(1/0,v),p={...p,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:y,protocol:x}=await go(m,d,{...p,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=ow(x,this.components.registrar,p);if(xd(x,"outbound",l)>=b){let v=new w(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[x]}),m.source=y.source,m.sink=y.sink,m.protocol=x,y.closeWrite!=null&&(m.closeWrite=y.closeWrite),y.closeRead!=null&&(m.closeRead=y.closeRead),y.close!=null&&(m.close=y.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw l.log.error("could not create new stream for protocols %s",d,y),m.timeline.close==null&&m.abort(y),y.code!=null?y:new w(String(y),B.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 h=o.timeline;o.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(p){l.log.error("error closing connection after timeline close",p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{l.log.error("error thrown while dispatching connection:close event",p)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let g=()=>{throw new w("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Ed({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??g,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 w("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 yo(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 to %p failed",n),new w(n.message,B.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 go(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 %p",t),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new w(o.message,B.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 go(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 w(String(o),B.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 yo(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 w(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var vd="1.2.1",Ad="libp2p";var xl=class extends ur{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new ur,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Hi(a.type,{detail:a.detail}));return c||u},We(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ls(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Ph({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Ad,version:vd},logger:this.logger,events:t,datastore:e.datastore??new Ws,connectionGater:Mh(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Ys(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 Pi(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 Ti(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ri(this.components,e.connectionManager)),this.configureComponent("registrar",new Bi(this.components)),this.configureComponent("addressManager",new Xs(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 Ii(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new _i(this.components,{routers:i})),(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[Ui]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ui])),u[Vi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Vi])),u[Mi]!=null&&(this.log("registering service %s for peer discovery",a),u[Mi].addEventListener?.("peer",f=>{this.#e(f)}))}}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 ct;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 w("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new w("no protocols were provided to open a stream",B.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={}){or(e)&&(e=me(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!==B.ERR_NOT_FOUND)throw s}let n=Ae([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return Qn(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)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Rd(r={}){let e=r.peerId??=await Wf();if(e.privateKey==null)throw new w("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await eo(e.privateKey),new xl(await ld(r))}async function iw(r={}){let e=await Rd(r);return r.start!==!1&&await e.start(),e}return Md(aw);})();
32
21
  /*! Bundled license information:
33
22
 
34
23
  pvtsutils/build/index.js: