libp2p 1.1.2 → 1.2.0-08f6f607d

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,34 @@
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 Zd=Object.create;var bo=Object.defineProperty;var Jd=Object.getOwnPropertyDescriptor;var Qd=Object.getOwnPropertyNames;var ep=Object.getPrototypeOf,tp=Object.prototype.hasOwnProperty;var rt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),be=(r,e)=>{for(var t in e)bo(r,t,{get:e[t],enumerable:!0})},Ul=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qd(e))!tp.call(r,o)&&o!==t&&bo(r,o,{get:()=>e[o],enumerable:!(n=Jd(e,o))||n.enumerable});return r};var dt=(r,e,t)=>(t=r!=null?Zd(ep(r)):{},Ul(e||!r||!r.__esModule?bo(t,"default",{value:r,enumerable:!0}):t,r)),rp=r=>Ul(bo({},"__esModule",{value:!0}),r);var Hu=rt(an=>{"use strict";var Tg="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Tg}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}},Ya="string",Ng=/^[0-9a-f]+$/i,kg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Lg=/^[a-zA-Z0-9-_]+$/,$o=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}},Ho=class r{static isHex(e){return typeof e===Ya&&Ng.test(e)}static isBase64(e){return typeof e===Ya&&kg.test(e)}static isBase64Url(e){return typeof e===Ya&&Lg.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 $o.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 $o.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,"")||""}};Ho.DEFAULT_UTF8_ENCODING="utf8";function Dg(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 Pg(...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 Og(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}an.BufferSourceConverter=kt;an.Convert=Ho;an.assign=Dg;an.combine=Pg;an.isEqual=Og});var fc=rt((V1,Qf)=>{var mn=1e3,gn=mn*60,yn=gn*60,_r=yn*24,g0=_r*7,y0=_r*365.25;Qf.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return w0(r);if(t==="number"&&isFinite(r))return e.long?E0(r):b0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function w0(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*y0;case"weeks":case"week":case"w":return t*g0;case"days":case"day":case"d":return t*_r;case"hours":case"hour":case"hrs":case"hr":case"h":return t*yn;case"minutes":case"minute":case"mins":case"min":case"m":return t*gn;case"seconds":case"second":case"secs":case"sec":case"s":return t*mn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function b0(r){var e=Math.abs(r);return e>=_r?Math.round(r/_r)+"d":e>=yn?Math.round(r/yn)+"h":e>=gn?Math.round(r/gn)+"m":e>=mn?Math.round(r/mn)+"s":r+"ms"}function E0(r){var e=Math.abs(r);return e>=_r?Ns(r,e,_r,"day"):e>=yn?Ns(r,e,yn,"hour"):e>=gn?Ns(r,e,gn,"minute"):e>=mn?Ns(r,e,mn,"second"):r+" ms"}function Ns(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var th=rt((K1,eh)=>{function x0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=fc(),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}eh.exports=x0});var hc=rt((je,ks)=>{je.formatArgs=A0;je.save=R0;je.load=I0;je.useColors=v0;je.storage=_0();je.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();je.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function v0(){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 A0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ks.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}je.log=console.debug||console.log||(()=>{});function R0(r){try{r?je.storage.setItem("debug",r):je.storage.removeItem("debug")}catch{}}function I0(){let r;try{r=je.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function _0(){try{return localStorage}catch{}}ks.exports=th()(je);var{formatters:S0}=ks.exports;S0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Sh=rt((MR,kc)=>{"use strict";var ly=Object.prototype.hasOwnProperty,Ve="~";function io(){}Object.create&&(io.prototype=Object.create(null),new io().__proto__||(Ve=!1));function uy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function _h(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new uy(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 $s(r,e){--r._eventsCount===0?r._events=new io:delete r._events[e]}function Ue(){this._events=new io,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ly.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.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};Ue.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=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};Ue.prototype.on=function(e,t,n){return _h(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return _h(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return $s(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&$s(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:$s(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&$s(this,t)):(this._events=new io,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=Ve;Ue.EventEmitter=Ue;typeof kc<"u"&&(kc.exports=Ue)});var Wc=rt((r_,Kh)=>{"use strict";function Vh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Sy(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 Vh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Vh(new o,t)}}Kh.exports=Sy});var Gh=rt(uo=>{(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}(),uo.ip2long=i,uo.long2ip=a,uo.Netmask=r}).call(uo)});var Xh=rt((Wh,ti)=>{(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 ti<"u"&&ti.exports?ti.exports=p:r.ipaddr=p})(Wh)});var dd=rt((J_,hd)=>{"use strict";hd.exports=fd;var Yy=fc(),fr=fd.prototype,Wy=new Date%1e9;function Xy(){return(Math.random()*1e9>>>0)+Wy++}function fd(r){r=r||{},this.id=r.id||Xy(),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)}fr.has=function(r){return r in this._lookup};fr.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};fr.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};fr.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};fr.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};fr.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=Yy(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};fr.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};fr.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 wd=rt((sS,yd)=>{"use strict";yd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Rd=rt((vd,Ad)=>{"use strict";var li=wd(),{hasOwnProperty:Ed}=Object.prototype,{propertyIsEnumerable:Qy}=Object,Tn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),ew=vd,bd={concatArrays:!1,ignoreUndefined:!1},ui=r=>{let e=[];for(let t in r)Ed.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Qy.call(r,n)&&e.push(n)}return e};function Nn(r){return Array.isArray(r)?tw(r):li(r)?rw(r):r}function tw(r){let e=r.slice(0,0);return ui(r).forEach(t=>{Tn(e,t,Nn(r[t]))}),e}function rw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return ui(r).forEach(t=>{Tn(e,t,Nn(r[t]))}),e}var xd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Tn(r,o,ul(r[o],e[o],n)):Tn(r,o,Nn(e[o])))}),r),nw=(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++)Ed.call(s,a)&&(i.push(String(a)),s===r?Tn(n,o++,s[a]):Tn(n,o++,Nn(s[a])));n=xd(n,s,ui(s).filter(a=>!i.includes(a)),t)}),n};function ul(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?nw(r,e,t):!li(e)||!li(r)?Nn(e):xd(r,e,ui(e),t)}Ad.exports=function(...r){let e=ul(Nn(bd),this!==ew&&this||{},bd),t={_:{}};for(let n of r)if(n!==void 0){if(!li(n))throw new TypeError("`"+n+"` is not an Option Object");t=ul(t,{_:n},e)}return t._}});var Lw={};be(Lw,{createLibp2p:()=>kw});var Fl=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 Eo(r){return r!=null&&!!r[qi]}var zi=Symbol.for("@libp2p/peer-routing");var Vl="keep-alive";var Kl;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Kl||(Kl={}));var Hw=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??{}}},xo=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 vo="ERR_TIMEOUT";var pr=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 $l(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Ga={};be(Ga,{Ed25519PrivateKey:()=>Qt,Ed25519PublicKey:()=>on,generateKeyPair:()=>Rg,generateKeyPairFromSeed:()=>$u,unmarshalEd25519PrivateKey:()=>vg,unmarshalEd25519PublicKey:()=>Ag});var Ji={};be(Ji,{base58btc:()=>ee,base58flickr:()=>cp});var xb=new Uint8Array(0);function Hl(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 ql(r){return new TextEncoder().encode(r)}function zl(r){return new TextDecoder().decode(r)}function np(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 op=np,sp=op,jl=sp;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 Yl(this,e)}},Xi=class{decoders;constructor(e){this.decoders=e}or(e){return Yl(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 Yl(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 $r({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}=jl(t,r);return $r({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function ip(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ap(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 ne({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return $r({prefix:e,name:r,encode(o){return ap(o,n,t)},decode(o){return ip(o,n,t,r)}})}var ee=Ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cp=Ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};be(ea,{identity:()=>qt});var lp=Zl,Wl=128,up=127,fp=~up,hp=Math.pow(2,31);function Zl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hp;)e[t++]=r&255|Wl,r/=128;for(;r&fp;)e[t++]=r&255|Wl,r>>>=7;return e[t]=r|0,Zl.bytes=t-n+1,e}var dp=Qi,pp=128,Xl=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&Xl)<<o:(i&Xl)*Math.pow(2,o),o+=7}while(i>=pp);return Qi.bytes=s-n,t}var mp=Math.pow(2,7),gp=Math.pow(2,14),yp=Math.pow(2,21),wp=Math.pow(2,28),bp=Math.pow(2,35),Ep=Math.pow(2,42),xp=Math.pow(2,49),vp=Math.pow(2,56),Ap=Math.pow(2,63),Rp=function(r){return r<mp?1:r<gp?2:r<yp?3:r<wp?4:r<bp?5:r<Ep?6:r<xp?7:r<vp?8:r<Ap?9:10},Ip={encode:lp,decode:dp,encodingLength:Rp},_p=Ip,Mn=_p;function Un(r,e=0){return[Mn.decode(r,e),Mn.decode.bytes]}function Hr(r,e,t=0){return Mn.encode(r,e,t),e}function qr(r){return Mn.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=qr(r),o=n+qr(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new zr(r,t,e,s)}function mr(r){let e=Rt(r),[t,n]=Un(e),[o,s]=Un(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new zr(t,o,i,e)}function Jl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hl(r.bytes,t.bytes)}}var zr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Ql=0,Sp="identity",eu=Rt;function Bp(r){return pt(Ql,eu(r))}var qt={code:Ql,name:Sp,encode:eu,digest:Bp};var na={};be(na,{sha256:()=>Re,sha512:()=>Cp});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 ru(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=ra({name:"sha2-256",code:18,encode:ru("SHA-256")}),Cp=ra({name:"sha2-512",code:19,encode:ru("SHA-512")});function te(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function 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 Le(r=0){return globalThis.Buffer?.allocUnsafe!=null?zt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ge(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=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return zt(t)}var oa={};be(oa,{base10:()=>Tp});var Tp=Ht({prefix:"9",name:"base10",alphabet:"0123456789"});var sa={};be(sa,{base16:()=>Np,base16upper:()=>kp});var Np=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kp=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ia={};be(ia,{base2:()=>Lp});var Lp=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aa={};be(aa,{base256emoji:()=>Up});var nu=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}"),Dp=nu.reduce((r,e,t)=>(r[t]=e,r),[]),Pp=nu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Op(r){return r.reduce((e,t)=>(e+=Dp[t],e),"")}function Mp(r){let e=[];for(let t of r){let n=Pp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Up=$r({prefix:"\u{1F680}",name:"base256emoji",encode:Op,decode:Mp});var ca={};be(ca,{base32:()=>ze,base32hex:()=>$p,base32hexpad:()=>qp,base32hexpadupper:()=>zp,base32hexupper:()=>Hp,base32pad:()=>Vp,base32padupper:()=>Kp,base32upper:()=>Fp,base32z:()=>Gp});var ze=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fp=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Vp=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Kp=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$p=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hp=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qp=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zp=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gp=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var la={};be(la,{base36:()=>jp,base36upper:()=>Yp});var jp=Ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yp=Ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fa={};be(fa,{base64:()=>Gr,base64pad:()=>Wp,base64url:()=>ua,base64urlpad:()=>Xp});var Gr=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wp=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ua=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xp=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};be(ha,{base8:()=>Zp});var Zp=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var da={};be(da,{identity:()=>Jp});var Jp=$r({prefix:"\0",name:"identity",encode:r=>zl(r),decode:r=>ql(r)});var Wb=new TextEncoder,Xb=new TextDecoder;function ou(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return rm(t,pa(r),e??ee.encoder);default:return nm(t,pa(r),e??ze.encoder)}}var su=new WeakMap;function pa(r){let e=su.get(r);if(e==null){let t=new Map;return su.set(r,t),t}return e}var nt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==om)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&&Jl(e.multihash,n.multihash)}toString(e){return ou(this,e)}toJSON(){return{"/":ou(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??iu(n,o,s.bytes))}else if(t[sm]===!0){let{version:n,multihash:o,code:s}=t,i=mr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=iu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Rt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new zr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Un(e.subarray(t));return t+=p,l},o=n(),s=Fn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=tm(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 tm(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 ze.prefix:{let t=e??ze;return[ze.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function rm(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 nm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Fn=112,om=18;function iu(r,e,t){let n=qr(r),o=n+qr(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var sm=Symbol.for("@ipld/js-cid/CID");var Gt={...da,...ia,...ha,...oa,...sa,...ca,...la,...Ji,...fa,...aa},hE={...na,...ea};function cu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var au=cu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ma=cu("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),im={utf8:au,"utf-8":au,hex:Gt.base16,latin1:ma,ascii:ma,binary:ma,...Gt},Ro=im;function D(r,e="utf8"){let t=Ro[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 jr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function am(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function ga(r,...e){if(!am(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 Io(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");jr(r.outputLen),jr(r.blockLen)}function Yr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function lu(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 _o=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function uu(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var Xr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ot=(r,e)=>r<<32-e|r>>>e,cm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!cm)throw new Error("Non little-endian hardware is not supported");var lm=async()=>{};async function fu(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 lm(),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)),!uu(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(!uu(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 Wr=class{clone(){return this._cloneInto()}},um={}.toString;function hu(r,e){if(e!==void 0&&um.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Bo(r){let e=n=>r().update(jt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Zr(r=32){if(_o&&typeof _o.getRandomValues=="function")return _o.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function fm(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 Jr=class extends Wr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Xr(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=jt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Xr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),lu(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;fm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Xr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Co=BigInt(4294967295),wa=BigInt(32);function du(r,e=!1){return e?{h:Number(r&Co),l:Number(r>>wa&Co)}:{h:Number(r>>wa&Co)|0,l:Number(r&Co)|0}}function hm(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}=du(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var dm=(r,e)=>BigInt(r>>>0)<<wa|BigInt(e>>>0),pm=(r,e,t)=>r>>>t,mm=(r,e,t)=>r<<32-t|e>>>t,gm=(r,e,t)=>r>>>t|e<<32-t,ym=(r,e,t)=>r<<32-t|e>>>t,wm=(r,e,t)=>r<<64-t|e>>>t-32,bm=(r,e,t)=>r>>>t-32|e<<64-t,Em=(r,e)=>e,xm=(r,e)=>r,vm=(r,e,t)=>r<<t|e>>>32-t,Am=(r,e,t)=>e<<t|r>>>32-t,Rm=(r,e,t)=>e<<t-32|r>>>64-t,Im=(r,e,t)=>r<<t-32|e>>>64-t;function _m(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Sm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Bm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Cm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Tm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Nm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),km=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Lm={fromBig:du,split:hm,toBig:dm,shrSH:pm,shrSL:mm,rotrSH:gm,rotrSL:ym,rotrBH:wm,rotrBL:bm,rotr32H:Em,rotr32L:xm,rotlSH:vm,rotlSL:Am,rotlBH:Rm,rotlBL:Im,add:_m,add3L:Sm,add3H:Bm,add4L:Cm,add4H:Tm,add5H:km,add5L:Nm},O=Lm;var[Dm,Pm]=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 Jr{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),M=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),le=O.add4L(T,M,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,Pm[b],Wt[b]),q=O.add5H(N,y,A,R,Dm[b],Yt[b]),z=N|0,M=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,M,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 Qr=Bo(()=>new ba);var No={};be(No,{bitGet:()=>$m,bitLen:()=>Km,bitMask:()=>Vn,bitSet:()=>Hm,bytesToHex:()=>St,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>va,ensureBytes:()=>oe,equalBytes:()=>Fm,hexToBytes:()=>yr,hexToNumber:()=>xa,isBytes:()=>st,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>yu,numberToVarBytesBE:()=>Um,utf8ToBytes:()=>Vm,validateObject:()=>mt});var gu=BigInt(0),To=BigInt(1),Om=BigInt(2);function st(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var Mm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function St(r){if(!st(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=Mm[r[t]];return e}function yu(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 pu(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 yr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=pu(r.charCodeAt(s)),a=pu(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(!st(r))throw new Error("Uint8Array expected");return xa(St(Uint8Array.from(r).reverse()))}function Zt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Zt(r,e).reverse()}function Um(r){return yr(yu(r))}function oe(r,e,t){let n;if(typeof e=="string")try{n=yr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(st(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(!st(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 Fm(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 Km(r){let e;for(e=0;r>gu;r>>=To,e+=1);return e}function $m(r,e){return r>>BigInt(e)&To}var Hm=(r,e,t)=>r|(t?To:gu)<<BigInt(e),Vn=r=>(Om<<BigInt(r-1))-To,Ea=r=>new Uint8Array(r),mu=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(mu([0]),l),n=a(),l.length!==0&&(o=a(mu([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 qm={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"||st(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=qm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ye=BigInt(0),Z=BigInt(1),br=BigInt(2),zm=BigInt(3),Aa=BigInt(4),wu=BigInt(5),bu=BigInt(8),Gm=BigInt(9),jm=BigInt(16);function X(r,e){let t=r%e;return t>=ye?t:e+t}function Ym(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===Z)return ye;let n=Z;for(;e>ye;)e&Z&&(n=n*r%t),r=r*r%t,e>>=Z;return n}function J(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function ko(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=ye,s=Z,i=Z,a=ye;for(;t!==ye;){let u=n/t,f=n%t,l=o-i*u,p=s-a*u;n=t,t=f,o=i,s=a,i=l,a=p}if(n!==Z)throw new Error("invert: does not exist");return X(o,e)}function Wm(r){let e=(r-Z)/br,t,n,o;for(t=r-Z,n=0;t%br===ye;t/=br,n++);for(o=br;o<r&&Ym(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)/br;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 Xm(r){if(r%Aa===zm){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%bu===wu){let e=(r-wu)/bu;return function(n,o){let s=n.mul(o,br),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,br),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%jm,Wm(r)}var Eu=(r,e)=>(X(r,e)&Z)===Z,Zm=["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=Zm.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function Jm(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===Z)return e;let n=r.ONE,o=e;for(;t>ye;)t&Z&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Z;return n}function Qm(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 Lo(r,e,t=!1,n={}){if(r<=ye)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=Xm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Vn(o),ZERO:ye,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 ye<=c&&c<r},is0:c=>c===ye,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)=>Jm(a,c,u),div:(c,u)=>X(c*ko(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ko(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Qm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function xu(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 vu(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=vu(r);return e+Math.ceil(e/2)}function Au(r,e,t=!1){let n=r.length,o=vu(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?wr(a,o):Zt(a,o)}var tg=BigInt(0),Sa=BigInt(1);function Do(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>tg;)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 Kn(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 it=BigInt(0),Ge=BigInt(1),Po=BigInt(2),rg=BigInt(8),ng={zip215:!0};function og(r){let e=Kn(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Oo(r){let e=og(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Po<<BigInt(a*8)-Ge,f=t.create,l=e.uvRatio||((_,x)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(x))}}catch{return{isValid:!1,value:it}}}),p=e.adjustScalarBytes||(_=>_),h=e.domain||((_,x,B)=>{if(x.length||B)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&it<_,g=(_,x)=>d(_)&&d(x)&&_<x,m=_=>_===it||g(_,u);function y(_,x){if(g(_,x))return _;throw new Error(`Expected valid scalar < ${x}, got ${typeof _} ${_}`)}function w(_){return _===it?_:y(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(x,B,L,P){if(this.ex=x,this.ey=B,this.ez=L,this.et=P,!m(x))throw new Error("x required");if(!m(B))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:B,y:L}=x||{};if(!m(B)||!m(L))throw new Error("invalid affine point");return new v(B,L,Ge,f(B*L))}static normalizeZ(x){let B=t.invertBatch(x.map(L=>L.ez));return x.map((L,P)=>L.toAffine(B[P])).map(v.fromAffine)}_setWindowSize(x){this._WINDOW_SIZE=x,b.delete(this)}assertValidity(){let{a:x,d:B}=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),re=f(Y*x),ve=f(G*f(re+H)),Ae=f(ue+f(B*f(Y*H)));if(ve!==Ae)throw new Error("bad point: equation left != right (1)");let me=f(L*P),ke=f(F*K);if(me!==ke)throw new Error("bad point: equation left != right (2)")}equals(x){A(x);let{ex:B,ey:L,ez:P}=this,{ex:F,ey:K,ez:Y}=x,H=f(B*Y),G=f(F*P),ue=f(L*Y),re=f(K*P);return H===G&&ue===re}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:B,ey:L,ez:P}=this,F=f(B*B),K=f(L*L),Y=f(Po*f(P*P)),H=f(x*F),G=B+L,ue=f(f(G*G)-F-K),re=H+K,ve=re-Y,Ae=H-K,me=f(ue*ve),ke=f(re*Ae),At=f(ue*Ae),dr=f(ve*re);return new v(me,ke,dr,At)}add(x){A(x);let{a:B,d:L}=e,{ex:P,ey:F,ez:K,et:Y}=this,{ex:H,ey:G,ez:ue,et:re}=x;if(B===BigInt(-1)){let Nl=f((F-P)*(G+H)),kl=f((F+P)*(G-H)),Ki=f(kl-Nl);if(Ki===it)return this.double();let Ll=f(K*Po*re),Dl=f(Y*Po*ue),Pl=Dl+Ll,Ol=kl+Nl,Ml=Dl-Ll,jd=f(Pl*Ki),Yd=f(Ol*Ml),Wd=f(Pl*Ml),Xd=f(Ki*Ol);return new v(jd,Yd,Xd,Wd)}let ve=f(P*H),Ae=f(F*G),me=f(Y*L*re),ke=f(K*ue),At=f((P+F)*(H+G)-ve-Ae),dr=ke-me,On=ke+me,Tl=f(Ae-B*ve),Hd=f(At*dr),qd=f(On*Tl),zd=f(At*Tl),Gd=f(dr*On);return new v(Hd,qd,Gd,zd)}subtract(x){return this.add(x.negate())}wNAF(x){return N.wNAFCached(this,b,x,v.normalizeZ)}multiply(x){let{p:B,f:L}=this.wNAF(y(x,n));return v.normalizeZ([B,L])[0]}multiplyUnsafe(x){let B=w(x);return B===it?T:this.equals(T)||B===Ge?this:this.equals(R)?this.wNAF(B).p:N.unsafeLadder(this,B)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(x){let{ex:B,ey:L,ez:P}=this,F=this.is0();x==null&&(x=F?rg:t.inv(P));let K=f(B*x),Y=f(L*x),H=f(P*x);if(F)return{x:it,y:Ge};if(H!==Ge)throw new Error("invZ was invalid");return{x:K,y:Y}}clearCofactor(){let{h:x}=e;return x===Ge?this:this.multiplyUnsafe(x)}static fromHex(x,B=!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===it||(B?y(H,u):y(H,t.ORDER));let G=f(H*H),ue=f(G-Ge),re=f(L*G-P),{isValid:ve,value:Ae}=l(ue,re);if(!ve)throw new Error("Point.fromHex: invalid y coordinate");let me=(Ae&Ge)===Ge,ke=(Y&128)!==0;if(!B&&Ae===it&&ke)throw new Error("Point.fromHex: x=0 and x_0=1");return ke!==me&&(Ae=f(-Ae)),v.fromAffine({x:Ae,y:H})}static fromPrivateKey(x){return M(x).point}toRawBytes(){let{x,y:B}=this.toAffine(),L=wr(B,t.BYTES);return L[L.length-1]|=x&Ge?128:0,L}toHex(){return St(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ge,f(e.Gx*e.Gy)),v.ZERO=new v(it,Ge,Ge,it);let{BASE:R,ZERO:T}=v,N=Do(v,a*8);function q(_){return X(_,n)}function z(_){return q(Xt(_))}function M(_){let x=a;_=oe("private key",_,x);let B=oe("hashed private key",s(_),2*x),L=p(B.slice(0,x)),P=B.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 M(_).pointBytes}function ie(_=new Uint8Array,...x){let B=Ct(...x);return z(s(h(B,oe("context",_),!!o)))}function We(_,x,B={}){_=oe("message",_),o&&(_=o(_));let{prefix:L,scalar:P,pointBytes:F}=M(x),K=ie(B.context,L,_),Y=R.multiply(K).toRawBytes(),H=ie(B.context,Y,F,_),G=q(K+H*P);w(G);let ue=Ct(Y,wr(G,t.BYTES));return oe("result",ue,a*2)}let I=ng;function k(_,x,B,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(B,F),G=v.fromHex(_.slice(0,K),F),ue=R.multiplyUnsafe(Y)}catch{return!1}if(!F&&H.isSmallOrder())return!1;let re=ie(P,G.toRawBytes(),H.toRawBytes(),x);return G.add(H.multiplyUnsafe(re)).subtract(ue).clearCofactor().equals(v.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:le,sign:We,verify:k,ExtendedPoint:v,utils:{getExtendedPublicKey:M,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,x=v.BASE){return x._setWindowSize(_),x.multiply(BigInt(3)),x}}}}var Ca=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ru=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),jE=BigInt(0),sg=BigInt(1),Ba=BigInt(2),ig=BigInt(5),Iu=BigInt(10),ag=BigInt(20),cg=BigInt(40),_u=BigInt(80);function lg(r){let e=Ca,n=r*r%e*r%e,o=J(n,Ba,e)*n%e,s=J(o,sg,e)*r%e,i=J(s,ig,e)*s%e,a=J(i,Iu,e)*i%e,c=J(a,ag,e)*a%e,u=J(c,cg,e)*c%e,f=J(u,_u,e)*u%e,l=J(f,_u,e)*u%e,p=J(l,Iu,e)*i%e;return{pow_p_5_8:J(p,Ba,e)*r%e,b2:n}}function ug(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function fg(r,e){let t=Ca,n=X(e*e*e,t),o=X(n*n*e,t),s=lg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*Ru,t),f=a===r,l=a===X(-r,t),p=a===X(-r*Ru,t);return f&&(i=c),(l||p)&&(i=u),Eu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Tt=Lo(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:Qr,randomBytes:Zr,adjustScalarBytes:ug,uvRatio:fg},en=Oo(Ta);function Su(r,e,t){if(e.length>255)throw new Error("Context is too big");return So(ya("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var YE=Oo({...Ta,domain:Su}),WE=Oo({...Ta,domain:Su,prehash:Qr});var hg=(Tt.ORDER+BigInt(3))/BigInt(8),XE=Tt.pow(Ba,hg),ZE=Tt.sqrt(Tt.neg(Tt.ONE)),JE=(Tt.ORDER-BigInt(5))/BigInt(8),QE=BigInt(486662);var ex=xu(Tt,Tt.neg(BigInt(486664)));var tx=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),rx=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),nx=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),ox=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var sx=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var tn=32,Nt=64,Mo=32;function Bu(){let r=en.utils.randomPrivateKey(),e=en.getPublicKey(r);return{privateKey:ku(r,e),publicKey:e}}function Cu(r){if(r.length!==Mo)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=en.getPublicKey(e);return{privateKey:ku(e,t),publicKey:t}}function Tu(r,e){let t=r.subarray(0,Mo);return en.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Nu(r,e,t){return en.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function ku(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Mo;n++)t[n]=r[n],t[Mo+n]=e[n];return t}var Ie={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 ka(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=Ie.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 ge([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 rn(r,e){let n=await ka().encrypt(r,e);return Gr.encode(n)}var La=new Float32Array([-0]),Jt=new Uint8Array(La.buffer);function Du(r,e,t){La[0]=r,e[t]=Jt[0],e[t+1]=Jt[1],e[t+2]=Jt[2],e[t+3]=Jt[3]}function Pu(r,e){return Jt[0]=r[e],Jt[1]=r[e+1],Jt[2]=r[e+2],Jt[3]=r[e+3],La[0]}var Da=new Float64Array([-0]),De=new Uint8Array(Da.buffer);function Ou(r,e,t){Da[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function Mu(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],Da[0]}var pg=BigInt(Number.MAX_SAFE_INTEGER),mg=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 Er;if(e<pg&&e>mg)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>Uu&&(o=0n,++n>Uu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Er;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):Er}},Er=new Ke(0,0);Er.toBigInt=function(){return 0n};Er.zzEncode=Er.zzDecode=function(){return this};Er.length=function(){return 1};var Uu=4294967296n;function Fu(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 Vu(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 Pa(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 at(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 Oa=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,at(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 at(this,4);return Uo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return Uo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=Pu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Mu(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 at(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw at(this,e);this.pos+=e}else do if(this.pos>=this.len)throw at(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 at(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 at(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 at(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 Ma(r){return new Oa(r instanceof Uint8Array?r:r.subarray())}function _e(r,e){let t=Ma(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 Le(i);o+i>e&&(n=Le(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var xr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Fa(){}var Ka=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},gg=Ua();function yg(r){return globalThis.Buffer!=null?Le(r):gg(r)}var qn=class{len;head;tail;states;constructor(){this.len=0,this.head=new xr(Fa,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new xr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $a((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($n,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($n,t.length(),t)}uint64Number(e){let t=Ke.fromNumber(e);return this._push($n,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($n,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push($n,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Va,1,e?1:0)}fixed32(e){return this._push(Hn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(Hn,4,t.lo)._push(Hn,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(Hn,4,t.lo)._push(Hn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Du,4,e)}double(e){return this._push(Ou,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Va,1,0):this.uint32(t)._push(bg,t,e)}string(e){let t=Fu(e);return t!==0?this.uint32(t)._push(Pa,t,e):this._push(Va,1,0)}fork(){return this.states=new Ka(this),this.head=this.tail=new xr(Fa,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 xr(Fa,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=yg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Va(r,e,t){e[t]=r&255}function wg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var $a=class extends xr{next;constructor(e,t){super(wg,e,t),this.next=void 0}};function $n(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Hn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function bg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(qn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Eg,e,r),this},qn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xg,e,r),this});function Eg(r,e,t){e.set(r,t)}function xg(r,e,t){r.length<40?Pa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function Ha(){return new qn}function Se(r,e){let t=Ha();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var nn;(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"})(nn||(nn={}));function Fo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function qa(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 Fo("enum",nn.VARINT,t,n)}function Be(r,e){return Fo("message",nn.LENGTH_DELIMITED,r,e)}var Q;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Q||(Q={}));var za;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(za||(za={}));(function(r){r.codec=()=>qa(za)})(Q||(Q={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((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=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(gt||(gt={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((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=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(yt||(yt={}));var on=class{_key;constructor(e){this._key=sn(e,tn)}verify(e,t){return Nu(this._key,t,e)}marshal(){return this._key}get bytes(){return gt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},Qt=class{_key;_publicKey;constructor(e,t){this._key=sn(e,Nt),this._publicKey=sn(t,tn)}sign(e){return Tu(this._key,e)}get public(){return new on(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.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 rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function vg(r){if(r.length>Nt){r=sn(r,Nt+tn);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Qt(n,o)}r=sn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(tn);return new Qt(e,t)}function Ag(r){return r=sn(r,tn),new on(r)}async function Rg(){let{privateKey:r,publicKey:e}=Bu();return new Qt(r,e)}async function $u(r){let{privateKey:e,publicKey:t}=Cu(r);return new Qt(e,t)}function sn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function V(r,e="utf8"){let t=Ro[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 Ig={"P-256":256,"P-384":384,"P-521":521},_g=Object.keys(Ig),iv=_g.join(" / ");var rc={};be(rc,{MAX_RSA_KEY_SIZE:()=>hn,RsaPrivateKey:()=>Rr,RsaPublicKey:()=>fn,fromJwk:()=>Qg,generateKeyPair:()=>e0,unmarshalRsaPrivateKey:()=>ec,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 Zr(r)}var nr={};be(nr,{exportToPem:()=>Yg,importFromPem:()=>kf,jwkToPkcs1:()=>qg,jwkToPkix:()=>Gg,pkcs1ToJwk:()=>Hg,pkixToJwk:()=>zg});var Ko=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Io(e);let n=jt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),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()}},zn=(r,e,t)=>new Ko(r,e).update(t).digest();zn.create=(r,e)=>new Ko(r,e);function Bg(r,e,t,n){Io(r);let o=hu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(jr(s),jr(i),jr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=jt(e),u=jt(t),f=new Uint8Array(i),l=zn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Cg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function ja(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Bg(r,e,t,n),f,l=new Uint8Array(4),p=Xr(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 fu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let y=0;y<m.length;y++)m[y]^=h[y]})}return Cg(c,u,a,f,h)}var $=dt(Hu());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 er(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 qo(...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 Wa(){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 qu(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=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(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 zu(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 Lv=Math.log(2);function zo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Xa(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 jn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Xa(this.items)}},Gn=[new Uint8Array([1])],Gu="0123456789";var ln="",lt=new ArrayBuffer(0),Za=new Uint8Array(0),Yn="EndOfContent",Yu="OCTET STRING",Wu="BIT STRING";function Mt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?$.BufferSourceConverter.toUint8Array(s.valueHex):Za}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",lt)}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=ln,warnings:n=[],valueBeforeDecode:o=Za}={}){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 Pe=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pe.NAME="valueBlock";var Go=class extends Mt(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):Za,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",lt}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=er(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}}};Go.NAME="identificationBlock";var jo=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=er(this.length,8);if(o.byteLength>127)return this.error="Too big length",lt;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}}};jo.NAME="lengthBlock";var S={},Ce=class extends Lt{constructor({name:e=ln,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Go(o),this.lenBlock=new jo(o),this.valueBlock=s?new s(o):new Pe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new jn;t||Xu(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?lt: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 zu(t,n)}};Ce.NAME="BaseBlock";function Xu(r){if(r instanceof S.Constructed)for(let e of r.valueBlock.value)Xu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Yo=class extends Ce{constructor({value:e=ln,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Yo.NAME="BaseStringBlock";var Wo=class extends Mt(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Wo.NAME="PrimitiveValueBlock";var Zu,Xo=class extends Ce{constructor(e={}){super(e,Wo),this.idBlock.isConstructed=!1}};Zu=Xo;S.Primitive=Zu;Xo.NAME="PRIMITIVE";function Ug(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 Cs(r,e=0,t=r.length){let n=e,o=new Ce({},Pe),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ce;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=Ug(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function un(r){if(!r.byteLength){let e=new Ce({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Cs($.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Fg(r,e){return r?1:e}var wt=class extends Pe{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(;Fg(this.isIndefiniteForm,n)>0;){let i=Cs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Yn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new jn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?lt: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 Ju,tr=class extends Ce{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 Gd=Object.create;var Eo=Object.defineProperty;var jd=Object.getOwnPropertyDescriptor;var Yd=Object.getOwnPropertyNames;var Wd=Object.getPrototypeOf,Xd=Object.prototype.hasOwnProperty;var tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),be=(r,e)=>{for(var t in e)Eo(r,t,{get:e[t],enumerable:!0})},Ol=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yd(e))!Xd.call(r,o)&&o!==t&&Eo(r,o,{get:()=>e[o],enumerable:!(n=jd(e,o))||n.enumerable});return r};var dt=(r,e,t)=>(t=r!=null?Gd(Wd(r)):{},Ol(e||!r||!r.__esModule?Eo(t,"default",{value:r,enumerable:!0}):t,r)),Zd=r=>Ol(Eo({},"__esModule",{value:!0}),r);var Vu=tt(tn=>{"use strict";var Ag="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Ag}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",Rg=/^[0-9a-f]+$/i,Ig=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,_g=/^[a-zA-Z0-9-_]+$/,Ho=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}},qo=class r{static isHex(e){return typeof e===ja&&Rg.test(e)}static isBase64(e){return typeof e===ja&&Ig.test(e)}static isBase64Url(e){return typeof e===ja&&_g.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 Ho.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 Ho.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,"")||""}};qo.DEFAULT_UTF8_ENCODING="utf8";function Sg(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 Bg(...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 Cg(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}tn.BufferSourceConverter=kt;tn.Convert=qo;tn.assign=Sg;tn.combine=Bg;tn.isEqual=Cg});var lc=tt((Rv,Wf)=>{var an=1e3,cn=an*60,ln=cn*60,Ir=ln*24,u0=Ir*7,f0=Ir*365.25;Wf.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return h0(r);if(t==="number"&&isFinite(r))return e.long?p0(r):d0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function h0(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*f0;case"weeks":case"week":case"w":return t*u0;case"days":case"day":case"d":return t*Ir;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ln;case"minutes":case"minute":case"mins":case"min":case"m":return t*cn;case"seconds":case"second":case"secs":case"sec":case"s":return t*an;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function d0(r){var e=Math.abs(r);return e>=Ir?Math.round(r/Ir)+"d":e>=ln?Math.round(r/ln)+"h":e>=cn?Math.round(r/cn)+"m":e>=an?Math.round(r/an)+"s":r+"ms"}function p0(r){var e=Math.abs(r);return e>=Ir?ks(r,e,Ir,"day"):e>=ln?ks(r,e,ln,"hour"):e>=cn?ks(r,e,cn,"minute"):e>=an?ks(r,e,an,"second"):r+" ms"}function ks(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Zf=tt((Iv,Xf)=>{function m0(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=m0});var uc=tt((Ge,Ls)=>{Ge.formatArgs=y0;Ge.save=w0;Ge.load=b0;Ge.useColors=g0;Ge.storage=E0();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 g0(){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 y0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ls.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 w0(r){try{r?Ge.storage.setItem("debug",r):Ge.storage.removeItem("debug")}catch{}}function b0(){let r;try{r=Ge.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function E0(){try{return localStorage}catch{}}Ls.exports=Zf()(Ge);var{formatters:x0}=Ls.exports;x0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Ah=tt((JA,Cc)=>{"use strict";var ry=Object.prototype.hasOwnProperty,Ke="~";function ao(){}Object.create&&(ao.prototype=Object.create(null),new ao().__proto__||(Ke=!1));function ny(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 ny(t,n||r,o),i=Ke?Ke+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 $s(r,e){--r._eventsCount===0?r._events=new ao:delete r._events[e]}function Pe(){this._events=new ao,this._eventsCount=0}Pe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ry.call(t,n)&&e.push(Ke?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Pe.prototype.listeners=function(e){var t=Ke?Ke+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};Pe.prototype.listenerCount=function(e){var t=Ke?Ke+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Pe.prototype.emit=function(e,t,n,o,s,i){var a=Ke?Ke+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};Pe.prototype.on=function(e,t,n){return vh(this,e,t,n,!1)};Pe.prototype.once=function(e,t,n){return vh(this,e,t,n,!0)};Pe.prototype.removeListener=function(e,t,n,o){var s=Ke?Ke+e:e;if(!this._events[s])return this;if(!t)return $s(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&$s(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:$s(this,s)}return this};Pe.prototype.removeAllListeners=function(e){var t;return e?(t=Ke?Ke+e:e,this._events[t]&&$s(this,t)):(this._events=new ao,this._eventsCount=0),this};Pe.prototype.off=Pe.prototype.removeListener;Pe.prototype.addListener=Pe.prototype.on;Pe.prefixed=Ke;Pe.EventEmitter=Pe;typeof Cc<"u"&&(Cc.exports=Pe)});var Gc=tt((yR,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 Ey(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=Ey});var $h=tt(fo=>{(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}(),fo.ip2long=i,fo.long2ip=a,fo.Netmask=r}).call(fo)});var Gh=tt((zh,ti)=>{(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 ti<"u"&&ti.exports?ti.exports=p:r.ipaddr=p})(zh)});var ld=tt((dI,cd)=>{"use strict";cd.exports=ad;var Ky=lc(),ur=ad.prototype,$y=new Date%1e9;function Hy(){return(Math.random()*1e9>>>0)+$y++}function ad(r){r=r||{},this.id=r.id||Hy(),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=Ky(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((EI,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 li=pd(),{hasOwnProperty:gd}=Object.prototype,{propertyIsEnumerable:Gy}=Object,Rn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),jy=wd,md={concatArrays:!1,ignoreUndefined:!1},ui=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)Gy.call(r,n)&&e.push(n)}return e};function In(r){return Array.isArray(r)?Yy(r):li(r)?Wy(r):r}function Yy(r){let e=r.slice(0,0);return ui(r).forEach(t=>{Rn(e,t,In(r[t]))}),e}function Wy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return ui(r).forEach(t=>{Rn(e,t,In(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)?Rn(r,o,al(r[o],e[o],n)):Rn(r,o,In(e[o])))}),r),Xy=(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?Rn(n,o++,s[a]):Rn(n,o++,In(s[a])));n=yd(n,s,ui(s).filter(a=>!i.includes(a)),t)}),n};function al(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Xy(r,e,t):!li(e)||!li(r)?In(e):yd(r,e,ui(e),t)}bd.exports=function(...r){let e=al(In(md),this!==jy&&this||{},md),t={_:{}};for(let n of r)if(n!==void 0){if(!li(n))throw new TypeError("`"+n+"` is not an Option Object");t=al(t,{_:n},e)}return t._}});var Rw={};be(Rw,{createLibp2p:()=>Aw});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 xo(r){return r!=null&&!!r[qi]}var zi=Symbol.for("@libp2p/peer-routing");var Ml="keep-alive";var kw=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??{}}},vo=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 Ao="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={};be(za,{Ed25519PrivateKey:()=>xr,Ed25519PublicKey:()=>Vn,generateKeyPair:()=>Eg,generateKeyPairFromSeed:()=>Fu,unmarshalEd25519PrivateKey:()=>wg,unmarshalEd25519PublicKey:()=>bg});var Ji={};be(Ji,{base58btc:()=>ee,base58flickr:()=>np});var Mw=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 Jd(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 Qd=Jd,ep=Qd,ql=ep;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 Fr({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 Fr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function tp(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 rp(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 Fr({prefix:e,name:r,encode(o){return rp(o,n,t)},decode(o){return tp(o,n,t,r)}})}var ee=Ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),np=Ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};be(ea,{identity:()=>qt});var op=Yl,Gl=128,sp=127,ip=~sp,ap=Math.pow(2,31);function Yl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ap;)e[t++]=r&255|Gl,r/=128;for(;r&ip;)e[t++]=r&255|Gl,r>>>=7;return e[t]=r|0,Yl.bytes=t-n+1,e}var cp=Qi,lp=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>=lp);return Qi.bytes=s-n,t}var up=Math.pow(2,7),fp=Math.pow(2,14),hp=Math.pow(2,21),dp=Math.pow(2,28),pp=Math.pow(2,35),mp=Math.pow(2,42),gp=Math.pow(2,49),yp=Math.pow(2,56),wp=Math.pow(2,63),bp=function(r){return r<up?1:r<fp?2:r<hp?3:r<dp?4:r<pp?5:r<mp?6:r<gp?7:r<yp?8:r<wp?9:10},Ep={encode:op,decode:cp,encodingLength:bp},xp=Ep,Nn=xp;function kn(r,e=0){return[Nn.decode(r,e),Nn.decode.bytes]}function Vr(r,e,t=0){return Nn.encode(r,e,t),e}function Kr(r){return Nn.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Vr(r,s,0),Vr(t,s,n),s.set(e,o),new $r(r,t,e,s)}function pr(r){let e=Rt(r),[t,n]=kn(e),[o,s]=kn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new $r(t,o,i,e)}function 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 $r=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,vp="identity",Zl=Rt;function Ap(r){return pt(Xl,Zl(r))}var qt={code:Xl,name:vp,encode:Zl,digest:Ap};var na={};be(na,{sha256:()=>Ae,sha512:()=>Rp});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")}),Rp=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={};be(oa,{base10:()=>Ip});var Ip=Ht({prefix:"9",name:"base10",alphabet:"0123456789"});var sa={};be(sa,{base16:()=>_p,base16upper:()=>Sp});var _p=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sp=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ia={};be(ia,{base2:()=>Bp});var Bp=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aa={};be(aa,{base256emoji:()=>Lp});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}"),Cp=eu.reduce((r,e,t)=>(r[t]=e,r),[]),Tp=eu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Np(r){return r.reduce((e,t)=>(e+=Cp[t],e),"")}function kp(r){let e=[];for(let t of r){let n=Tp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Lp=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:Np,decode:kp});var ca={};be(ca,{base32:()=>qe,base32hex:()=>Up,base32hexpad:()=>Fp,base32hexpadupper:()=>Vp,base32hexupper:()=>Mp,base32pad:()=>Pp,base32padupper:()=>Op,base32upper:()=>Dp,base32z:()=>Kp});var qe=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Dp=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Pp=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Op=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Up=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Mp=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fp=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vp=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Kp=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var la={};be(la,{base36:()=>$p,base36upper:()=>Hp});var $p=Ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hp=Ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fa={};be(fa,{base64:()=>Ln,base64pad:()=>qp,base64url:()=>ua,base64urlpad:()=>zp});var Ln=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qp=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ua=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zp=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};be(ha,{base8:()=>Gp});var Gp=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var da={};be(da,{identity:()=>jp});var jp=Fr({prefix:"\0",name:"identity",encode:r=>$l(r),decode:r=>Kl(r)});var hb=new TextEncoder,db=new TextDecoder;function tu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Zp(t,pa(r),e??ee.encoder);default:return Jp(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!==Dn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Qp)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[em]===!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!==Dn)throw new Error(`Version 0 CID must use dag-pb (code: ${Dn}) 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,Dn,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 $r(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=kn(e.subarray(t));return t+=p,l},o=n(),s=Dn;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]=Xp(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 Xp(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 Zp(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 Jp(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 Dn=112,Qp=18;function nu(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Vr(r,s,0),Vr(e,s,n),s.set(t,o),s}var em=Symbol.for("@ipld/js-cid/CID");var Gt={...da,...ia,...ha,...oa,...sa,...ca,...la,...Ji,...fa,...aa},Cb={...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}),tm={utf8:ou,"utf-8":ou,hex:Gt.base16,latin1:ma,ascii:ma,binary:ma,...Gt},Io=tm;function D(r,e="utf8"){let t=Io[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 Hr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function rm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function ga(r,...e){if(!rm(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 _o(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Hr(r.outputLen),Hr(r.blockLen)}function qr(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 So=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 Gr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),nt=(r,e)=>r<<32-e|r>>>e,nm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!nm)throw new Error("Non little-endian hardware is not supported");var om=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 om(),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 Bo(...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 zr=class{clone(){return this._cloneInto()}},sm={}.toString;function lu(r,e){if(e!==void 0&&sm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Co(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 jr(r=32){if(So&&typeof So.getRandomValues=="function")return So.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function im(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 Yr=class extends zr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Gr(this.buffer)}update(e){qr(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=Gr(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){qr(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;im(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Gr(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 To=BigInt(4294967295),wa=BigInt(32);function uu(r,e=!1){return e?{h:Number(r&To),l:Number(r>>wa&To)}:{h:Number(r>>wa&To)|0,l:Number(r&To)|0}}function am(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=uu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var cm=(r,e)=>BigInt(r>>>0)<<wa|BigInt(e>>>0),lm=(r,e,t)=>r>>>t,um=(r,e,t)=>r<<32-t|e>>>t,fm=(r,e,t)=>r>>>t|e<<32-t,hm=(r,e,t)=>r<<32-t|e>>>t,dm=(r,e,t)=>r<<64-t|e>>>t-32,pm=(r,e,t)=>r>>>t-32|e<<64-t,mm=(r,e)=>e,gm=(r,e)=>r,ym=(r,e,t)=>r<<t|e>>>32-t,wm=(r,e,t)=>e<<t|r>>>32-t,bm=(r,e,t)=>e<<t-32|r>>>64-t,Em=(r,e,t)=>r<<t-32|e>>>64-t;function xm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var vm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Am=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Rm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Im=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,_m=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Sm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Bm={fromBig:uu,split:am,toBig:cm,shrSH:lm,shrSL:um,rotrSH:fm,rotrSL:hm,rotrBH:dm,rotrBL:pm,rotr32H:mm,rotr32L:gm,rotlSH:ym,rotlSL:wm,rotlBH:bm,rotlBL:Em,add:xm,add3L:vm,add3H:Am,add4L:Rm,add4H:Im,add5H:Sm,add5L:_m},O=Bm;var[Cm,Tm]=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 Yr{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,Tm[b],Wt[b]),q=O.add5H(N,y,A,R,Cm[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 Wr=Co(()=>new ba);var ko={};be(ko,{bitGet:()=>Um,bitLen:()=>Om,bitMask:()=>Pn,bitSet:()=>Mm,bytesToHex:()=>St,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>va,ensureBytes:()=>oe,equalBytes:()=>Dm,hexToBytes:()=>gr,hexToNumber:()=>xa,isBytes:()=>ot,numberToBytesBE:()=>Zt,numberToBytesLE:()=>yr,numberToHexUnpadded:()=>pu,numberToVarBytesBE:()=>Lm,utf8ToBytes:()=>Pm,validateObject:()=>mt});var du=BigInt(0),No=BigInt(1),Nm=BigInt(2);function ot(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var km=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+=km[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 Lm(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 Dm(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 Pm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Om(r){let e;for(e=0;r>du;r>>=No,e+=1);return e}function Um(r,e){return r>>BigInt(e)&No}var Mm=(r,e,t)=>r|(t?No:du)<<BigInt(e),Pn=r=>(Nm<<BigInt(r-1))-No,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 Fm={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=Fm[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),Vm=BigInt(3),Aa=BigInt(4),mu=BigInt(5),gu=BigInt(8),Km=BigInt(9),$m=BigInt(16);function X(r,e){let t=r%e;return t>=me?t:e+t}function Hm(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 Lo(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 qm(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&&Hm(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 zm(r){if(r%Aa===Vm){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%$m,qm(r)}var yu=(r,e)=>(X(r,e)&Z)===Z,Gm=["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=Gm.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function jm(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 Ym(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 Do(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=zm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Pn(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)=>jm(a,c,u),div:(c,u)=>X(c*Lo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Lo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Ym(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 Xm=BigInt(0),Sa=BigInt(1);function Po(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>Xm;)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 On(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),Oo=BigInt(2),Zm=BigInt(8),Jm={zip215:!0};function Qm(r){let e=On(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Uo(r){let e=Qm(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Oo<<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(Oo*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*Oo*te),kl=f(Y*Oo*ue),Ll=kl+Nl,Dl=Tl+Cl,Pl=kl-Nl,$d=f(Ll*Ki),Hd=f(Dl*Pl),qd=f(Ll*Pl),zd=f(Ki*Dl);return new v($d,Hd,zd,qd)}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,Tn=Be+pe,Bl=f(ve-C*xe),Md=f(At*hr),Fd=f(Tn*Bl),Vd=f(At*Bl),Kd=f(hr*Tn);return new v(Md,Fd,Kd,Vd)}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?Zm: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=Po(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=Jm;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"),uE=BigInt(0),eg=BigInt(1),Ba=BigInt(2),tg=BigInt(5),vu=BigInt(10),rg=BigInt(20),ng=BigInt(40),Au=BigInt(80);function og(r){let e=Ca,n=r*r%e*r%e,o=J(n,Ba,e)*n%e,s=J(o,eg,e)*r%e,i=J(s,tg,e)*s%e,a=J(i,vu,e)*i%e,c=J(a,rg,e)*a%e,u=J(c,ng,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 sg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ig(r,e){let t=Ca,n=X(e*e*e,t),o=X(n*n*e,t),s=og(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=Do(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:Wr,randomBytes:jr,adjustScalarBytes:sg,uvRatio:ig},Xr=Uo(Ta);function Ru(r,e,t){if(e.length>255)throw new Error("Context is too big");return Bo(ya("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var fE=Uo({...Ta,domain:Ru}),hE=Uo({...Ta,domain:Ru,prehash:Wr});var ag=(Tt.ORDER+BigInt(3))/BigInt(8),dE=Tt.pow(Ba,ag),pE=Tt.sqrt(Tt.neg(Tt.ONE)),mE=(Tt.ORDER-BigInt(5))/BigInt(8),gE=BigInt(486662);var yE=wu(Tt,Tt.neg(BigInt(486664)));var wE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),bE=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),EE=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),xE=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var vE=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Zr=32,Nt=64,Mo=32;function Iu(){let r=Xr.utils.randomPrivateKey(),e=Xr.getPublicKey(r);return{privateKey:Cu(r,e),publicKey:e}}function _u(r){if(r.length!==Mo)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=Xr.getPublicKey(e);return{privateKey:Cu(e,t),publicKey:t}}function Su(r,e){let t=r.subarray(0,Mo);return Xr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Bu(r,e,t){return Xr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Cu(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Mo;n++)t[n]=r[n],t[Mo+n]=e[n];return t}var Oe={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=Oe.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 Jr(r,e){let n=await Tu().encrypt(r,e);return Ln.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 ug=BigInt(Number.MAX_SAFE_INTEGER),fg=BigInt(Number.MIN_SAFE_INTEGER),$e=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<ug&&e>fg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>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 $e(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 Fo(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 Fo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw it(this,4);return Fo(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 $e(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=Fo(this.buf,this.pos+=4),t=Fo(this.buf,this.pos+=4);return new $e(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 Ue(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}},hg=Ua();function dg(r){return globalThis.Buffer!=null?Ce(r):hg(r)}var Fn=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(Un,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(Un,t.length(),t)}uint64Number(e){let t=$e.fromNumber(e);return this._push(Un,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=$e.fromBigInt(e).zzEncode();return this._push(Un,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(Un,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(Mn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(Mn,4,t.lo)._push(Mn,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(Mn,4,t.lo)._push(Mn,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(mg,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=dg(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 pg(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(pg,e,t),this.next=void 0}};function Un(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 Mn(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 mg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Fn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(gg,e,r),this},Fn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(yg,e,r),this});function gg(r,e,t){e.set(r,t)}function yg(r,e,t){r.length<40?Da(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function $a(){return new Fn}function Me(r,e){let t=$a();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Qr;(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"})(Qr||(Qr={}));function Vo(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 Vo("enum",Qr.VARINT,t,n)}function Fe(r,e){return Vo("message",Qr.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=Fe((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=>Me(t,r.codec()),r.decode=t=>Ue(t,r.codec())})(gt||(gt={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Fe((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=>Me(t,r.codec()),r.decode=t=>Ue(t,r.codec())})(yt||(yt={}));var Vn=class{_key;constructor(e){this._key=en(e,Zr)}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=en(e,Nt),this._publicKey=en(t,Zr)}sign(e){return Su(this._key,e)}get public(){return new Vn(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 Jr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function wg(r){if(r.length>Nt){r=en(r,Nt+Zr);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new xr(n,o)}r=en(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(Zr);return new xr(e,t)}function bg(r){return r=en(r,Zr),new Vn(r)}async function Eg(){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 en(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=Io[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={};be(tc,{MAX_RSA_KEY_SIZE:()=>Jn,RsaPrivateKey:()=>sn,RsaPublicKey:()=>Zn,fromJwk:()=>jg,generateKeyPair:()=>Yg,unmarshalRsaPrivateKey:()=>Qa,unmarshalRsaPublicKey:()=>Gg});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 jr(r)}var rr={};be(rr,{exportToPem:()=>Kg,importFromPem:()=>$g,jwkToPkcs1:()=>Ug,jwkToPkix:()=>Fg,pkcs1ToJwk:()=>Og,pkixToJwk:()=>Mg});var $o=class extends zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,_o(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 qr(this),this.iHash.update(e),this}digestInto(e){qr(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()}},Kn=(r,e,t)=>new $o(r,e).update(t).digest();Kn.create=(r,e)=>new $o(r,e);function xg(r,e,t,n){_o(r);let o=lu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Hr(s),Hr(i),Hr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=jt(e),u=jt(t),f=new Uint8Array(i),l=Kn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function vg(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}=xg(r,e,t,n),f,l=new Uint8Array(4),p=Gr(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 vg(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 zo(...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 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 Sx=Math.log(2);function Go(){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 Hn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wa(this.items)}},$n=[new Uint8Array([1])],Hu="0123456789";var nn="",ct=new ArrayBuffer(0),Xa=new Uint8Array(0),qn="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=nn,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 jo=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}}};jo.NAME="identificationBlock";var Yo=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}}};Yo.NAME="lengthBlock";var S={},Ie=class extends Lt{constructor({name:e=nn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new jo(o),this.lenBlock=new Yo(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 Hn;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 Wo=class extends Ie{constructor({value:e=nn,...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}'`}};Wo.NAME="BaseStringBlock";var Xo=class extends Ut(Ne){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Xo.NAME="PrimitiveValueBlock";var Yu,Zo=class extends Ie{constructor(e={}){super(e,Xo),this.idBlock.isConstructed=!1}};Yu=Zo;S.Primitive=Yu;Zo.NAME="PRIMITIVE";function Ng(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 Ts(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=Ng(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 on(r){if(!r.byteLength){let e=new Ie({},Ne);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ts($.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function kg(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(;kg(this.isIndefiniteForm,n)>0;){let i=Ts(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===qn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===qn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Hn;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(`
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} :`}};Ju=tr;S.Constructed=Ju;tr.NAME="CONSTRUCTED";var Zo=class extends Pe{fromBER(e,t,n){return t}toBER(e){return lt}};Zo.override="EndOfContentValueBlock";var Qu,Jo=class extends Ce{constructor(e={}){super(e,Zo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Qu=Jo;S.EndOfContent=Qu;Jo.NAME=Yn;var ef,rr=class extends Ce{constructor(e={}){super(e,Pe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ef=rr;S.Null=ef;rr.NAME="NULL";var Qo=class extends Mt(Pe){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,Wa.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Qo.NAME="BooleanValueBlock";var tf,es=class extends Ce{constructor(e={}){super(e,Qo),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}`}};tf=es;S.Boolean=tf;es.NAME="BOOLEAN";var ts=class extends Mt(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===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Yu)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}}};ts.NAME="OctetStringValueBlock";var rf,Dt=class r extends Ce{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=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=Cs(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?tr.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)}};rf=Dt;S.OctetString=rf;Dt.NAME=Yu;var rs=class extends Mt(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===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Wu)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=Cs(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 lt;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}}};rs.NAME="BitStringValueBlock";var nf,cn=class extends Ce{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},rs),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 tr.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)}`}}};nf=cn;S.BitString=nf;cn.NAME=Wu;var of;function Vg(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=qo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=qo(t,s)),s}function ju(r){if(r>=Gn.length)for(let e=Gn.length;e<=r;e++){let t=new Uint8Array([0]),n=Gn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=qo(t,n)),Gn.push(n)}return Gn[r]}function Kg(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Wn=class extends Mt(Pe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Wa.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(qu(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=Kg(ju(n),t),i="-";break;default:t=Vg(t,ju(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Gu.charAt(t[c]));return a===!1&&(i+=Gu.charAt(0)),i}};of=Wn;Wn.NAME="IntegerValueBlock";Object.defineProperty(of.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var sf,fe=class r extends Ce{constructor(e={}){super(e,Wn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return zo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){zo();let t=BigInt(e),n=new jn,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()}`}};sf=fe;S.Integer=sf;fe.NAME="INTEGER";var af,ns=class extends fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};af=ns;S.Enumerated=af;ns.NAME="ENUMERATED";var Xn=class extends Mt(Pe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=$.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){zo();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=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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}}};Xn.NAME="sidBlock";var os=class extends Pe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Xn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,lt;t.push(o)}return Xa(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Xn;if(o>Number.MAX_SAFE_INTEGER){zo();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}};os.NAME="ObjectIdentifierValueBlock";var cf,ct=class extends Ce{constructor(e={}){super(e,os),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()}}};cf=ct;S.ObjectIdentifier=cf;ct.NAME="OBJECT IDENTIFIER";var Zn=class extends Mt(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=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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}}};Zn.NAME="relativeSidBlock";var ss=class extends Pe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Zn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,lt;n.push(s)}return Xa(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Zn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ss.NAME="RelativeObjectIdentifierValueBlock";var lf,is=class extends Ce{constructor(e={}){super(e,ss),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()}}};lf=is;S.RelativeObjectIdentifier=lf;is.NAME="RelativeObjectIdentifier";var uf,Ee=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};uf=Ee;S.Sequence=uf;Ee.NAME="SEQUENCE";var ff,as=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ff=as;S.Set=ff;as.NAME="SET";var cs=class extends Mt(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ln}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="StringValueBlock";var ls=class extends cs{};ls.NAME="SimpleStringValueBlock";var Fe=class extends Yo{constructor({...e}={}){super(e,ls)}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 us=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}};us.NAME="Utf8StringValueBlock";var hf,Pt=class extends us{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};hf=Pt;S.Utf8String=hf;Pt.NAME="UTF8String";var fs=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))}};fs.NAME="BmpStringValueBlock";var df,hs=class extends fs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};df=hs;S.BmpString=df;hs.NAME="BMPString";var ds=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=er(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}};ds.NAME="UniversalStringValueBlock";var pf,ps=class extends ds{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};pf=ps;S.UniversalString=pf;ps.NAME="UniversalString";var mf,ms=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};mf=ms;S.NumericString=mf;ms.NAME="NumericString";var gf,gs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};gf=gs;S.PrintableString=gf;gs.NAME="PrintableString";var yf,ys=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};yf=ys;S.TeletexString=yf;ys.NAME="TeletexString";var wf,ws=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};wf=ws;S.VideotexString=wf;ws.NAME="VideotexString";var bf,bs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};bf=bs;S.IA5String=bf;bs.NAME="IA5String";var Ef,Es=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ef=Es;S.GraphicString=Ef;Es.NAME="GraphicString";var xf,Jn=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};xf=Jn;S.VisibleString=xf;Jn.NAME="VisibleString";var vf,xs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};vf=xs;S.GeneralString=vf;xs.NAME="GeneralString";var Af,vs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Af=vs;S.CharacterString=Af;vs.NAME="CharacterString";var Rf,Qn=class extends Jn{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}}};Rf=Qn;S.UTCTime=Rf;Qn.NAME="UTCTime";var If,As=class extends Qn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),l=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(h.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,h.length===4){if(d=parseInt(h.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push($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}}};If=As;S.GeneralizedTime=If;As.NAME="GeneralizedTime";var _f,Rs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};_f=Rs;S.DATE=_f;Rs.NAME="DATE";var Sf,Is=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Sf=Is;S.TimeOfDay=Sf;Is.NAME="TimeOfDay";var Bf,_s=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Bf=_s;S.DateTime=Bf;_s.NAME="DateTime";var Cf,Ss=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Cf=Ss;S.Duration=Cf;Ss.NAME="Duration";var Tf,Bs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Tf=Bs;S.TIME=Tf;Bs.NAME="TIME";function Hg(r){let{result:e}=un(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 qg(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 Ee({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 zg(r){let{result:e}=un(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 Gg(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new rr]}),new cn({valueHex:new Ee({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 jg=16,Ja=32,Qa=1e4;async function Yg(r,e){let t=Ie.get(),o=new Ee({value:[new fe({value:0}),new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new rr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=vr(jg),a=await ja(Qr,e,i,{c:Qa,dkLen:Ja}),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 Ee({value:[new Dt({valueHex:i}),new fe({value:Qa}),new fe({value:Ja}),new Ee({value:[new ct({value:"1.2.840.113549.2.11"}),new rr]})]}),p=new Ee({value:[new ct({value:"1.2.840.113549.1.5.13"}),new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.5.12"}),l]}),new Ee({value:[new ct({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new Ee({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 kf(r,e){let t=Ie.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}=un(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Wg(s),l=await ja(Qr,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=eo(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=un(h);n=Nf(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}=un(o);n=Nf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return ec(n)}function Wg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new E("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=eo(s.valueBlock.value[0].getValue()),a=Qa,c=Ja;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new E("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new E("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=eo(u.valueBlock.value[1].getValue());return{cipherText:eo(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Nf(r){return eo(r.valueBlock.value[2].getValue())}function eo(r){return new Uint8Array(r,0,r.byteLength)}async function Lf(r){let e=await Ie.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 Of(e);return{privateKey:t[0],publicKey:t[1]}}async function tc(r){let t=[await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Xg(r)],n=await Of({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Df(r,e){let t=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ie.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Pf(r,e,t){let n=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ie.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Of(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ie.get().subtle.exportKey("jwk",r.privateKey),Ie.get().subtle.exportKey("jwk",r.publicKey)])}async function Xg(r){return Ie.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 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 hn=8192,fn=class{_key;constructor(e){this._key=e}verify(e,t){return Pf(this._key,t,e)}marshal(){return nr.jwkToPkix(this._key)}get bytes(){return gt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},Rr=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return vr(16)}sign(e){return Df(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fn(this._publicKey)}marshal(){return nr.jwkToPkcs1(this._key)}get bytes(){return yt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.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 nr.exportToPem(this,e);if(t==="libp2p-key")return rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function ec(r){let e=nr.pkcs1ToJwk(r);if(Ts(e)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await tc(e);return new Rr(t.privateKey,t.publicKey)}function Jg(r){let e=nr.pkixToJwk(r);if(Ts(e)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fn(e)}async function Qg(r){if(Ts(r)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await tc(r);return new Rr(e.privateKey,e.publicKey)}async function e0(r){if(r>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Lf(r);return new Rr(e.privateKey,e.publicKey)}var ac={};be(ac,{Secp256k1PrivateKey:()=>pn,Secp256k1PublicKey:()=>dn,generateKeyPair:()=>m0,unmarshalSecp256k1PrivateKey:()=>d0,unmarshalSecp256k1PublicKey:()=>p0});var t0=(r,e,t)=>r&e^~r&t,r0=(r,e,t)=>r&e^r&t^e&t,n0=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]),or=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),sr=new Uint32Array(64),nc=class extends Jr{constructor(){super(64,32,8,!1),this.A=or[0]|0,this.B=or[1]|0,this.C=or[2]|0,this.D=or[3]|0,this.E=or[4]|0,this.F=or[5]|0,this.G=or[6]|0,this.H=or[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)sr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=sr[l-15],h=sr[l-2],d=ot(p,7)^ot(p,18)^p>>>3,g=ot(h,17)^ot(h,19)^h>>>10;sr[l]=g+sr[l-7]+d+sr[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=ot(a,6)^ot(a,11)^ot(a,25),h=f+p+t0(a,c,u)+n0[l]+sr[l]|0,g=(ot(n,2)^ot(n,13)^ot(n,22))+r0(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(){sr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Mf=Bo(()=>new nc);function o0(r){let e=Kn(r);mt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:s0,hexToBytes:i0}=No,Ir={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Ir;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:s0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Ir,t=typeof r=="string"?i0(r):r;if(!st(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}=Ir._parseInt(t.subarray(2)),{d:i,l:a}=Ir._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Ut=BigInt(0),Qe=BigInt(1),s1=BigInt(2),Uf=BigInt(3),i1=BigInt(4);function a0(r){let e=o0(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"&&Ut<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(st(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,Uf),{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),M=t.mul(w,b);return M=t.add(M,M),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(M,v),T=t.mul(y,T),z=t.mul(g,z),M=t.sub(N,z),M=t.mul(g,M),M=t.add(M,T),T=t.add(N,N),N=t.add(T,N),N=t.add(N,z),N=t.mul(N,M),R=t.add(R,N),z=t.mul(b,A),z=t.add(z,z),N=t.mul(z,M),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,Uf),M=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(M,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(M,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(M,M),le=t.add(le,M),ie=t.mul(q,ie),I=t.mul(z,I),le=t.add(le,ie),ie=t.sub(M,ie),ie=t.mul(q,ie),I=t.add(I,ie),M=t.mul(le,I),T=t.add(T,M),M=t.mul(k,I),R=t.mul(We,R),R=t.sub(R,M),M=t.mul(We,le),N=t.mul(k,N),N=t.add(N,M),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===Ut)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>Ut||v>Ut;)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:M}=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(M)}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===Ut||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=Do(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function c0(r){let e=Kn(r);return mt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ff(r){let e=c0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Ut<I&&I<t.ORDER}function a(I){return X(I,n)}function c(I){return ko(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=a0({...e,toBytes(I,k,U){let _=k.toAffine(),x=t.toBytes(_.x),B=Ct;return U?B(Uint8Array.from([k.hasEvenY()?2:3]),x):B(Uint8Array.from([4]),x,t.toBytes(_.y))},fromBytes(I){let k=I.length,U=I[0],_=I.subarray(1);if(k===o&&(U===2||U===3)){let x=Bt(_);if(!i(x))throw new Error("Point is not on curve");let B=l(x),L=t.sqrt(B),P=(L&Qe)===Qe;return(U&1)===1!==P&&(L=t.neg(L)),{x,y:L}}else if(k===s&&U===4){let x=t.fromBytes(_.subarray(0,t.BYTES)),B=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x,y:B}}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,U)=>Bt(I.slice(k,U));class y{constructor(k,U,_){this.r=k,this.s=U,this.recovery=_,this.assertValidity()}static fromCompact(k){let U=e.nByteLength;return k=oe("compactSignature",k,U*2),new y(m(k,0,U),m(k,U,2*U))}static fromDER(k){let{r:U,s:_}=Ir.toSig(oe("DER",k));return new y(U,_)}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:U,s:_,recovery:x}=this,B=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?U+e.n:U;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(-B*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 yr(this.toDERHex())}toDERHex(){return Ir.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(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 Au(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=st(I),U=typeof I=="string",_=(k||U)&&I.length;return k?_===o||_===s:U?_===2*o||_===2*s:I instanceof u}function v(I,k,U=!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(U)}let R=e.bits2int||function(I){let k=Bt(I),U=I.length*8-e.nBitLength;return U>0?k>>BigInt(U):k},T=e.bits2int_modN||function(I){return a(R(I))},N=Vn(e.nBitLength);function q(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Ut<=I&&I<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Zt(I,e.nByteLength)}function z(I,k,U=M){if(["recovered","canonical"].some(re=>re in U))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:x}=e,{lowS:B,prehash:L,extraEntropy:P}=U;B==null&&(B=!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 re=P===!0?x(t.BYTES):P;Y.push(oe("extraEntropy",re))}let H=Ct(...Y),G=F;function ue(re){let ve=R(re);if(!p(ve))return;let Ae=c(ve),me=u.BASE.multiply(ve).toAffine(),ke=a(me.x);if(ke===Ut)return;let At=a(Ae*a(G+ke*K));if(At===Ut)return;let dr=(me.x===ke?0:2)|Number(me.y&Qe),On=At;return B&&d(At)&&(On=g(At),dr^=1),new y(ke,On,dr)}return{seed:H,k2sig:ue}}let M={lowS:e.lowS,prehash:!1},le={lowS:e.lowS,prehash:!1};function ie(I,k,U=M){let{seed:_,k2sig:x}=z(I,k,U),B=e;return va(B.hash.outputLen,B.nByteLength,B.hmac)(_,x)}u.BASE._setWindowSize(8);function We(I,k,U,_=le){let x=I;if(k=oe("msgHash",k),U=oe("publicKey",U),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:B,prehash:L}=_,P,F;try{if(typeof x=="string"||st(x))try{P=y.fromDER(x)}catch(me){if(!(me instanceof Ir.Err))throw me;P=y.fromCompact(x)}else if(typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint"){let{r:me,s:ke}=x;P=new y(me,ke)}else throw new Error("PARSE");F=u.fromHex(U)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(B&&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),re=a(K*G),ve=u.BASE.multiplyAndAddUnsafe(F,ue,re)?.toAffine();return ve?a(ve.x)===K:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ie,verify:We,ProjectivePoint:u,Signature:y,utils:w}}function l0(r){return{hash:r,hmac:(e,...t)=>zn(r,e,So(...t)),randomBytes:Zr}}function Vf(r,e){let t=n=>Ff({...r,...l0(n)});return Object.freeze({...t(e),create:t})}var Hf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Kf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),u0=BigInt(1),oc=BigInt(2),$f=(r,e)=>(r+e/oc)/e;function f0(r){let e=Hf,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,oc,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,oc,e);if(!sc.eql(sc.sqr(R),r))throw new Error("Cannot find square root");return R}var sc=Lo(Hf,void 0,void 0,{sqrt:f0}),ut=Vf({a:BigInt(0),b:BigInt(7),Fp:sc,n:Kf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Kf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-u0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=$f(s*r,e),c=$f(-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}}}},Mf),m1=BigInt(0);var g1=ut.ProjectivePoint;function qf(){return ut.utils.randomPrivateKey()}function zf(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(Ze(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function Gf(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(Ze(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function jf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Yf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ic(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Wf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var dn=class{_key;constructor(e){ic(e),this._key=e}verify(e,t){return Gf(this._key,t,e)}marshal(){return jf(this._key)}get bytes(){return gt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Ze(e)?{bytes:t}=await e:t=e.bytes,t}},pn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Wf(e),Yf(this._key),ic(this._publicKey)}sign(e){return zf(this._key,e)}get public(){return new dn(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.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 rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function d0(r){return new pn(r)}function p0(r){return new dn(r)}async function m0(){let r=qf();return new pn(r)}var ir={rsa:rc,ed25519:Ga,secp256k1:ac};function cc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function lc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw cc(r)}async function Xf(r,e){return lc(r).generateKeyPair(e??2048)}function to(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return ir.rsa.unmarshalRsaPublicKey(t);case Q.Ed25519:return ir.ed25519.unmarshalEd25519PublicKey(t);case Q.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw cc(e.Type??"unknown")}}function Zf(r,e){return e=(e??"rsa").toLowerCase(),lc(e),r.bytes}async function uc(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return ir.rsa.unmarshalRsaPrivateKey(t);case Q.Ed25519:return ir.ed25519.unmarshalEd25519PrivateKey(t);case Q.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw cc(e.Type??"RSA")}}function Jf(r,e){return e=(e??"rsa").toLowerCase(),lc(e),r.bytes}var Ye=dt(hc(),1);Ye.default.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);Ye.default.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);Ye.default.formatters.m=r=>r==null?"undefined":Gr.baseEncode(r);Ye.default.formatters.p=r=>r==null?"undefined":r.toString();Ye.default.formatters.c=r=>r==null?"undefined":r.toString();Ye.default.formatters.k=r=>r==null?"undefined":r.toString();Ye.default.formatters.a=r=>r==null?"undefined":r.toString();function B0(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 C0(r)}}}function C0(r){let e=B0(`${r}:trace`);return Ye.default.enabled(`${r}:trace`)&&Ye.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Ye.default)(`${r}:trace`)),Object.assign((0,Ye.default)(r),{error:(0,Ye.default)(`${r}:error`),trace:e})}var T0=Symbol.for("nodejs.util.inspect.custom"),rh=Object.values(Gt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Gt.identity.decoder),nh=114,dc=36,pc=37,ro=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 nt.createV1(nh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return he(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[T0](){return`PeerId(${this.toString()})`}},Sr=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Br=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Cr=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function oh(r){if(r.type==="RSA")return new Sr(r);if(r.type==="Ed25519")return new Br(r);if(r.type==="secp256k1")return new Cr(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function he(r,e){if(e=e??rh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ee.decode(`z${r}`));return r.startsWith("12D")?new Br({multihash:t}):r.startsWith("16U")?new Cr({multihash:t}):new Sr({multihash:t})}return wn(rh.decode(r))}function wn(r){try{let e=mr(r);if(e.code===qt.code){if(e.digest.length===dc)return new Br({multihash:e});if(e.digest.length===pc)return new Cr({multihash:e})}if(e.code===Re.code)return new Sr({multihash:e})}catch{return N0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function N0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==nh)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Re.code)return new Sr({multihash:r.multihash});if(e.code===qt.code){if(e.digest.length===dc)return new Br({multihash:r.multihash});if(e.digest.length===pc)return new Cr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ds(r,e){return r.length===dc?new Br({multihash:pt(qt.code,r),privateKey:e}):r.length===pc?new Cr({multihash:pt(qt.code,r),privateKey:e}):new Sr({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function Tr(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 He=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 Tr(this.map.entries(),e=>[he(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,he(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 Tr(this.map.keys(),e=>he(e))}values(){return this.map.values()}get size(){return this.map.size}};var et=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 Tr(this.set.entries(),e=>{let t=he(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=he(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Tr(this.set.values(),e=>he(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 mc;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),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.id=t.bytes();break;case 2:o.pubKey=t.bytes();break;case 3:o.privKey=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(mc||(mc={}));var sh=async()=>{let r=await Xf("Ed25519"),e=await L0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function L0(r){return Ds(Zf(r.public),Jf(r))}var D0=Math.pow(2,7),P0=Math.pow(2,14),O0=Math.pow(2,21),gc=Math.pow(2,28),yc=Math.pow(2,35),wc=Math.pow(2,42),bc=Math.pow(2,49),j=128,Oe=127;function Me(r){if(r<D0)return 1;if(r<P0)return 2;if(r<O0)return 3;if(r<gc)return 4;if(r<yc)return 5;if(r<wc)return 6;if(r<bc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function M0(r,e,t=0){switch(Me(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 U0(r,e,t=0){switch(Me(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 F0(r,e){let t=r[e],n=0;if(n+=t&Oe,t<j||(t=r[e+1],n+=(t&Oe)<<7,t<j)||(t=r[e+2],n+=(t&Oe)<<14,t<j)||(t=r[e+3],n+=(t&Oe)<<21,t<j)||(t=r[e+4],n+=(t&Oe)*gc,t<j)||(t=r[e+5],n+=(t&Oe)*yc,t<j)||(t=r[e+6],n+=(t&Oe)*wc,t<j)||(t=r[e+7],n+=(t&Oe)*bc,t<j))return n;throw new RangeError("Could not decode varint")}function V0(r,e){let t=r.get(e),n=0;if(n+=t&Oe,t<j||(t=r.get(e+1),n+=(t&Oe)<<7,t<j)||(t=r.get(e+2),n+=(t&Oe)<<14,t<j)||(t=r.get(e+3),n+=(t&Oe)<<21,t<j)||(t=r.get(e+4),n+=(t&Oe)*gc,t<j)||(t=r.get(e+5),n+=(t&Oe)*yc,t<j)||(t=r.get(e+6),n+=(t&Oe)*wc,t<j)||(t=r.get(e+7),n+=(t&Oe)*bc,t<j))return n;throw new RangeError("Could not decode varint")}function qe(r,e,t=0){return e==null&&(e=Le(Me(r))),e instanceof Uint8Array?M0(r,e,t):U0(r,e,t)}function ft(r,e=0){return r instanceof Uint8Array?F0(r,e):V0(r,e)}var ah=Symbol.for("@achingbrain/uint8arraylist");function ih(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 Ps(r){return!!r?.[ah]}var xe=class r{bufs;length;[ah]=!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(Ps(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(Ps(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=ih(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ih(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(Ps(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 ge(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ge(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(!Ps(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let p=u;p>=0;p--){let h=this.get(l+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=It(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=It(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var ch={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var no;(function(r){let e;r.codec=()=>(e==null&&(e=Be((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=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(no||(no={}));var bn=class r{static createFromProtobuf=async e=>{let t=no.decode(e),n=await Ds(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=lh(n,o,s),c=await(await uc(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",ch.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=no.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return te(this.marshal(),e.marshal())}async validate(e){let t=lh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return to(this.peerId.publicKey).verify(t.subarray(),this.signature)}},lh=(r,e,t)=>{let n=D(r),o=qe(n.byteLength),s=qe(e.length),i=qe(t.length);return new xe(o,n,s,e,i,t)};function uh(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 Os=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var fh=45,K0=15,En=new Os;function Ec(r){if(!(r.length>K0))return En.new(r).parseWith(()=>En.readIPv4Addr())}function xc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>fh))return En.new(r).parseWith(()=>En.readIPv6Addr())}function Ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>fh))return En.new(r).parseWith(()=>En.readIPAddr())}var d2=parseInt("0xFFFF",16),p2=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Us(r){return!!Ec(r)}function Fs(r){return!!xc(r)}function xn(r){return!!Ms(r)}var ph=Us,G0=Fs,vc=function(r){let e=0;if(r=r.toString().trim(),ph(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(G0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ph(t[n]),i;s&&(i=vc(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")},mh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var vn={},Ac={},Y0=[[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"]];Y0.forEach(r=>{let e=W0(...r);Ac[e.code]=e,vn[e.name]=e});function W0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Ac[r]!=null)return Ac[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(vn[r]!=null)return vn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Z2=W("ip4"),J2=W("ip6"),Q2=W("ipcidr");function Ic(r,e){switch(W(r).code){case 4:case 41:return Z0(e);case 42:return wh(e);case 6:case 273:case 33:case 132:return Eh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return wh(e);case 421:return ty(e);case 444:return bh(e);case 445:return bh(e);case 466:return ey(e);default:return V(e,"base16")}}function _c(r,e){switch(W(r).code){case 4:return gh(e);case 41:return gh(e);case 42:return yh(e);case 6:case 273:case 33:case 132:return Sc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return yh(e);case 421:return J0(e);case 444:return ry(e);case 445:return ny(e);case 466:return Q0(e);default:return D(e,"base16")}}var Rc=Object.values(Gt).map(r=>r.decoder),X0=function(){let r=Rc[0].or(Rc[1]);return Rc.slice(2).forEach(e=>r=r.or(e)),r}();function gh(r){if(!xn(r))throw new Error("invalid ip address");return vc(r)}function Z0(r){let e=mh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xn(e))throw new Error("invalid ip address");return e}function Sc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Eh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function yh(r){let e=D(r),t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function wh(r){let e=ft(r);if(r=r.slice(Me(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function J0(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ee.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function Q0(r){let e=X0.decode(r),t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function ey(r){let e=ft(r),t=r.slice(Me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function ty(r){let e=ft(r),t=r.slice(Me(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function ry(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ze.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Sc(n);return ge([t,o],t.length+o.length)}function ny(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ze.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Sc(n);return ge([t,o],t.length+o.length)}function bh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=Eh(t);return`${n}:${o}`}function xh(r){r=Bc(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 Ah("invalid address: "+r);if(a.path===!0){n=Bc(o.slice(s).join("/")),e.push([a.code,_c(a.code,n)]),t.push([a.code,n]);break}let c=_c(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Ic(a.code,c)])}return{string:vh(t),bytes:Tc(e),tuples:e,stringTuples:t,path:n}}function Cc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=ft(r,o),i=Me(s),a=W(s),c=oy(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 Ah("Invalid address Uint8Array: "+V(r,"base16"));e.push([s,u]);let f=Ic(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:vh(t),tuples:e,stringTuples:t,path:n}}function vh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Bc(e.join("/"))}function Tc(r){return ge(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(qe(t.code));return e.length>1&&e[1]!=null&&(n=ge([n,e[1]])),n}))}function oy(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+Me(t)}}function Bc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Ah(r){return new Error("Error parsing address: "+r)}var sy=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),iy=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Vs=class r{bytes;#e;#t;#s;#a;[Nc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Cc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=xh(e)}else if(ar(e))t=Cc(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??""}`),iy.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(Tc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===vn.p2p.code&&e.push([n,o]),n===vn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ee.decode(`z${n}`),"base58btc"):V(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Ks.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)}[sy](){return`Multiaddr(${this.#e})`}};var Ks=new Map;function ar(r){return!!r?.[Nc]}function se(r){return new Vs(r)}var Rh="libp2p-peer-record",Ih=Uint8Array.from([3,1]);var oo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Be((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=>Se(s,n.codec()),n.decode=s=>_e(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Be((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=>Se(n,r.codec()),r.decode=n=>_e(n,r.codec())})(oo||(oo={}));var kr=class r{static createFromProtobuf=e=>{let t=oo.decode(e),n=wn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Rh;static CODEC=Ih;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=oo.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||!uh(this.multiaddrs,e.multiaddrs))}};function ay(r){return r[Symbol.asyncIterator]!=null}function cy(r){if(ay(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 so=cy;var Lc=dt(Sh(),1);var ao=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Dc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Bh=r=>globalThis.DOMException===void 0?new Dc(r):new DOMException(r),Ch=r=>{let e=r.reason===void 0?Bh("This operation was aborted."):r.reason;return e instanceof Error?e:Bh(e)};function co(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(Ch(p)),p.addEventListener("abort",()=>{f(Ch(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new ao;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 Pc(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 lo=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=Pc(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 An=class extends Lc.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:lo,...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=co(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 ao&&!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 cr={},Rn=r=>{r.addEventListener("message",e=>{Rn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Rn.dispatchEvent("message",r,e)})};Rn.addEventListener=(r,e)=>{cr[r]==null&&(cr[r]=[]),cr[r].push(e)};Rn.removeEventListener=(r,e)=>{cr[r]!=null&&(cr[r]=cr[r].filter(t=>t===e))};Rn.dispatchEvent=function(r,e,t){cr[r]!=null&&cr[r].forEach(n=>n(e,t))};var Oc=Rn;var Mc="lock:worker:request-read",Uc="lock:worker:release-read",Fc="lock:master:grant-read",Vc="lock:worker:request-write",Kc="lock:worker:release-write",$c="lock:master:grant-write";var Th=(r=21)=>Math.random().toString().substring(2);var Nh=(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)})}}}))},kh=(r,e,t,n)=>async()=>{let o=Th();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)})},fy={singleProcess:!1},Lh=r=>{if(r=Object.assign({},fy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Oc.addEventListener("message",Nh(t,"requestReadLock",Mc,Uc,Fc)),Oc.addEventListener("message",Nh(t,"requestWriteLock",Vc,Kc,$c)),t}return{isWorker:!0,readLock:t=>kh(t,Mc,Fc,Uc),writeLock:t=>kh(t,Vc,$c,Kc)}};var Lr={},lr;async function Hc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>co((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var hy=(r,e)=>{if(lr.isWorker===!0)return{readLock:lr.readLock(r,e),writeLock:lr.writeLock(r,e)};let t=new An({concurrency:1}),n;return{async readLock(){if(n!=null)return Hc(n,e);n=new An({concurrency:e.concurrency,autoStart:!1});let o=n,s=Hc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Hc(t,e)}}},dy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function qc(r){let e=Object.assign({},dy,r);return lr==null&&(lr=Lh(e),lr.isWorker!==!0&&(lr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),lr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=hy(e.name,e)),Lr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var In;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Be((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=>Se(i,o.codec()),o.decode=i=>_e(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Be((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=qs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Se(i,o.codec()),o.decode=i=>_e(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Be((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Hs.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(Hs.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=>Se(o,r.codec()),r.decode=o=>_e(o,r.codec())})(In||(In={}));var Hs;(function(r){let e;r.codec=()=>(e==null&&(e=Be((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=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(Hs||(Hs={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Be((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=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(qs||(qs={}));function _n(r,e){let t=In.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=oh({...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="/",Dh=new TextEncoder().encode(Ft),zs=Dh[0],Dr=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]!==zs)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=Dh),this._buf[0]!==zs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(zs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===zs;)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 py(this.baseNamespace())}name(){return my(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(),...gy(e.map(t=>t.namespaces()))])}};function py(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function my(r){let e=r.split(":");return e[e.length-1]}function gy(r){return[].concat(...r)}var zc="/peers/";function Sn(r){if(!Eo(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${zc}${e}`)}async function Ph(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)),!ar(o.multiaddr))throw new E("Multiaddr was invalid",Te.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function js(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",Te.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new E("peer id did not match existing peer id",Te.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Gs(l,{validate:Oh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gs(l,{validate:Mh,map:Uh})}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=Gs([...a.entries()],{validate:Oh})}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=Gs([...p.entries()],{validate:Mh,map:Uh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Ph(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 Gs(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 Oh(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Te.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Te.ERR_INVALID_PARAMETERS)}function Mh(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Te.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Te.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Te.ERR_INVALID_PARAMETERS)}}function Uh(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 Ys(r,e,t){let n=r.toString().split("/")[2],o=ze.decode(n),s=wn(o),i=t.get(s);if(i!=null)return i;let a=_n(s,e);return t.set(s,a),a}function yy(r,e){return r==null?{}:{prefix:zc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ys(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ys(n.key,n.value,e),Ys(o.key,o.value,e)))}}var Ws=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=qc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(Sn(e))}async load(e){let t=await this.datastore.get(Sn(e));return _n(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(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 js(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 js(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new He;for await(let{key:n,value:o}of this.datastore.query(yy(e??{},t))){let s=Ys(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Sn(e)),n=_n(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=In.encode(t);return n!=null&&te(s,n)?{peer:_n(e,s),previous:o,updated:!1}:(await this.datastore.put(Sn(e),s),{peer:_n(e,s),previous:o,updated:!0})}};var Xs=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 Ws(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 so(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 bn.openAndCertify(e,kr.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=kr.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 bn.createFromProtobuf(s.peerRecordEnvelope),a=kr.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 wy(r){return r[Symbol.asyncIterator]!=null}function by(r){if(wy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gc=by;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 Fh=Ey;function xy(r){return r[Symbol.asyncIterator]!=null}function vy(r,e){if(xy(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Fh(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 Pr=vy;function Ay(r){return r[Symbol.asyncIterator]!=null}function Ry(r,e){return Ay(r)?async function*(){yield*(await so(r)).sort(e)}():function*(){yield*so(r).sort(e)}()}var jc=Ry;function Iy(r){return r[Symbol.asyncIterator]!=null}function _y(r,e){return Iy(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 Yc=_y;var Zs=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 Gc(this.putMany(e,n)),e=[],await Gc(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=Yc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=Yc(n,e.limit)),n}};var $h=dt(Wc(),1);function Hh(r){return r=r??new Error("Not Found"),(0,$h.default)(r,"ERR_NOT_FOUND")}var Js=class extends Zs{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 Hh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Dr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Dr(e)}};function qh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Cy=r=>r;function Xc(r,e){let t=r.getPeerId();return t!=null&&he(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Qs=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??Cy,this._updatePeerStoreAddresses=qh(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=Xc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Xc(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=Xc(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 Zc=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=>$l(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")}},Ty=["metrics","connectionProtector"],Ny=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function zh(r={}){let e=new Zc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ny.includes(o)){let i=e.components[o];if(i==null&&!Ty.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 Jh=dt(Gh(),1);var jh="[a-fA-F\\d:]",ur=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${jh})|(?<=${jh})(?=\\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}",de="[a-fA-F\\d]{1,4}",ei=`
6
+ `)}`:`${t} :`}};Wu=er;S.Constructed=Wu;er.NAME="CONSTRUCTED";var Jo=class extends Ne{fromBER(e,t,n){return t}toBER(e){return ct}};Jo.override="EndOfContentValueBlock";var Xu,Qo=class extends Ie{constructor(e={}){super(e,Jo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Xu=Qo;S.EndOfContent=Xu;Qo.NAME=qn;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 es=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}}};es.NAME="BooleanValueBlock";var Ju,ts=class extends Ie{constructor(e={}){super(e,es),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=ts;S.Boolean=Ju;ts.NAME="BOOLEAN";var rs=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===qn){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}}};rs.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},rs),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=Ts(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 ns=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===qn){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=Ts(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}}};ns.NAME="BitStringValueBlock";var ef,rn=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},ns),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=rn;S.BitString=ef;rn.NAME=Gu;var tf;function Lg(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=zo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=zo(t,s)),s}function qu(r){if(r>=$n.length)for(let e=$n.length;e<=r;e++){let t=new Uint8Array([0]),n=$n[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=zo(t,n)),$n.push(n)}return $n[r]}function Dg(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var zn=class extends 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=Dg(qu(n),t),i="-";break;default:t=Lg(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=zn;zn.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,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Go(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Go();let t=BigInt(e),n=new Hn,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,os=class extends fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};nf=os;S.Enumerated=nf;os.NAME="ENUMERATED";var Gn=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){Go();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}}};Gn.NAME="sidBlock";var ss=class extends Ne{constructor({value:e=nn,...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.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 Gn;if(o>Number.MAX_SAFE_INTEGER){Go();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}};ss.NAME="ObjectIdentifierValueBlock";var of,at=class extends Ie{constructor(e={}){super(e,ss),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 jn=class extends Ut(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=$.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}}};jn.NAME="relativeSidBlock";var is=class extends Ne{constructor({value:e=nn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,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 jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};is.NAME="RelativeObjectIdentifierValueBlock";var sf,as=class extends Ie{constructor(e={}){super(e,is),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=as;S.RelativeObjectIdentifier=sf;as.NAME="RelativeObjectIdentifier";var af,Ee=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};af=Ee;S.Sequence=af;Ee.NAME="SEQUENCE";var cf,cs=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};cf=cs;S.Set=cf;cs.NAME="SET";var ls=class extends Ut(Ne){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=nn}toJSON(){return{...super.toJSON(),value:this.value}}};ls.NAME="StringValueBlock";var us=class extends ls{};us.NAME="SimpleStringValueBlock";var Ve=class extends Wo{constructor({...e}={}){super(e,us)}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}};Ve.NAME="SIMPLE STRING";var fs=class extends Ve{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}};fs.NAME="Utf8StringValueBlock";var lf,Pt=class extends fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};lf=Pt;S.Utf8String=lf;Pt.NAME="UTF8String";var hs=class extends Ve{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))}};hs.NAME="BmpStringValueBlock";var uf,ds=class extends hs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};uf=ds;S.BmpString=uf;ds.NAME="BMPString";var ps=class extends Ve{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}};ps.NAME="UniversalStringValueBlock";var ff,ms=class extends ps{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ff=ms;S.UniversalString=ff;ms.NAME="UniversalString";var hf,gs=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};hf=gs;S.NumericString=hf;gs.NAME="NumericString";var df,ys=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};df=ys;S.PrintableString=df;ys.NAME="PrintableString";var pf,ws=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};pf=ws;S.TeletexString=pf;ws.NAME="TeletexString";var mf,bs=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};mf=bs;S.VideotexString=mf;bs.NAME="VideotexString";var gf,Es=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};gf=Es;S.IA5String=gf;Es.NAME="IA5String";var yf,xs=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};yf=xs;S.GraphicString=yf;xs.NAME="GraphicString";var wf,Yn=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};wf=Yn;S.VisibleString=wf;Yn.NAME="VisibleString";var bf,vs=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};bf=vs;S.GeneralString=bf;vs.NAME="GeneralString";var Ef,As=class extends Ve{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Ef=As;S.CharacterString=Ef;As.NAME="CharacterString";var xf,Wn=class extends Yn{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]=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}}};xf=Wn;S.UTCTime=xf;Wn.NAME="UTCTime";var vf,Rs=class extends Wn{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(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}}};vf=Rs;S.GeneralizedTime=vf;Rs.NAME="GeneralizedTime";var Af,Is=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Af=Is;S.DATE=Af;Is.NAME="DATE";var Rf,_s=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Rf=_s;S.TimeOfDay=Rf;_s.NAME="TimeOfDay";var If,Ss=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};If=Ss;S.DateTime=If;Ss.NAME="DateTime";var _f,Bs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};_f=Bs;S.Duration=_f;Bs.NAME="Duration";var Sf,Cs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Sf=Cs;S.TIME=Sf;Cs.NAME="TIME";function Og(r){let{result:e}=on(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 Ug(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 Ee({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 Mg(r){let{result:e}=on(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 Fg(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new Ee({value:[new at({value:"1.2.840.113549.1.1.1"}),new tr]}),new rn({valueHex:new Ee({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 Vg=16,Za=32,Ja=1e4;async function Kg(r,e){let t=Oe.get(),o=new Ee({value:[new fe({value:0}),new Ee({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(Vg),a=await Ga(Wr,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 Ee({value:[new Dt({valueHex:i}),new fe({value:Ja}),new fe({value:Za}),new Ee({value:[new at({value:"1.2.840.113549.2.11"}),new tr]})]}),p=new Ee({value:[new at({value:"1.2.840.113549.1.5.13"}),new Ee({value:[new Ee({value:[new at({value:"1.2.840.113549.1.5.12"}),l]}),new Ee({value:[new at({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new Ee({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 $g(r,e){let t=Oe.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}=on(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Hg(s),l=await Ga(Wr,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Xn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=on(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}=on(o);n=Bf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Qa(n)}function Hg(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=Xn(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=Xn(u.valueBlock.value[1].getValue());return{cipherText:Xn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Bf(r){return Xn(r.valueBlock.value[2].getValue())}function Xn(r){return new Uint8Array(r,0,r.byteLength)}async function Cf(r){let e=await Oe.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 Oe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await qg(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 Oe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Oe.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 Oe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Oe.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([Oe.get().subtle.exportKey("jwk",r.privateKey),Oe.get().subtle.exportKey("jwk",r.publicKey)])}async function qg(r){return Oe.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 Ns(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 Jn=8192,Zn=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}},sn=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 Zn(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 Jr(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(Ns(e)>Jn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ec(e);return new sn(t.privateKey,t.publicKey)}function Gg(r){let e=rr.pkixToJwk(r);if(Ns(e)>Jn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zn(e)}async function jg(r){if(Ns(r)>Jn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ec(r);return new sn(e.privateKey,e.publicKey)}async function Yg(r){if(r>Jn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Cf(r);return new sn(e.privateKey,e.publicKey)}var ic={};be(ic,{Secp256k1PrivateKey:()=>eo,Secp256k1PublicKey:()=>Qn,generateKeyPair:()=>l0,unmarshalSecp256k1PrivateKey:()=>a0,unmarshalSecp256k1PublicKey:()=>c0});var Wg=(r,e,t)=>r&e^~r&t,Xg=(r,e,t)=>r&e^r&t^e&t,Zg=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 Yr{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+Wg(a,c,u)+Zg[l]+or[l]|0,g=(nt(n,2)^nt(n,13)^nt(n,22))+Xg(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=Co(()=>new rc);function Jg(r){let e=On(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:Qg,hexToBytes:e0}=ko,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:Qg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?e0(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),Qx=BigInt(2),Df=BigInt(3),ev=BigInt(4);function t0(r){let e=Jg(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=Po(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function r0(r){let e=On(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=r0(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 Lo(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=t0({...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=Pn(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),Tn=At;return C&&d(At)&&(Tn=g(At),hr^=1),new y(Be,Tn,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 n0(r){return{hash:r,hmac:(e,...t)=>Kn(r,e,Bo(...t)),randomBytes:jr}}function Of(r,e){let t=n=>Pf({...r,...n0(n)});return Object.freeze({...t(e),create:t})}var Ff=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Uf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),o0=BigInt(1),nc=BigInt(2),Mf=(r,e)=>(r+e/nc)/e;function s0(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=Do(Ff,void 0,void 0,{sqrt:s0}),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=-o0*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),lv=BigInt(0);var uv=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 Qn=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}},eo=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 Qn(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 Jr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function a0(r){return new eo(r)}function c0(r){return new Qn(r)}async function l0(){let r=Vf();return new eo(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 to(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 ro(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":Ln.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 v0(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 Ds(){return{forComponent(r){return A0(r)}}}function A0(r){let e=v0(`${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 R0=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,no=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")}[R0](){return`PeerId(${this.toString()})`}},_r=class extends no{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sr=class extends no{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends no{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 un(Jf.decode(r))}function un(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 I0(rt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function I0(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 fn(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 hn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var 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 hn(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 hn(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 hn(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 hn(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 _0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function _0(r){return fn(jf(r.public),Yf(r))}var S0=Math.pow(2,7),B0=Math.pow(2,14),C0=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<S0)return 1;if(r<B0)return 2;if(r<C0)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 T0(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 N0(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 k0(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 L0(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 De(r,e,t=0){return e==null&&(e=Ce(Le(r))),e instanceof Uint8Array?T0(r,e,t):N0(r,e,t)}function ft(r,e=0){return r instanceof Uint8Array?k0(r,e):L0(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 Ps(r){return!!r?.[nh]}var ye=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(Ps(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(Ps(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(Ps(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(!Ps(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 oo;(function(r){let e;r.codec=()=>(e==null&&(e=Fe((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=>Me(t,r.codec()),r.decode=t=>Ue(t,r.codec())})(oo||(oo={}));var dn=class r{static createFromProtobuf=async e=>{let t=oo.decode(e),n=await fn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=sh(n,o,s),c=await(await ro(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=oo.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 to(this.peerId.publicKey).verify(t.subarray(),this.signature)}},sh=(r,e,t)=>{let n=D(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new ye(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 Os=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,D0=15,pn=new Os;function yc(r){if(!(r.length>D0))return pn.new(r).parseWith(()=>pn.readIPv4Addr())}function wc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ah))return pn.new(r).parseWith(()=>pn.readIPv6Addr())}function Us(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ah))return pn.new(r).parseWith(()=>pn.readIPAddr())}var B1=parseInt("0xFFFF",16),C1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ms(r){return!!yc(r)}function Fs(r){return!!wc(r)}function mn(r){return!!Us(r)}var uh=Ms,F0=Fs,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(F0(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 gn={},Ec={},K0=[[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"]];K0.forEach(r=>{let e=$0(...r);Ec[e.code]=e,gn[e.name]=e});function $0(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(gn[r]!=null)return gn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var hA=W("ip4"),dA=W("ip6"),pA=W("ipcidr");function vc(r,e){switch(W(r).code){case 4:case 41:return q0(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 Y0(e);case 444:return mh(e);case 445:return mh(e);case 466:return j0(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 z0(e);case 444:return W0(e);case 445:return X0(e);case 466:return G0(e);default:return D(e,"base16")}}var xc=Object.values(Gt).map(r=>r.decoder),H0=function(){let r=xc[0].or(xc[1]);return xc.slice(2).forEach(e=>r=r.or(e)),r}();function hh(r){if(!mn(r))throw new Error("invalid ip address");return bc(r)}function q0(r){let e=fh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!mn(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(De(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 z0(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(De(e.length));return Re([t,e],t.length+e.length)}function G0(r){let e=H0.decode(r),t=Uint8Array.from(De(e.length));return Re([t,e],t.length+e.length)}function j0(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 Y0(r){let e=ft(r),t=r.slice(Le(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function W0(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 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!==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=Z0(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(De(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function Z0(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 J0=Symbol.for("nodejs.util.inspect.custom"),Bc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Q0=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Vs=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??""}`),Q0.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===gn.p2p.code&&e.push([n,o]),n===gn["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=Ks.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)}[J0](){return`Multiaddr(${this.#e})`}};var Ks=new Map;function ir(r){return!!r?.[Bc]}function se(r){return new Vs(r)}var Eh="libp2p-peer-record",xh=Uint8Array.from([3,1]);var so;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Fe((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=>Me(s,n.codec()),n.decode=s=>Ue(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Fe((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=>Me(n,r.codec()),r.decode=n=>Ue(n,r.codec())})(so||(so={}));var Tr=class r{static createFromProtobuf=e=>{let t=so.decode(e),n=un(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=so.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 ey(r){return r[Symbol.asyncIterator]!=null}function ty(r){if(ey(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var io=ty;var Tc=dt(Ah(),1);var co=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 lo(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 co;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 uo=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 yn=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:uo,...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=lo(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 co&&!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={},wn=r=>{r.addEventListener("message",e=>{wn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{wn.dispatchEvent("message",r,e)})};wn.addEventListener=(r,e)=>{ar[r]==null&&(ar[r]=[]),ar[r].push(e)};wn.removeEventListener=(r,e)=>{ar[r]!=null&&(ar[r]=ar[r].filter(t=>t===e))};wn.dispatchEvent=function(r,e,t){ar[r]!=null&&ar[r].forEach(n=>n(e,t))};var Lc=wn;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)})},oy={singleProcess:!1},Ch=r=>{if(r=Object.assign({},oy,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()=>lo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var sy=(r,e)=>{if(cr.isWorker===!0)return{readLock:cr.readLock(r,e),writeLock:cr.writeLock(r,e)};let t=new yn({concurrency:1}),n;return{async readLock(){if(n!=null)return Vc(n,e);n=new yn({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)}}},iy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Kc(r){let e=Object.assign({},iy,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]=sy(e.name,e)),Nr[e.name]}var _e={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var bn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Fe((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=>Me(i,o.codec()),o.decode=i=>Ue(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Fe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=qs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Me(i,o.codec()),o.decode=i=>Ue(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Fe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Hs.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(Hs.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=>Me(o,r.codec()),r.decode=o=>Ue(o,r.codec())})(bn||(bn={}));var Hs;(function(r){let e;r.codec=()=>(e==null&&(e=Fe((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=>Me(t,r.codec()),r.decode=t=>Ue(t,r.codec())})(Hs||(Hs={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Fe((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=>Me(t,r.codec()),r.decode=t=>Ue(t,r.codec())})(qs||(qs={}));function En(r,e){let t=bn.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),zs=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]!==zs)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]!==zs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(zs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===zs;)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 ay(this.baseNamespace())}name(){return cy(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(),...ly(e.map(t=>t.namespaces()))])}};function ay(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function cy(r){let e=r.split(":");return e[e.length-1]}function ly(r){return[].concat(...r)}var $c="/peers/";function xn(r){if(!xo(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 js(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=Gs(l,{validate:kh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gs(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=Gs([...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=Gs([...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 Gs(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 Ys(r,e,t){let n=r.toString().split("/")[2],o=qe.decode(n),s=un(o),i=t.get(s);if(i!=null)return i;let a=En(s,e);return t.set(s,a),a}function uy(r,e){return r==null?{}:{prefix:$c,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ys(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ys(n.key,n.value,e),Ys(o.key,o.value,e)))}}var Ws=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(xn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",_e.ERR_INVALID_PARAMETERS);await this.datastore.delete(xn(e))}async load(e){let t=await this.datastore.get(xn(e));return En(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(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 js(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 js(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(uy(e??{},t))){let s=Ys(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(xn(e)),n=En(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=bn.encode(t);return n!=null&&ne(s,n)?{peer:En(e,s),previous:o,updated:!1}:(await this.datastore.put(xn(e),s),{peer:En(e,s),previous:o,updated:!0})}};var Xs=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 Ws(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 io(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await dn.openAndCertify(e,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 dn.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 fy(r){return r[Symbol.asyncIterator]!=null}function hy(r){if(fy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Hc=hy;function dy(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=dy;function py(r){return r[Symbol.asyncIterator]!=null}function my(r,e){if(py(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=my;function gy(r){return r[Symbol.asyncIterator]!=null}function yy(r,e){return gy(r)?async function*(){yield*(await io(r)).sort(e)}():function*(){yield*io(r).sort(e)}()}var qc=yy;function wy(r){return r[Symbol.asyncIterator]!=null}function by(r,e){return wy(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=by;var Zs=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 Js=class extends Zs{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 vy=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 Qs=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??vy,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=Ds())}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")}},Ay=["metrics","connectionProtector"],Ry=["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"&&!Ry.includes(o)){let i=e.components[o];if(i==null&&!Ay.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}",ei=`
8
8
  (?:
9
- (?:${de}:){7}(?:${de}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
10
- (?:${de}:){6}(?:${ht}|:${de}|:)| // 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
- (?:${de}:){5}(?::${ht}|(?::${de}){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
- (?:${de}:){4}(?:(?::${de}){0,1}:${ht}|(?::${de}){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
- (?:${de}:){3}(?:(?::${de}){0,2}:${ht}|(?::${de}){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
- (?:${de}:){2}(?:(?::${de}){0,3}:${ht}|(?::${de}){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
- (?:${de}:){1}(?:(?::${de}){0,4}:${ht}|(?::${de}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
16
- (?::(?:(?::${de}){0,5}:${ht}|(?::${de}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
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
17
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
18
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),ky=new RegExp(`(?:^${ht}$)|(?:^${ei}$)`),Ly=new RegExp(`^${ht}$`),Dy=new RegExp(`^${ei}$`),Jc=r=>r&&r.exact?ky:new RegExp(`(?:${ur(r)}${ht}${ur(r)})|(?:${ur(r)}${ei}${ur(r)})`,"g");Jc.v4=r=>r&&r.exact?Ly:new RegExp(`${ur(r)}${ht}${ur(r)}`,"g");Jc.v6=r=>r&&r.exact?Dy:new RegExp(`${ur(r)}${ei}${ur(r)}`,"g");var Yh=Jc;var Qh=dt(Xh(),1),{isValid:Py,parse:Oy}=Qh.default,My=["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"],Uy=My.map(r=>new Jh.Netmask(r));function Fy(r){for(let e of Uy)if(e.contains(r))return!0;return!1}function Zh(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 ed=r=>{if(Py(r)){let e=Oy(r);if(e.kind()==="ipv4")return Fy(e.toNormalizedString());if(e.kind()==="ipv6")return Zh(r)}else if(xn(r)&&Yh.v6().test(r))return Zh(r)};var ri=ed;function td(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ri(`${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 Vy=r=>r.toString().split("/").slice(1),fo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),ae=r=>({match:e=>fo(t=>t===r).match(e),pattern:r}),si=()=>({match:r=>fo(e=>typeof e=="string").match(r),pattern:"{string}"}),rd=()=>({match:r=>fo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),tt=()=>({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}"}),ni=()=>({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 we(...r){function e(o){let s=Vy(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 el=ce(ae("dns4"),si()),tl=ce(ae("dns6"),si()),rl=ce(ae("dnsaddr"),si()),nd=ce(ae("dns"),si()),B_=we(el),C_=we(tl),T_=we(rl),N_=we(vt(nd,rl,el,tl)),od=ce(ae("ip4"),fo(Us)),sd=ce(ae("ip6"),fo(Fs)),id=vt(od,sd),ho=vt(id,nd,el,tl,rl),k_=we(ho),L_=we(od),D_=we(sd),P_=we(id),ii=ce(ho,ae("tcp"),rd()),po=ce(ho,ae("udp"),rd()),Ky=vt(ii,po),O_=we(ii),M_=we(po),nl=ce(po,ae("quic")),ai=ce(po,ae("quic-v1")),$y=vt(nl,ai),U_=we(nl),F_=we(ai),Qc=vt(ho,ii,po,nl,ai),ad=vt(ce(Qc,ae("ws"),xt(tt()))),V_=we(ad),cd=vt(ce(Qc,ae("wss"),xt(tt())),ce(Qc,ae("tls"),ae("ws"),xt(tt()))),K_=we(cd),ld=ce(Ky,ae("webrtc-direct"),ni(),xt(ni()),xt(tt())),$_=we(ld),ud=ce(ai,ae("webtransport"),ni(),ni(),xt(tt())),H_=we(ud),oi=vt(ad,cd,ce(ii,xt(tt())),ce($y,xt(tt())),ce(ho,xt(tt())),ld,ud,tt()),q_=we(oi),Hy=ce(oi,ae("p2p-circuit"),tt()),ol=we(Hy),qy=vt(ce(oi,ae("p2p-circuit"),ae("webrtc"),tt()),ce(oi,ae("webrtc"),xt(tt())),ae("webrtc")),z_=we(qy);function sl(r){try{let{address:e}=r.nodeAddress();return!!ri(e)}catch{return!0}}function zy(r,e){let t=sl(r.multiaddr),n=sl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Gy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function jy(r,e){let t=ol.exactMatch(r.multiaddr),n=ol.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Bn(r,e){let t=zy(r,e);if(t!==0)return t;let n=jy(r,e);return n!==0?n:Gy(r,e)}var al=dt(hc(),1),cl=dt(dd(),1);function ci(r,e,t){return`${r}?name=${e}&type=${t}`}async function pd(r,e){return await(await fetch(r,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function Or(r,e){return`${e}_${r}`}var il=Object.assign((0,al.default)("dns-over-http-resolver"),{error:(0,al.default)("dns-over-http-resolver:error")}),ll=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new cl.default({max:e?.maxCache??100}),this._TXTcache=new cl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??pd,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(Or(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(ci(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(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.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(Or(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(ci(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(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.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(Or(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(ci(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(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.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()}},md=ll;var gd=md;var{code:Jy}=W("dnsaddr");async function Cn(r,e={}){let t=new gd;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,o]=r.stringTuples().find(([a])=>a===Jy)??[];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 Id=dt(Rd(),1),fi=Id.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 C;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(C||(C={}));var ow={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Cn},addressSorter:Bn},transportManager:{faultTolerance:Kt.FATAL_ALL}};function _d(r){let e=fi(ow,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,C.ERR_PROTECTOR_REQUIRED);return e}var Sd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},sw=new WeakMap;function iw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Sd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Sd())},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}),sw.set(l,()=>{c(s),s=null,i()}),l}}var aw=iw(),Bd=aw;var hi=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 fl}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 Bd(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)}},fl=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 di(r){if(Eo(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:he(t),r.forEach(n=>{if(!ar(n))throw new E("Invalid Multiaddr",C.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",C.ERR_INVALID_PARAMETERS)}else{let s=he(o);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",C.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var pi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},kn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pi(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 pi(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 hl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mi(r={}){return cw(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 cw(r,e){e=e??{};let t=e.onEnd,n=new kn,o,s,i,a=pe(),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=pe()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new kn,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 kn,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 hl)},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 dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function gi(r,e,t,n){let o=new dl(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 yi=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 Ln(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new yi(t?.errorMessage,t?.errorCode));let n,o=new yi(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 wi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=pe(),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 lw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var bi=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=lw(),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 wi(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 Ln(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 uw(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 Dn=class extends pr{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=uw(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 bi(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 gi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await gi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gi(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=mi({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 Ei=class extends Dn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xi="last-dial-failure";var vi=5,Ai=100,Ri=50,Cd=1e3*60*7;var Mr={minConnections:vi,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Cd,autoDialDiscoveredPeersDebounce:10},Ii=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Mr.minConnections,this.autoDialPriority=t.autoDialPriority??Mr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Mr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Mr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Mr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Mr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ei({concurrency:t.autoDialConcurrency??Mr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new et(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 He;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(xi);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 Td={maxConnections:Ai,allow:[]},_i=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Td.maxConnections,this.allow=t.allow??Td.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 He;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 Nd(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 yl(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await dw(r,e),i=(await Promise.all(n.map(async a=>yl(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 dw(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 Si={addressSorter:Bn,maxParallelDials:Ri,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:Cn}},Bi=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Si.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Si.maxPeerAddrsToDial,this.dialTimeout=t.dialTimeout??Si.dialTimeout,this.connections=t.connections??new He,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??{}))Ks.set(n,o);this.queue=new Dn({concurrency:t.maxParallelDials??Si.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}=di(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",C.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(p.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",p.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",p.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[xi]: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,vo);l.push(h)}}throw l.length===1?l[0]:new xo(l,"All multiaddr dials failed",C.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=Nd([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",C.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",C.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:p})=>p.toString()))}catch(l){if(l.code!==C.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:p})=>p.toString())),o.push(...l.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(l){l.code!==C.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let p=await yl(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",C.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new E("The connection gater denied all addresses in the dial request",C.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}};var gw=50,Ur={minConnections:vi,maxConnections:Ai,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ci=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ur.maxConnections;let n=t.minConnections??Ur.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",C.ERR_INVALID_PARAMETERS);this.connections=new He,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??Ur.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new hi({points:t.inboundConnectionThreshold??Ur.inboundConnectionThreshold,duration:1}),this.autoDial=new Ii({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Ur.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Ur.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Ur.autoDialMaxQueueLength}),this.connectionPruner=new _i({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Bi(e,{addressSorter:t.addressSorter??Bn,maxParallelDials:t.maxParallelDials??Ri,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:Cn},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(Vl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new E("Not started",C.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=di(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??gw}),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 yw(r){return r[Symbol.asyncIterator]!=null}function ww(...r){let e=[];for(let t of r)yw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=mi({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 mo=ww;var Ti=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",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new et;for await(let s of mo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",C.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Ni=globalThis.CustomEvent??Event;async function*El(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=pe(),a=pe(),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=pe(),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 Ni("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Ni("task-complete"))})}c=!0,o.dispatchEvent(new Ni("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ni("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=pe(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var ki=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",C.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",C.ERR_FIND_SELF);let n=this,o=mo(...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,C.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new et;for await(let s of El(async function*(){let i=mo(...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 xl=32,vl=64,Li=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}`,C.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,C.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=fi.bind({ignoreUndefined:!0})({maxInboundStreams:xl,maxOutboundStreams:vl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new E("invalid topology",C.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.onDisconnect?.(t)}}).catch(n=>{n.code!==C.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.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 Al=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 kd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Al({name:e,metrics:t}):n=new Map,n}var Di=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=kd({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",C.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,C.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,C.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=C.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}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",C.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.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`,C.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Kt.FATAL_ALL)throw new E(n,C.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ne="/multistream/1.0.0";var Rl=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=pe(),this.haveNext=pe()}[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=pe(),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=pe(),await Ln(this.needNext.promise,t?.signal,t)}};function Ld(){return new Rl}var Pi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Il=class extends Pi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Dd(r,e){let t=Ld();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 xe;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Il("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 xe:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Pi("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 Oi(r){return r[Symbol.asyncIterator]!=null}var Mi=r=>{let e=Me(r),t=Le(e);return qe(r,t),Mi.bytes=e,t};Mi.bytes=0;function Fr(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 Oi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Fr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mi;return new xe(t(r.byteLength),r)};var Pn=dt(Wc(),1);var bw=8,Ew=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Sl=r=>{let e=ft(r);return Sl.bytes=Me(e),e};Sl.bytes=0;function _l(r,e){let t=new xe,n=Vr.LENGTH,o=-1,s=e?.lengthDecoder??Sl,i=e?.maxLengthLength??bw,a=e?.maxDataLength??Ew;function*c(){for(;t.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(t),o<0)throw(0,Pn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Pn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Vr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Pn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Vr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Vr.LENGTH}}}return Oi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Pn.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,Pn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}_l.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 _l(n,{...e??{},onLength:s=>{t=s}})};var Ui=class extends Error{code;constructor(e,t){super(e),this.code=t}},Pd=r=>ft(r);Pd.bytes=0;function go(r,e={}){let t=Dd(r,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Me(e.maxDataLength)),{read:async o=>{let s=-1,i=new xe,a=e?.lengthDecoder??Pd;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 Ui("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new Ui("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(s,o)},write:async(o,s)=>{await t.write(Fr.single(o,e),s)},writeV:async(o,s)=>{let i=new xe(...o.map(a=>Fr.single(a,e)));await t.write(i,s)},unwrap:()=>t.unwrap()}}var vw=D(`
19
- `);async function Kr(r,e,t){await r.write(e,t)}async function Od(r,e,t){await r.writeV(e,t)}async function Aw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==vw[0])throw e.log.error("Invalid mss message - missing newline",t),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function hr(r,e){let t=await Aw(r,e);return V(t.subarray())}async function yo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Rw(r,e[0],t);let n=go(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"]',Ne,o);let s=D(`${Ne}
18
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Iy=new RegExp(`(?:^${ht}$)|(?:^${ei}$)`),_y=new RegExp(`^${ht}$`),Sy=new RegExp(`^${ei}$`),Wc=r=>r&&r.exact?Iy:new RegExp(`(?:${lr(r)}${ht}${lr(r)})|(?:${lr(r)}${ei}${lr(r)})`,"g");Wc.v4=r=>r&&r.exact?_y:new RegExp(`${lr(r)}${ht}${lr(r)}`,"g");Wc.v6=r=>r&&r.exact?Sy:new RegExp(`${lr(r)}${ei}${lr(r)}`,"g");var qh=Wc;var Wh=dt(Gh(),1),{isValid:By,parse:Cy}=Wh.default,Ty=["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"],Ny=Ty.map(r=>new Yh.Netmask(r));function ky(r){for(let e of Ny)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(By(r)){let e=Cy(r);if(e.kind()==="ipv4")return ky(e.toNormalizedString());if(e.kind()==="ipv6")return jh(r)}else if(mn(r)&&qh.v6().test(r))return jh(r)};var ri=Xh;function Zh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ri(`${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 Ly=r=>r.toString().split("/").slice(1),ho=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),ae=r=>({match:e=>ho(t=>t===r).match(e),pattern:r}),si=()=>({match:r=>ho(e=>typeof e=="string").match(r),pattern:"{string}"}),Jh=()=>({match:r=>ho(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}"}),ni=()=>({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 we(...r){function e(o){let s=Ly(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"),si()),Jc=ce(ae("dns6"),si()),Qc=ce(ae("dnsaddr"),si()),Qh=ce(ae("dns"),si()),HR=we(Zc),qR=we(Jc),zR=we(Qc),GR=we(vt(Qh,Qc,Zc,Jc)),ed=ce(ae("ip4"),ho(Ms)),td=ce(ae("ip6"),ho(Fs)),rd=vt(ed,td),po=vt(rd,Qh,Zc,Jc,Qc),jR=we(po),YR=we(ed),WR=we(td),XR=we(rd),ii=ce(po,ae("tcp"),Jh()),mo=ce(po,ae("udp"),Jh()),Dy=vt(ii,mo),ZR=we(ii),JR=we(mo),el=ce(mo,ae("quic")),ai=ce(mo,ae("quic-v1")),Py=vt(el,ai),QR=we(el),eI=we(ai),Xc=vt(po,ii,mo,el,ai),nd=vt(ce(Xc,ae("ws"),xt(et()))),tI=we(nd),od=vt(ce(Xc,ae("wss"),xt(et())),ce(Xc,ae("tls"),ae("ws"),xt(et()))),rI=we(od),sd=ce(Dy,ae("webrtc-direct"),ni(),xt(ni()),xt(et())),nI=we(sd),id=ce(ai,ae("webtransport"),ni(),ni(),xt(et())),oI=we(id),oi=vt(nd,od,ce(ii,xt(et())),ce(Py,xt(et())),ce(po,xt(et())),sd,id,et()),sI=we(oi),Oy=ce(oi,ae("p2p-circuit"),et()),tl=we(Oy),Uy=vt(ce(oi,ae("p2p-circuit"),ae("webrtc"),et()),ce(oi,ae("webrtc"),xt(et())),ae("webrtc")),iI=we(Uy);function rl(r){try{let{address:e}=r.nodeAddress();return!!ri(e)}catch{return!0}}function My(r,e){let t=rl(r.multiaddr),n=rl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Fy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Vy(r,e){let t=tl.exactMatch(r.multiaddr),n=tl.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vn(r,e){let t=My(r,e);if(t!==0)return t;let n=Vy(r,e);return n!==0?n:Fy(r,e)}var ol=dt(uc(),1),sl=dt(ld(),1);function ci(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(ci(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(ci(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(ci(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:zy}=W("dnsaddr");async function An(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===zy)??[];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),fi=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 Zy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:An},addressSorter:vn},transportManager:{faultTolerance:Kt.FATAL_ALL}};async function vd(r){let e=fi(Zy,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 fn(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},Jy=new WeakMap;function Qy({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}),Jy.set(l,()=>{c(s),s=null,i()}),l}}var ew=Qy(),Rd=ew;var hi=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 di(r){if(xo(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 pi=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}},_n=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pi(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 pi(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 mi(r={}){return tw(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 tw(r,e){e=e??{};let t=e.onEnd,n=new _n,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 _n,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 _n,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 gi(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 yi=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 Sn(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new yi(t?.errorMessage,t?.errorCode));let n,o=new yi(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 wi=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 rw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var bi=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=rw(),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 wi(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 Sn(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 nw(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 Bn=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=nw(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 bi(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 gi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await gi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gi(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=mi({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 Ei=class extends Bn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xi="last-dial-failure";var vi=5,Ai=100,Ri=50,Id=1e3*60*7;var Pr={minConnections:vi,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Id,autoDialDiscoveredPeersDebounce:10},Ii=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 Ei({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(xi);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:Ai,allow:[]},_i=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 iw(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 iw(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 Si={addressSorter:vn,maxParallelDials:Ri,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:An}},Bi=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Si.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Si.maxPeerAddrsToDial,this.dialTimeout=t.dialTimeout??Si.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??{}))Ks.set(n,o);this.queue=new Bn({concurrency:t.maxParallelDials??Si.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}=di(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:{[xi]: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,Ao);l.push(h)}}throw l.length===1?l[0]:new vo(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 lw=50,Or={minConnections:vi,maxConnections:Ai,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ci=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 hi({points:t.inboundConnectionThreshold??Or.inboundConnectionThreshold,duration:1}),this.autoDial=new Ii({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 _i({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Bi(e,{addressSorter:t.addressSorter??vn,maxParallelDials:t.maxParallelDials??Ri,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:An},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}=di(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??lw}),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 uw(r){return r[Symbol.asyncIterator]!=null}function fw(...r){let e=[];for(let t of r)uw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=mi({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 go=fw;var Ti=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 go(...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 Ni=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 Ni("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Ni("task-complete"))})}c=!0,o.dispatchEvent(new Ni("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ni("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 ki=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=go(...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=go(...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,Li=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=fi.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 Di=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 Sn(this.needNext.promise,t?.signal,t)}};function Cd(){return new xl}var Pi=class extends Error{code;constructor(e,t){super(e),this.code=t}},vl=class extends Pi{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 ye;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 ye:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Pi("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 Oi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function yo(r,e={}){let t=Td(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength));let n=e?.lengthDecoder??ft,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new ye;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 Oi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Oi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new ye(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ye(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var hw=D(`
19
+ `);async function Ur(r,e,t){await r.write(e,t)}async function Nd(r,e,t){await r.writeV(e,t)}async function dw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==hw[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 dw(r,e);return V(t.subarray())}async function wo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return pw(r,e[0],t);let n=yo(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
20
  `),i=D(`${o}
21
- `);await Od(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await hr(n,t);if(t.log.trace('select: read "%s"',a),a===Ne&&(t.log.trace("select: reading protocol response"),a=await hr(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Kr(n,D(`${c}
22
- `),t),t.log.trace("select: reading protocol response");let u=await hr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Rw(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=pe(),c=!1,u=!1,f=pe(),l=!1,p=!1,h=pe(),d=go({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',Ne,e,v.byteLength);let R=`${e}
23
- `;yield new xe(Uint8Array.from([19]),D(`${Ne}
24
- `),qe(R.length),D(R),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ne,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',Ne,e),await d.writeV([D(`${Ne}
21
+ `);await Nd(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 Ur(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 pw(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=yo({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 ye(Uint8Array.from([19]),D(`${Se}
24
+ `),De(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}
25
25
  `),D(`${e}
26
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ne,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 hr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===Ne&&(w=await hr(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 Ln(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}async function wo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=go(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await hr(n,t);if(t.log.trace('handle: read "%s"',o),o===Ne){t.log.trace('handle: respond with "%s" for "%s"',Ne,o),await Kr(n,D(`${Ne}
27
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Ne,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Kr(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 xe(...e.map(i=>Fr.single(D(`${i}
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 Sn(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}function Ui(r){return r[Symbol.asyncIterator]!=null}var Mi=r=>{let e=Le(r),t=Ce(e);return De(r,t),Mi.bytes=e,t};Mi.bytes=0;function Fi(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)}()}Fi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mi;return new ye(t(r.byteLength),r)};var Cn=dt(Gc(),1);var mw=8,gw=1024*1024*4,Mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Mr||(Mr={}));var Il=r=>{let e=ft(r);return Il.bytes=Le(e),e};Il.bytes=0;function Rl(r,e){let t=new ye,n=Mr.LENGTH,o=-1,s=e?.lengthDecoder??Il,i=e?.maxLengthLength??mw,a=e?.maxDataLength??gw;function*c(){for(;t.byteLength>0;){if(n===Mr.LENGTH)try{if(o=s(t),o<0)throw(0,Cn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Cn.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,Cn.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,Cn.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,Cn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Rl.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 Rl(n,{...e??{},onLength:s=>{t=s}})};async function bo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=yo(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 Ur(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 Ur(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 ye(...e.map(i=>Fi.single(D(`${i}
29
29
  `))),D(`
30
- `));t.log.trace('handle: respond with "%s" for %s',e,o),await Kr(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 Kr(n,D(`na
31
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var _w=500,Bl=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";[Fl]=!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(_w);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 Ud(r){return new Bl(r)}var Bw=3e4;function Cw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return xl}function Tw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??vl}function Fd(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}`,C.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",C.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",vo))};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",C.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),l=await p.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let p={...l,...o};await this.shouldBlockConnection(s,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new E("inbound connection that skipped encryption must have a peer id",C.ERR_INVALID_MULTIADDR);let h=he(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=he(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new E("Encryption was skipped but no peer id was passed",C.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await wo(d,g,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let w=Cw(y,this.components.registrar);if(Fd(y,"inbound",l)===w){let A=new E(`Too many inbound protocol streams for protocol "${y}" - limit ${w}`,C.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",C.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(Bw);Xe(1/0,v),g={...g,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:y,protocol:w}=await yo(m,d,{...g,log:m.log,yieldBytes:!0});m.log("selected protocol %s",w);let b=Tw(w,this.components.registrar,g);if(Fd(w,"outbound",l)>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - limit ${b}`,C.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),C.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let p=o.timeline;o.timeline=new Proxy(p,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&p.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(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",C.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Ud({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 wo(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,C.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await yo(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,C.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await yo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new E(String(o),C.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await wo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),C.ERR_MUXER_UNAVAILABLE)}}};var Vd="1.1.2",Kd="libp2p";var Cl=class extends pr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new pr,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??Ls(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=zh({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:Kd,version:Vd},logger:this.logger,events:t,datastore:e.datastore??new Js,connectionGater:td(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Xs(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 Di(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ci(this.components,e.connectionManager)),this.configureComponent("registrar",new Li(this.components)),this.configureComponent("addressManager",new Qs(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 ki(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 Ti(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 et;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new E("no protocols were provided to open a stream",C.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("no protocols were provided to open a stream",C.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ar(e)&&(e=he(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==C.ERR_NOT_FOUND)throw s}let n=ge([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return to(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(C.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function $d(r={}){return r.peerId??=await sh(),new Cl(_d(r))}async function kw(r={}){let e=await $d(r);return r.start!==!1&&await e.start(),e}return rp(Lw);})();
30
+ `));t.log.trace('handle: respond with "%s" for %s',e,o),await Ur(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 Ur(n,D(`na
31
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var ww=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(ww);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 Ld(r){return new _l(r)}var bw=3e4;function Ew(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 xw(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 Dd(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",Ao))};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 bo(d,g,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let w=Ew(y,this.components.registrar);if(Dd(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(bw);Xe(1/0,v),g={...g,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:y,protocol:w}=await wo(m,d,{...g,log:m.log,yieldBytes:!0});m.log("selected protocol %s",w);let b=xw(w,this.components.registrar,g);if(Dd(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=Ld({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await bo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection 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 wo(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 wo(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 bo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var Pd="1.2.0-08f6f607d",Od="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??Ds(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Kh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Od,version:Pd},logger:this.logger,events:t,datastore:e.datastore??new Js,connectionGater:Zh(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Xs(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 Di(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ci(this.components,e.connectionManager)),this.configureComponent("registrar",new Li(this.components)),this.configureComponent("addressManager",new Qs(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 ki(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 Ti(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 to(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 Ud(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 ro(e.privateKey),new Sl(await vd(r))}async function Aw(r={}){let e=await Ud(r);return r.start!==!1&&await e.start(),e}return Zd(Rw);})();
32
32
  /*! Bundled license information:
33
33
 
34
34
  pvtsutils/build/index.js: