@helia/libp2p 2.1.3-16fc74d3 → 2.1.3-47363dd2
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 +2 -2
- package/dist/index.min.js.map +2 -2
- package/package.json +3 -3
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaLibp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaLibp2P=(()=>{var gS=Object.create;var Ru=Object.defineProperty;var yS=Object.getOwnPropertyDescriptor;var bS=Object.getOwnPropertyNames;var wS=Object.getPrototypeOf,ES=Object.prototype.hasOwnProperty;var Ir=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},fe=(r,e)=>{for(var t in e)Ru(r,t,{get:e[t],enumerable:!0})},M6=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bS(e))!ES.call(r,s)&&s!==t&&Ru(r,s,{get:()=>e[s],enumerable:!(n=yS(e,s))||n.enumerable});return r};var oi=(r,e,t)=>(t=r!=null?gS(wS(r)):{},M6(e||!r||!r.__esModule?Ru(t,"default",{value:r,enumerable:!0}):t,r)),xS=r=>M6(Ru({},"__esModule",{value:!0}),r);var l7=Ir((D$,c7)=>{"use strict";function mC(r){return r>=55296&&r<=56319}function gC(r){return r>=56320&&r<=57343}c7.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var s=t.length,o=0,i,a,c=0;c<s;c+=1){if(i=t.charCodeAt(c),a=t[c],mC(i)&&gC(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var d7=Ir((N$,u7)=>{"use strict";function yC(r){return r>=55296&&r<=56319}function bC(r){return r>=56320&&r<=57343}u7.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,s=null,o=null,i=0;i<t;i++)s=e.charCodeAt(i),bC(s)?o!=null&&yC(o)?n+=1:n+=3:s<=127?n+=1:s>=128&&s<=2047?n+=2:s>=2048&&s<=65535&&(n+=3),o=s;return n}});var h7=Ir((O$,f7)=>{"use strict";var wC=l7(),EC=d7();f7.exports=wC.bind(null,EC)});var g7=Ir((M$,m7)=>{"use strict";var xC=h7(),vC=/[\/\?<>\\:\*\|"]/g,SC=/[\x00-\x1f\x80-\x9f]/g,AC=/^\.+$/,TC=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function CC(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function p7(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(vC,e).replace(SC,e).replace(AC,e).replace(TC,e);return t=CC(t,e),xC(t,255)}m7.exports=function(r,e){var t=e&&e.replacement||"",n=p7(r,t);return t===""?n:p7(n,"")}});var y7=Ir(Ni=>{"use strict";var _C="[object ArrayBuffer]",Bn=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===_C}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),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])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 s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},am="string",RC=/^[0-9a-f\s]+$/i,PC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,LC=/^[a-zA-Z0-9-_]+$/,Cd=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Bn.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},vr=class{static toString(e,t=!1){let n=Bn.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},Id=class r{static isHex(e){return typeof e===am&&RC.test(e)}static isBase64(e){return typeof e===am&&PC.test(e)}static isBase64Url(e){return typeof e===am&&LC.test(e)}static ToString(e,t="utf8"){let n=Bn.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 vr.toString(n,!0);case"utf16":case"utf16be":return vr.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 vr.fromString(e,!0);case"utf16":case"utf16be":return vr.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Bn.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 Cd.fromString(e);case"utf16":case"utf16be":return vr.fromString(e);case"utf16le":case"usc2":return vr.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 Cd.toString(e);case"utf16":case"utf16be":return vr.toString(e);case"utf16le":case"usc2":return vr.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 s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Bn.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Bn.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];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 s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return vr.toString(e,t)}static FromUtf16String(e,t=!1){return vr.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,"")||""}};Id.DEFAULT_UTF8_ENCODING="utf8";function kC(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function DC(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function NC(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}Ni.BufferSourceConverter=Bn;Ni.Convert=Id;Ni.assign=kC;Ni.combine=DC;Ni.isEqual=NC});var _m=Ir(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.Netmask4Impl=void 0;Hi.ip2long=Vi;Hi.long2ip=dn;function dn(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[e,t,n,s].join(".")}var OI=48,MI=97,BI=65;function UI(r){let e=0,t=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,t=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,t=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)e=e*t+(r.charCodeAt(s)-OI)>>>0;else if(t===16)if("a"<=r[s]&&r[s]<="f")e=e*t+(10+r.charCodeAt(s)-MI)>>>0;else if("A"<=r[s]&&r[s]<="F")e=e*t+(10+r.charCodeAt(s)-BI)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[e,s]}function Vi(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=UI(r);r=r.substring(s),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var Im=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let s=e.split("/",2);e=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Vi(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Vi(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=dn(this.netLong),this.mask=dn(this.maskLong),this.hostmask=dn(~this.maskLong),this.first=this.bitmask<=30?dn(this.netLong+1):this.base,this.last=this.bitmask<=30?dn(this.netLong+this.size-2):dn(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?dn(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(Vi(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(dn(this.netLong+this.size*e),this.mask)}forEach(e){let t=Vi(this.first),n=Vi(this.last),s=0;for(;t<=n;)e(dn(t),t,s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Hi.Netmask4Impl=Im});var Ly=Ir(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.Netmask6Impl=void 0;qi.ip6bigint=Pm;qi.bigint2ip6=No;var FI=_m(),Rm=(1n<<128n)-1n;function Pm(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),s=(0,FI.ip2long)(n),o=r.substring(0,t+1)+"0:0";return Py(o)&~0xffffffffn|BigInt(s)}return Py(r)}function Py(r){let e=r.indexOf("::"),t;if(e!==-1){let s=r.substring(0,e),o=r.substring(e+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let s=0;s<8;s++){let o=t[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function No(r){if(r<0n||r>Rm)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)e[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(t=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(t=s,n=o),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var Lm=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let s=e.indexOf("/");s!==-1?(n=parseInt(e.substring(s+1),10),e=e.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Rm>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Pm(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=No(this.netBigint),this.mask=No(this.maskBigint),this.hostmask=No(~this.maskBigint&Rm),this.first=this.base,this.last=No(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(Pm(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(No(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;t<=s;)e(No(t),Number(t),o),o++,t++}toString(){return this.base+"/"+this.bitmask}};qi.Netmask6Impl=Lm});var ky=Ir(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.long2ip=Ts.ip2long=Ts.Netmask=void 0;var _f=_m();Object.defineProperty(Ts,"ip2long",{enumerable:!0,get:function(){return _f.ip2long}});Object.defineProperty(Ts,"long2ip",{enumerable:!0,get:function(){return _f.long2ip}});var $I=Ly(),km=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new $I.Netmask6Impl(e,t):this._impl=new _f.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof _f.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};Ts.Netmask=km});var J9=Ir((vX,_3)=>{"use strict";var kR=Object.prototype.hasOwnProperty,qt="~";function xl(){}Object.create&&(xl.prototype=Object.create(null),new xl().__proto__||(qt=!1));function DR(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Z9(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new DR(t,n||r,s),i=qt?qt+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Xh(r,e){--r._eventsCount===0?r._events=new xl:delete r._events[e]}function Nt(){this._events=new xl,this._eventsCount=0}Nt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)kR.call(t,n)&&e.push(qt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Nt.prototype.listeners=function(e){var t=qt?qt+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};Nt.prototype.listenerCount=function(e){var t=qt?qt+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(e,t,n,s,o,i){var a=qt?qt+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){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,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};Nt.prototype.on=function(e,t,n){return Z9(this,e,t,n,!1)};Nt.prototype.once=function(e,t,n){return Z9(this,e,t,n,!0)};Nt.prototype.removeListener=function(e,t,n,s){var o=qt?qt+e:e;if(!this._events[o])return this;if(!t)return Xh(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Xh(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Xh(this,o)}return this};Nt.prototype.removeAllListeners=function(e){var t;return e?(t=qt?qt+e:e,this._events[t]&&Xh(this,t)):(this._events=new xl,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=qt;Nt.EventEmitter=Nt;typeof _3<"u"&&(_3.exports=Nt)});var rb=Ir((qX,tb)=>{tb.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var bx=Ir(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.parseCookie=gx;Cn.parse=gx;Cn.stringifyCookie=sN;Cn.stringifySetCookie=E0;Cn.serialize=E0;Cn.parseSetCookie=oN;Cn.stringifySetCookie=E0;Cn.serialize=E0;var px=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mx=/^[\u0021-\u003A\u003C-\u007E]*$/,JD=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,eN=/^[\u0020-\u003A\u003D-\u007E]*$/,tN=/^-?\d+$/,rN=Object.prototype.toString,nN=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function gx(r,e){let t=new nN,n=r.length;if(n<2)return t;let s=e?.decode||yx,o=0;do{let i=z4(r,o,n);if(i===-1)break;let a=q4(r,o,n);if(i>a){o=r.lastIndexOf(";",i-1)+1;continue}let c=Ks(r,o,i);t[c]===void 0&&(t[c]=s(Ks(r,i+1,a))),o=a+1}while(o<n);return t}function sN(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let s of Object.keys(r)){let o=r[s];if(o===void 0)continue;if(!px.test(s))throw new TypeError(`cookie name is invalid: ${s}`);let i=t(o);if(!mx.test(i))throw new TypeError(`cookie val is invalid: ${o}`);n.push(`${s}=${i}`)}return n.join("; ")}function E0(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},o=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!px.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?o(n.value):"";if(!mx.test(i))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+i;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!JD.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!eN.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!iN(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function oN(r,e){let t=e?.decode||yx,n=r.length,s=q4(r,0,n),o=z4(r,0,s),i=o===-1?{name:"",value:t(Ks(r,0,s))}:{name:Ks(r,0,o),value:t(Ks(r,o+1,s))},a=s+1;for(;a<n;){let c=q4(r,a,n),l=z4(r,a,c),u=l===-1?Ks(r,a,c):Ks(r,a,l),d=l===-1?void 0:Ks(r,l+1,c);switch(u.toLowerCase()){case"httponly":i.httpOnly=!0;break;case"secure":i.secure=!0;break;case"partitioned":i.partitioned=!0;break;case"domain":i.domain=d;break;case"path":i.path=d;break;case"max-age":d&&tN.test(d)&&(i.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(i.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(i.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(i.sameSite=p);break}a=c+1}return i}function q4(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function z4(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Ks(r,e,t){let n=e,s=t;do{let o=r.charCodeAt(n);if(o!==32&&o!==9)break}while(++n<s);for(;s>n;){let o=r.charCodeAt(s-1);if(o!==32&&o!==9)break;s--}return r.slice(n,s)}function yx(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function iN(r){return rN.call(r)==="[object Date]"}});var mO={};fe(mO,{libp2pDefaults:()=>Ip,withLibp2p:()=>pO,withLibp2pLight:()=>fS});var B6=Symbol.for("@libp2p/connection");var Qs=Symbol.for("@libp2p/content-routing");var jt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},ii=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ai=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},v=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_r=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},qa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},za=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Zs=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},ci=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Rr=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},li=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Qr=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Js=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Ue=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ui=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Zr=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Pu=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Lu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ku=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},le=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},eo=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},as=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Pr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var cs=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},to=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Ga=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Du=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},di=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Lr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Nu=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},ls=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Ou=class extends ls{constructor(e,t){super(!0,e,t)}},Mu=class extends ls{constructor(e,t){super(!1,e,t)}};var ro=Symbol.for("@libp2p/peer-discovery");var Bu=Symbol.for("@libp2p/peer-id");function Jr(r){return!!r?.[Bu]}var no=Symbol.for("@libp2p/peer-routing");var so="keep-alive";function Uu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function kr(...r){let e=[];for(let t of r)Uu(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function en(...r){let e=[];for(let t of r)Uu(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var us=Symbol.for("@libp2p/transport");var Wa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Wa||(Wa={}));function vS(r){return typeof r?.handleEvent=="function"}function SS(r){return r===!0||r===!1}function AS(r){return SS(r)?r:r?.capture??!1}function _p(r){let e={capture:AS(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function U6(r,e){return _p(r).capture===_p(e).capture}var ue=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=_p(n);if(s?.signal?.aborted===!0)return;let o=l=>{s.once&&this.removeEventListener(e,t,s),vS(t)?t.handleEvent(l):t(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==t?!1:U6(l.options,s)))return;super.addEventListener(e,o,s);let c=()=>{this.removeEventListener(e,t,s)};s.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:o,options:s,onAbort:c})}removeEventListener(e,t,n){let s=this.#e.get(e);if(s==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,s.filter(o=>o.callback===t&&U6(o.options,n)?(super.removeEventListener(e,o.wrapper,n),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ye=Symbol.for("@libp2p/service-capabilities"),ir=Symbol.for("@libp2p/service-dependencies");var Dp={};fe(Dp,{base58btc:()=>Ie,base58flickr:()=>kS});var JO=new Uint8Array(0);function $6(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 yr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return oo(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return oo(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function K6(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var F6=4096;function V6(r){let e=r.length;if(e<=F6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=F6));return t}function TS(r){return r?.buffer instanceof ArrayBuffer}function oo(r){return TS(r)?r:r.slice()}function CS(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),l!==a&&(n[l]=o)}}var u=r.length,d=r.charAt(0),f=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function p(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var b=0,w=0,x=0,S=m.length;x!==S&&m[x]===0;)x++,b++;for(var C=(S-x)*h+1>>>0,I=new Uint8Array(C);x!==S;){for(var L=m[x],P=0,B=C-1;(L!==0||P<w)&&B!==-1;B--,P++)L+=256*I[B]>>>0,I[B]=L%u>>>0,L=L/u>>>0;if(L!==0)throw new Error("Non-zero carry");w=P,x++}for(var W=C-w;W!==C&&I[W]===0;)W++;for(var G=d.repeat(b);W<C;++W)G+=r.charAt(I[W]);return G}function g(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var w=0,x=0;m[b]===d;)w++,b++;for(var S=(m.length-b)*f+1>>>0,C=new Uint8Array(S);m[b];){var I=n[m.charCodeAt(b)];if(I===255)return;for(var L=0,P=S-1;(I!==0||L<x)&&P!==-1;P--,L++)I+=u*C[P]>>>0,C[P]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=L,b++}if(m[b]!==" "){for(var B=S-x;B!==S&&C[B]===0;)B++;for(var W=new Uint8Array(w+(S-B)),G=w;B!==S;)W[G++]=C[B++];return W}}}function y(m){var b=g(m);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:g,decode:y}}var IS=CS,_S=IS,q6=_S;var Rp=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")}},Pp=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 z6(this,e)}},Lp=class{decoders;constructor(e){this.decoders=e}or(e){return z6(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 z6(r,e){return new Lp({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kp=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Rp(e,t,n),this.decoder=new Pp(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fi({name:r,prefix:e,encode:t,decode:n}){return new kp(r,e,t,n)}function ds({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=q6(t,r,n);return fi({prefix:e,name:r,encode:s,decode:i=>yr(o(i))})}function RS(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function PS(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function LS(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function Ye({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=LS(n,s);return fi({prefix:e,name:r,encode(i){return PS(i,n,t)},decode(i){return RS(i,o,t,r)}})}var Ie=ds({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kS=ds({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Np={};fe(Np,{base32:()=>br,base32hex:()=>MS,base32hexpad:()=>US,base32hexpadupper:()=>FS,base32hexupper:()=>BS,base32pad:()=>NS,base32padupper:()=>OS,base32upper:()=>DS,base32z:()=>$S});var br=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),DS=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),NS=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),OS=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),MS=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),BS=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),US=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),FS=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),$S=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Op={};fe(Op,{base36:()=>io,base36upper:()=>KS});var io=ds({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),KS=ds({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var ze={};fe(ze,{Digest:()=>ao,create:()=>Ut,decode:()=>_e,equals:()=>Bp,hasCode:()=>iA});var VS=j6,G6=128,HS=127,qS=~HS,zS=Math.pow(2,31);function j6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zS;)e[t++]=r&255|G6,r/=128;for(;r&qS;)e[t++]=r&255|G6,r>>>=7;return e[t]=r|0,j6.bytes=t-n+1,e}var GS=Mp,WS=128,W6=127;function Mp(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Mp.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&W6)<<s:(i&W6)*Math.pow(2,s),s+=7}while(i>=WS);return Mp.bytes=o-n,t}var jS=Math.pow(2,7),YS=Math.pow(2,14),XS=Math.pow(2,21),QS=Math.pow(2,28),ZS=Math.pow(2,35),JS=Math.pow(2,42),eA=Math.pow(2,49),tA=Math.pow(2,56),rA=Math.pow(2,63),nA=function(r){return r<jS?1:r<YS?2:r<XS?3:r<QS?4:r<ZS?5:r<JS?6:r<eA?7:r<tA?8:r<rA?9:10},sA={encode:VS,decode:GS,encodingLength:nA},oA=sA,ja=oA;function Ya(r,e=0){let t=ja.decode(r,e),n=ja.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function hi(r,e,t=0){return ja.encode(r,e,t),e}function pi(r){return ja.encodingLength(r)}function Ut(r,e){let t=e.byteLength,n=pi(r),s=n+pi(t),o=new Uint8Array(s+t);return hi(r,o,0),hi(t,o,n),o.set(e,s),new ao(r,t,e,o)}function _e(r){let e=yr(r),[t,n]=Ya(e),[s,o]=Ya(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ao(t,s,i,e)}function Bp(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$6(r.bytes,t.bytes)}}var ao=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=oo(n),this.bytes=oo(s)}};function iA(r,e){return r.code===e}function Y6(r,e){let{bytes:t,version:n}=r;return n===0?cA(t,Up(r),e??Ie.encoder):lA(t,Up(r),e??br.encoder)}var X6=new WeakMap;function Up(r){let e=X6.get(r);if(e==null){let t=new Map;return X6.set(r,t),t}return e}var ge=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=oo(s),this["/"]=this.bytes}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!==Xa)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==uA)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=Ut(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&&Bp(e.multihash,n.multihash)}toString(e){return Y6(this,e)}toJSON(){return{"/":Y6(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:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Q6(n,s,o.bytes))}else if(t[dA]===!0){let{version:n,multihash:s,code:o}=t,i=_e(s);return r.create(n,o,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!==Xa)throw new Error(`Version 0 CID must use dag-pb (code: ${Xa}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Q6(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Xa,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,s=yr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ao(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Ya(e.subarray(t));return t+=f,d},s=n(),o=Xa;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=aA(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Up(o).set(n,e),o}};function aA(r,e){switch(r[0]){case"Q":{let t=e??Ie;return[Ie.prefix,t.decode(`${Ie.prefix}${r}`)]}case Ie.prefix:{let t=e??Ie;return[Ie.prefix,t.decode(r)]}case br.prefix:{let t=e??br;return[br.prefix,t.decode(r)]}case io.prefix:{let t=e??io;return[io.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function cA(r,e,t){let{prefix:n}=t;if(n!==Ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function lA(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Xa=112,uA=18;function Q6(r,e,t){let n=pi(r),s=n+pi(e),o=new Uint8Array(s+t.byteLength);return hi(r,o,0),hi(e,o,n),o.set(t,s),o}var dA=Symbol.for("@ipld/js-cid/CID");var Fp={};fe(Fp,{identity:()=>ar});var Z6=0,fA="identity",J6=yr;function hA(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ut(Z6,J6(r))}var ar={code:Z6,name:fA,encode:J6,digest:hA};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 pA(r){return r.buffer instanceof ArrayBuffer}function he(r){return pA(r)?r:r.slice()}var e5="1.2.840.10045.3.1.7",t5="1.3.132.0.34",r5="1.3.132.0.35";async function n5(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function s5(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,he(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function o5(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,he(e),he(t.subarray()));return n?.signal?.throwIfAborted(),o}function ne(r=0){return new Uint8Array(r)}function Ge(r=0){return new Uint8Array(r)}function mA(r){return r?.buffer instanceof ArrayBuffer}function $u(r){if(mA(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function et(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ge(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return $u(t)}var a5=Symbol.for("@achingbrain/uint8arraylist");function i5(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function mi(r){return!!r?.[a5]}var j=class r{bufs;length;[a5]=!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(mi(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}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(mi(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=i5(this.bufs,e);return t.buf[t.index]}set(e,t){let n=i5(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(mi(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:s}=this._subList(e,t);return et(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:et(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){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(!mi(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}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=Ge(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 s=ne(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,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=Ge(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 s=ne(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,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((s,o)=>s+o.byteLength,0)),n.length=t,n}};var $p={};fe($p,{base10:()=>gA});var gA=ds({prefix:"9",name:"base10",alphabet:"0123456789"});var Kp={};fe(Kp,{base16:()=>yA,base16upper:()=>bA});var yA=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),bA=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Vp={};fe(Vp,{base2:()=>wA});var wA=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hp={};fe(Hp,{base256emoji:()=>AA});var c5=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}"),EA=c5.reduce((r,e,t)=>(r[t]=e,r),[]),xA=c5.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function vA(r){return r.reduce((e,t)=>(e+=EA[t],e),"")}function SA(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=xA[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var AA=fi({prefix:"\u{1F680}",name:"base256emoji",encode:vA,decode:SA});var qp={};fe(qp,{base64:()=>_n,base64pad:()=>Qa,base64url:()=>Za,base64urlpad:()=>TA});var _n=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qa=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Za=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),TA=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var zp={};fe(zp,{base8:()=>CA});var CA=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gp={};fe(Gp,{identity:()=>IA});var IA=fi({prefix:"\0",name:"identity",encode:r=>V6(yr(r)),decode:r=>yr(K6(r))});var UM=new TextEncoder,FM=new TextDecoder;var Ku=85;var Yp={};fe(Yp,{sha256:()=>yt,sha512:()=>PA});var RA=20;function Ja({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new jp(r,e,t,n,s)}var jp=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??RA,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?l5(n,this.code,t?.truncate):n.then(s=>l5(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function l5(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ut(e,r)}function d5(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var yt=Ja({name:"sha2-256",code:18,encode:d5("SHA-256")}),PA=Ja({name:"sha2-512",code:19,encode:d5("SHA-512")});var co={...Gp,...Vp,...zp,...$p,...Kp,...Np,...Op,...Dp,...qp,...Hp},QM={...Yp,...Fp};function h5(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var f5=h5("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xp=h5("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=Ge(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),LA={utf8:f5,"utf-8":f5,hex:co.base16,latin1:Xp,ascii:Xp,binary:Xp,...co},Vu=LA;function T(r,e="utf8"){let t=Vu[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function k(r,e="utf8"){let t=Vu[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var kA=parseInt("11111",2),Qp=parseInt("10000000",2),DA=parseInt("01111111",2),p5={0:ec,1:ec,2:NA,3:BA,4:UA,5:MA,6:OA,16:ec,22:ec,48:ec};function wr(r,e={offset:0}){let t=r[e.offset]&kA;if(e.offset++,p5[t]!=null)return p5[t](r,e);throw new Error("No decoder for tag "+t)}function tc(r,e){let t=0;if((r[e.offset]&Qp)===Qp){let n=r[e.offset]&DA,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");s+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(s,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function ec(r,e){tc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wr(r,e);if(n===null)break;t.push(n)}return t}function NA(r,e){let t=tc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function OA(r,e){let t=tc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function MA(r,e){return e.offset++,null}function BA(r,e){let t=tc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function UA(r,e){let t=tc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function FA(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new j;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Hu(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=FA(r.byteLength);return new j(Uint8Array.from([e.byteLength|Qp]),e)}function Ft(r){let e=new j,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new j(Uint8Array.from([2]),Hu(e),e)}function rc(r){let e=Uint8Array.from([0]),t=new j(e,r);return new j(Uint8Array.from([3]),Hu(t),t)}function m5(r){return new j(Uint8Array.from([4]),Hu(r),r)}function Dr(r,e=48){let t=new j;for(let n of r)t.append(n);return new j(Uint8Array.from([e]),Hu(t),t)}var $A=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),KA=Uint8Array.from([6,5,43,129,4,0,34]),VA=Uint8Array.from([6,5,43,129,4,0,35]),g5={ext:!0,kty:"EC",crv:"P-256"},y5={ext:!0,kty:"EC",crv:"P-384"},b5={ext:!0,kty:"EC",crv:"P-521"},gi=32,yi=48,bi=66;function w5(r){let e=wr(r);return Zp(e)}function Zp(r){let e=r[1],t=k(e,"base64url"),n=r[2][1][0],s=1,o,i;if(e.byteLength===gi)return o=k(n.subarray(s,s+gi),"base64url"),i=k(n.subarray(s+gi),"base64url"),new uo({...g5,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===yi)return o=k(n.subarray(s,s+yi),"base64url"),i=k(n.subarray(s+yi),"base64url"),new uo({...y5,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===bi)return o=k(n.subarray(s,s+bi),"base64url"),i=k(n.subarray(s+bi),"base64url"),new uo({...b5,key_ops:["sign"],d:t,x:o,y:i});throw new v(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Jp(r){let e=wr(r);return E5(e)}function E5(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===gi*2+1)return n=k(e.subarray(t,t+gi),"base64url"),s=k(e.subarray(t+gi),"base64url"),new lo({...g5,key_ops:["verify"],x:n,y:s});if(e.byteLength===yi*2+1)return n=k(e.subarray(t,t+yi),"base64url"),s=k(e.subarray(t+yi),"base64url"),new lo({...y5,key_ops:["verify"],x:n,y:s});if(e.byteLength===bi*2+1)return n=k(e.subarray(t,t+bi),"base64url"),s=k(e.subarray(t+bi),"base64url"),new lo({...b5,key_ops:["verify"],x:n,y:s});throw new v(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function x5(r){return Dr([Ft(Uint8Array.from([1])),m5(T(r.d??"","base64url")),Dr([S5(r.crv)],160),Dr([rc(new j(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function v5(r){return Dr([Ft(Uint8Array.from([1])),Dr([S5(r.crv)],160),Dr([rc(new j(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function S5(r){if(r==="P-256")return $A;if(r==="P-384")return KA;if(r==="P-521")return VA;throw new v(`Invalid curve ${r}`)}async function A5(r="P-256"){let e=await n5(r);return new uo(e.privateKey)}var lo=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=v5(this.jwk)),this._raw}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async verify(e,t,n){return o5(this.jwk,t,e,n)}},uo=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new lo({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=x5(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async sign(e,t){return s5(this.jwk,e,t)}};var qu=BigInt(4294967295),T5=BigInt(32);function HA(r,e=!1){return e?{h:Number(r&qu),l:Number(r>>T5&qu)}:{h:Number(r>>T5&qu)|0,l:Number(r&qu)|0}}function C5(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=HA(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var qA=r=>r/2**32|0,zA=r=>r>>>0;function I5(r,e,t,n){let s=qA(t),o=zA(t);r.setUint32(e,n?o:s,n),r.setUint32(e+4,n?s:o,n)}var e2=(r,e,t)=>r>>>t,t2=(r,e,t)=>r<<32-t|e>>>t,fo=(r,e,t)=>r>>>t|e<<32-t,ho=(r,e,t)=>r<<32-t|e>>>t,nc=(r,e,t)=>r<<64-t|e>>>t-32,sc=(r,e,t)=>r>>>t-32|e<<64-t;function tn(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var _5=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),R5=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,P5=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),L5=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,k5=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),D5=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;function zu(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var r2=r=>r?`"${r}" `:"";function bt(r,e=""){if(typeof r!="number")throw new TypeError(r2(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(r2(e)+"expected integer >= 0, got "+r);return r}function Ct(r,e,t=""){if(zu(r)&&(e===void 0||r.length===e))return r;e!==void 0&&bt(e,"length");let n=zu(r),s=e!==void 0?` of length ${e}`:"",o=n?`length=${r.length}`:`type=${typeof r}`,i=r2(t)+"expected Uint8Array"+s+", got "+o;throw n?new RangeError(i):new TypeError(i)}function Rn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(bt(r.outputLen),bt(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var WA=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},N5=(r,e)=>{WA(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function wi(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Gu(r,e){Ct(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function tt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ei(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Nr(r,e){return r<<32-e|r>>>e}function Wu(r,e){return r<<e|r>>>32-e>>>0}var M5=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jA=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ju(r){if(Ct(r),M5)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=jA[r[t]];return e}function O5(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function Yu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(M5)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=O5(r.charCodeAt(o)),a=O5(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function YA(r){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return r&&t.catch(r),t}return new Promise(t=>e.setTimeout(t,0))}async function B5(r,e,t,n){if(bt(r,"iters"),bt(e,"tick"),typeof t!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-s;i>=0&&i<e||(await YA(n),s=Date.now())}}function XA(r){if(typeof r!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(r);try{return new Uint8Array(e)}finally{tt(e)}}function n2(r,e=""){return typeof r=="string"?XA(r):Ct(r,void 0,e)}function s2(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Ct(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function o2(r,e,t="opts"){return N5(r,"defaults"),e!==void 0&&N5(e,t),Object.assign(Object.create(null),r,e)}function oc(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=o2({},e,"info");let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function U5(r=32){bt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var i2=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Xu(r,e,t){return r&e^~r&t}function Qu(r,e,t){return r&e^r&t^e&t}var po=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ei(this.buffer)}update(e){wi(this),Ct(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length,i=!1;for(let a=0;a<o;){let c=Math.min(s-this.pos,o-a);if(c===s){let l=Ei(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}n.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){wi(this),Gu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>s-i&&(this.process(n,0),t.fill(0)),I5(n,s-8,this.length*8,o),this.process(n,0),this.roundClean();let a=e===t?n:Ei(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},F5=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $5=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var QA=Uint32Array.from([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]),fs=new Uint32Array(64),a2=class extends po{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)fs[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=fs[d-15],h=fs[d-2],p=Nr(f,7)^Nr(f,18)^f>>>3,g=Nr(h,17)^Nr(h,19)^h>>>10;fs[d]=g+fs[d-7]+p+fs[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Nr(a,6)^Nr(a,11)^Nr(a,25),h=u+f+Xu(a,c,l)+QA[d]+fs[d]|0,g=(Nr(n,2)^Nr(n,13)^Nr(n,22))+Qu(n,s,o)|0;u=l,l=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+g|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){tt(fs)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),tt(this.buffer)}},c2=class extends a2{constructor(){super(32,F5)}};var K5=C5(["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))),ZA=K5[0],JA=K5[1],hs=new Uint32Array(80),ps=new Uint32Array(80),l2=class extends po{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:g,Hl:y}=this;return[e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y]}set(e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let w=0;w<16;w++,t+=4)hs[w]=e.getUint32(t),ps[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=hs[w-15]|0,S=ps[w-15]|0,C=fo(x,S,1)^fo(x,S,8)^e2(x,S,7),I=ho(x,S,1)^ho(x,S,8)^t2(x,S,7),L=hs[w-2]|0,P=ps[w-2]|0,B=fo(L,P,19)^nc(L,P,61)^e2(L,P,6),W=ho(L,P,19)^sc(L,P,61)^t2(L,P,6),G=P5(I,W,ps[w-7],ps[w-16]),Z=L5(G,C,B,hs[w-7],hs[w-16]);hs[w]=Z|0,ps[w]=G|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:g,Gl:y,Hh:m,Hl:b}=this;for(let w=0;w<80;w++){let x=fo(d,f,14)^fo(d,f,18)^nc(d,f,41),S=ho(d,f,14)^ho(d,f,18)^sc(d,f,41),C=d&h^~d&g,I=f&p^~f&y,L=k5(b,S,I,JA[w],ps[w]),P=D5(L,m,x,C,ZA[w],hs[w]),B=L|0,W=fo(n,s,28)^nc(n,s,34)^nc(n,s,39),G=ho(n,s,28)^sc(n,s,34)^sc(n,s,39),Z=n&o^n&a^o&a,N=s&i^s&c^i&c;m=g|0,b=y|0,g=h|0,y=p|0,h=d|0,p=f|0,{h:d,l:f}=tn(l|0,u|0,P|0,B|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let $=_5(B,G,N);n=R5($,P,W,Z),s=$|0}({h:n,l:s}=tn(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=tn(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=tn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=tn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=tn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=tn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:y}=tn(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:b}=tn(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,s,o,i,a,c,l,u,d,f,h,p,g,y,m,b)}roundClean(){tt(hs,ps)}destroy(){this.destroyed=!0,tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},u2=class extends l2{constructor(){super(64,$5)}};var It=oc(()=>new c2,i2(1));var Pn=oc(()=>new u2,i2(3));function Ju(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var Ee=(r,e,t)=>Ct(r,e,t),d2=bt;function H5(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function ms(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function mo(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var ic=ju,Er=(...r)=>s2(...r),xi=r=>Yu(r),ys=zu,Ln=r=>U5(r),Zu=BigInt(0),V5=BigInt(1),eT=r=>r?`"${r}" `:"";function Yt(r,e=""){if(typeof r!="boolean")throw new TypeError(eT(e)+"expected boolean, got type="+typeof r);return r}function ed(r){if(typeof r=="bigint"){if(!gs(r))throw new RangeError("positive bigint expected, got "+r)}else d2(r);return r}function kn(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function ac(r){let e=ed(r).toString(16);return e.length&1?"0"+e:e}function q5(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Zu:BigInt("0x"+r)}function rn(r){return q5(ju(r))}function nn(r){return q5(ju(bs(Ct(r)).reverse()))}function td(r,e){if(bt(e),e===0)throw new Error("zero output length is invalid");r=ed(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return Yu(n.padStart(t,"0"))}function cc(r,e){return td(r,e).reverse()}function bs(r){return Uint8Array.from(Ee(r))}function gs(r){return typeof r=="bigint"&&Zu<=r}function f2(r,e,t){return gs(r)&&gs(e)&&gs(t)&&e<=r&&r<t}function sn(r,e,t,n){if(!f2(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function vi(r){if(r<Zu)throw new Error("expected non-negative bigint, got "+r);return r===Zu?0:r.toString(2).length}var lc=r=>(kn(r,"n"),(V5<<BigInt(r))-V5);function z5(r,e,t){if(bt(r,"hashLen"),bt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...y)=>t(l,Er(c,...y)),h=(y=s)=>{l=f(o,y),c=f(),y.length!==0&&(l=f(i,y),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=f();let b=c.slice();m.push(b),y+=c.length}return Er(...m)};return(y,m)=>{d(),h(y);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function _t(r,e={},t={},n="object"){ms(r,n),ms(e,"fields"),ms(t,"optFields");function s(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let d=typeof u;if(d!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(t,!0)}var ct=BigInt(0),Re=BigInt(1),ws=BigInt(2),j5=BigInt(3),h2=BigInt(4),Y5=BigInt(5),tT=BigInt(7),X5=BigInt(8),rT=BigInt(9),nT=BigInt(15),Q5=BigInt(16),sT=BigInt("0x10000000000000000");function De(r,e){if(e<=ct)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ct?t:e+t}function Z5(r,e,t){if(t<=Re)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<ct)throw new Error("invalid exponent, negatives unsupported");if(e===ct)return Re;if(e===Re)return r;let n=r%t;if(n<ct&&(n+=t),e<sT){let a=Re;for(;e>ct;)e&Re&&(a=a*n%t),n=n*n%t,e>>=Re;return a}let s=[];for(;e>ct;)s.push(Number(e&nT)),e>>=h2;let o=new Array(16);o[0]=Re,o[1]=n;for(let a=2;a<16;a++)o[a]=o[a-1]*n%t;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=s[a];c!==0&&(i=i*o[c]%t)}return i}function Ke(r,e,t){if(t<=Re)throw new Error("pow2: expected modulus > 1, got "+t);if(e<ct)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >ct;)n*=n,n%=t;return n}function G5(r,e){if(r===ct)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected modulus > 1, got "+e);let t=De(r,e),n=e,s=ct,o=Re;for(;t!==ct;){let a=n/t,c=n-t*a,l=s-o*a;n=t,t=c,s=o,o=l}if(n!==Re)throw new Error("invert: does not exist");return De(s,e)}function J5(r,e){if(e<=Re)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=De(r,e);if(t===ct)throw new Error("invertCt: expected non-zero number");let n=Z5(t,e-ws,e);if(De(t*n,e)!==Re)throw new Error("invertCt: does not exist");return n}function p2(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function m2(r,e){if((r&Re)===ct)throw new Error(e+": expected odd modulus, got "+r)}function e8(r,e){let t=r,n=(t.ORDER+Re)/h2,s=t.pow(e,n);return p2(t,s,e),s}function oT(r,e){let t=r,n=(t.ORDER-Y5)/X5,s=t.mul(e,ws),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,ws),o),c=t.mul(i,t.sub(a,t.ONE));return p2(t,c,e),c}function iT(r){let e=Ai(r),t=t8(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+tT)/Q5;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,s),h=l.mul(u,o),p=l.eql(l.sqr(d),c),g=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,g);let y=l.eql(l.sqr(d),c),m=l.cmov(u,d,y);return p2(l,m,c),m})}function t8(r){if(r<j5)throw new Error("sqrt is not defined for small field");m2(r,"tonelliShanks");let e=r-Re,t=0;for(;e%ws===ct;)e/=ws,t++;let n=ws,s=Ai(r);for(;uc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return e8;let o=s.pow(n,e),i=(e+Re)/ws;return function(c,l){let u=c;if(u.is0(l))return l;if(uc(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,o),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(h);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let m=Re<<BigInt(d-g-1),b=u.pow(f,m);d=g,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function aT(r){return m2(r,"Fp.sqrt"),r%h2===j5?e8:r%X5===Y5?oT:r%Q5===rT?iT(r):t8(r)}var r8=(r,e)=>(De(r,e)&Re)===Re,cT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Si(r){if(ms(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);kn(r.BYTES,"BYTES"),kn(r.BITS,"BITS");for(let e of cT)mo(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Re)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function nd(r,e,t=!1){Si(r),Ju(e,"nums"),Yt(t,"passZero");let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,l)=>n.is0(c)?a:(s[l]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,l)=>n.is0(c)?a:(s[l]=n.mul(a,s[l]),n.mul(a,c)),i),s}function uc(r,e){Si(r);let t=r;m2(t.ORDER,"FpLegendre");let n=(t.ORDER-Re)/ws,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function lT(r,e){if(e!==void 0&&d2(e),r<=ct)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=vi(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var W5=new WeakMap,rd=class{ORDER;BITS;BYTES;isLE;ZERO=ct;ONE=Re;_lengths;_mod;constructor(e,t={}){if(e<=Re)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=lT(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return De(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ct<=e&&e<this.ORDER}is0(e){return e===ct}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Re)===Re}neg(e){return De(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return De(e*e,this.ORDER)}add(e,t){return De(e+t,this.ORDER)}sub(e,t){return De(e-t,this.ORDER)}mul(e,t){return De(e*t,this.ORDER)}pow(e,t){return Z5(e,t,this.ORDER)}div(e,t){return De(e*G5(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return G5(e,this.ORDER)}sqrt(e){let t=W5.get(this);return t||W5.set(this,t=aT(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?cc(e,this.BYTES):td(e,this.BYTES)}fromBytes(e,t=!1){Ee(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?nn(e):rn(e);if(a&&(c=De(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return nd(this,e,!0)}cmov(e,t,n){return Yt(n,"condition"),n?t:e}};function Ai(r,e={}){return Object.freeze(rd.prototype),new rd(r,e)}function n8(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Re)throw new Error("field order must be greater than 1");let e=vi(r-Re);return Math.ceil(e/8)}function sd(r){let e=n8(r);return e+Math.ceil(e/2)}function od(r,e,t=!1){Ee(r);let n=r.length,s=n8(e),o=Math.max(sd(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?nn(r):rn(r),a=De(i,e-Re)+Re;return t?cc(a,s):td(a,s)}var b2=BigInt(0),dc=BigInt(1),uT=BigInt(4),g2=16,s8=128,dT=5,o8=2**31;function Es(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);mo(e.fromAffine,"Point.fromAffine"),mo(e.fromBytes,"Point.fromBytes"),mo(e.fromHex,"Point.fromHex"),ms(e.BASE,"Point.BASE"),ms(e.ZERO,"Point.ZERO"),Si(e.Fp),Si(e.Fn)}function id(r,e){Es(r),a8(e,r);let t=nd(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function fT(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function hT(r,e){let t=r*(4*e+128);if(t>o8)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+o8/2**20+" MiB")}function w2(r,e){if(r!==void 0){mo(r,"randomBytes");try{let t=r(e);if(!ys(t)||t.length!==e)return}catch{return}return r}}function a8(r,e){Ju(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function pT(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,s)=>{if(!(t===void 0?e.isValid(n):gs(n)&&n<t))throw new Error("invalid scalar at index "+s)})}var c8=new WeakMap;function y2(r){return c8.get(r)||1}function mT(r,e){let t=r.double(),n=[r];for(let s=1;s<e;s++)n.push(n[s-1].add(t));return n}function gT(r,e){let t=2**e,n=t/2,s=BigInt(t-1),o=[];for(;r>b2;){let i=0;r&dc&&(i=Number(r&s),i>=n&&(i-=t),r-=BigInt(i)),o.push(i),r>>=dc}return o}function yT(r,e,t){let n=2**e,s=n/2,o=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(r&o);r>>=i,l>s&&(l-=n,r+=dc),a.push(l)}if(r!==b2)throw new Error("invalid wnaf");return a}function bT(r,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let s=r;for(let o=n-1;o>=0;o--){o!==n-1&&(s=s.double());for(let i=0;i<t.length;i++){let a=t[i][o];if(a){let c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}var Ti=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Es(e),this.randomBytes=w2(t,g2),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let s=Math.ceil(n/t)+1,o=2**(t-1),i=[],a=e;for(let c=0;c<s;c++){let l=a;for(let u=0;u<o;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:s,comp:i}}wnafCachedCT(e,t){let{W:n,windows:s,comp:o}=e,i=2**(n-1),a=yT(t,n,s),c=this.ZERO,l=this.BASE;for(let u=0;u<s;u++){let d=a[u],f=u*i,h=Math.abs(d)-1,p=o[f];for(let y=1;y<i;y++)p=y===h?o[f+y]:p;let g=p.negate();d===0?l=l.add(o[f]):c=c.add(d<0?g:p)}return{p:c,f:l}}getWnafPrecomputes(e,t,n,s){let o=this.wnafPrecomputes.get(t),i=o?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!f2(t,dc,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,s){let o=y2(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,s),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let s=this.Point.Fn.BITS+s8,o=this.randomBytes(g2);if(!ys(o)||o.length!==g2)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+rn(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,n)}fixedWindowCT(e,t,n){let s=dT,o=1<<s,i=lc(s),a=new Array(o);a[0]=this.ZERO;for(let u=1;u<o;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/s),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let h=0;h<s;h++)l=l.double();let d=Number(t>>BigInt(u*s)&i),f=a[0];for(let h=1;h<o;h++)f=h===d?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===dc?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,s){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,s):this.mulCT(e,t,s)}mulUnsafe(e,t,n){if(this.assertPoint(e),!gs(t))throw new Error("invalid scalar");let s=y2(e);if(s===1||t>=this.Point.Fn.ORDER)return ad(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(s,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),fT(t,this.bits);let n=Math.ceil((this.bits+s8)/t)+1;hT(n*2**(t-1),this.Point.Fp.BYTES),c8.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return y2(e)!==1}};function ad(r,e,t,n=!1){if(Es(r),a8(e,r),Yt(n,"allowOversized"),pT(t,r.Fn,n?r.Fn.ORDER**uT:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let s=e.map(i=>mT(i,4)),o=t.map(i=>gT(i,4));return bT(r.ZERO,s,o)}function i8(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Si(e),e}else return Ai(r,{isLE:t})}function cd(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);_t(t);for(let c of["p","n","h"]){let l=e[c];if(!(gs(l)&&l!==b2))throw new Error(`CURVE.${c} must be positive bigint`)}let s=i8(e.p,t.Fp,n),o=i8(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Ci(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var ld=BigInt(0),ud=BigInt(1),dd=BigInt(2),wT=BigInt(4),l8=BigInt(8);function ET(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function u8(r,e={}){_t(e,{},{},"extraOpts");let t=e,n=cd("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;if(uc(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(uc(s,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");_t(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Ln:t.randomBytes,l=dd<<BigInt(s.BYTES*8)-ud;function u(b){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(b)}let d=t.uvRatio===void 0?(b,w)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,w))}}catch{return{isValid:!1,value:ld}}}:t.uvRatio;if(!ET(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=s.eql(i.a,s.neg(s.ONE))?b=>s.neg(b):s.eql(i.a,s.ONE)?b=>b:b=>s.mul(i.a,b);function h(b,w,x=!1){let S=x?ud:ld;return sn("coordinate "+b,w,S,l),w}function p(b){if(!(b instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new g(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(w,x,S,C){this.X=h("x",w),this.Y=h("y",x),this.Z=h("z",S,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");let{x,y:S}=w||{};return h("x",x),h("y",S),new g(x,S,s.ONE,s.mul(x,S))}static fromBytes(w,x=!1){let S=s.BYTES,{a:C,d:I}=i;w=bs(Ee(w,S,"point")),Yt(x,"zip215");let L=bs(w),P=w[S-1];L[S-1]=P&-129;let B=nn(L),W=x?l:s.ORDER;sn("point.y",B,ld,W);let G=s.sqr(B),Z=s.sub(G,s.ONE),N=s.sub(s.mulN(I,G),C),{isValid:$,value:O}=d(Z,N);if(!$)throw new Error("bad point: invalid y coordinate");let D=u(O),Y=(P&128)!==0;if(!x&&s.is0(O)&&Y)throw new Error("bad point: x=0 and x_0=1");return Y!==D&&(O=s.neg(O)),g.fromAffine({x:O,y:B})}static fromHex(w,x=!1){return g.fromBytes(xi(w),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=6,x=!0){return m.setWindowSize(this,w),x||this.multiply(dd),this}assertValidity(){let w=this,{a:x,d:S}=i;if(w.is0())throw new Error("bad point: ZERO");let{X:C,Y:I,Z:L,T:P}=w,B=s.sqr(C),W=s.sqr(I),G=s.sqr(L),Z=s.sqr(G),N=s.mul(B,x),$=s.mul(s.add(N,W),G),O=s.add(Z,s.mul(S,s.mul(B,W)));if(!s.eql($,O))throw new Error("bad point: equation left != right (1)");let D=s.mul(C,I),Y=s.mul(L,P);if(!s.eql(D,Y))throw new Error("bad point: equation left != right (2)")}equals(w){p(w);let{X:x,Y:S,Z:C}=this,{X:I,Y:L,Z:P}=w,B=s.mul(x,P),W=s.mul(I,C),G=s.mul(S,P),Z=s.mul(L,C);return s.eql(B,W)&&s.eql(G,Z)}is0(){return this.equals(g.ZERO)}negate(){return new g(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){let{X:w,Y:x,Z:S}=this,C=s.sqr(w),I=s.sqr(x),L=s.mul(s.sqr(S),dd),P=f(C),B=s.addN(w,x),W=s.sub(s.subN(s.sqr(B),C),I),G=s.addN(P,I),Z=s.subN(G,L),N=s.subN(P,I),$=s.mul(W,Z),O=s.mul(G,N),D=s.mul(W,N),Y=s.mul(Z,G);return new g($,O,Y,D)}add(w){p(w);let{d:x}=i,{X:S,Y:C,Z:I,T:L}=this,{X:P,Y:B,Z:W,T:G}=w,Z=s.mul(S,P),N=s.mul(C,B),$=s.mul(s.mulN(L,x),G),O=s.mul(I,W),D=s.sub(s.subN(s.mulN(s.addN(S,C),s.addN(P,B)),Z),N),Y=s.subN(O,$),M=s.addN(O,$),_=s.sub(N,f(Z)),E=s.mul(D,Y),A=s.mul(M,_),R=s.mul(D,_),U=s.mul(Y,M);return new g(E,A,U,R)}subtract(w){return p(w),this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:S}=m.mulSecret(this,w,a,y);return y([x,S])[0]}multiplyUnsafe(w){if(!o.isValid(w))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return w===ld?g.ZERO:this.is0()||w===ud?this:m.mulUnsafe(this,w,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.mulUnsafe(this,i.n).is0()}toAffine(w){let x=this,S=w;if(S!=null&&typeof S!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof S);let{X:C,Y:I,Z:L}=x,P=x.is0();S==null&&(S=P?s.create(l8):s.inv(L));let B=s.mul(C,S),W=s.mul(I,S),G=s.mul(L,S);if(P)return{x:s.ZERO,y:s.ONE};if(!s.eql(G,s.ONE))throw new Error("invZ was invalid");return{x:B,y:W}}clearCofactor(){return a===ud?this:a===dd?this.double():a===wT?this.double().double():a===l8?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:w,y:x}=this.toAffine(),S=s.toBytes(x);return S[S.length-1]|=u(w)?128:0,S}toHex(){return ic(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=b=>id(g,b),m=new Ti(g,c);return m.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function d8(r,e,t={}){if(Es(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;_t(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(kn(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=s.randomBytes===void 0?Ln:s.randomBytes,f=s.toMontgomery,h=s.toMontgomerySecret,p=s.adjustScalarBytes===void 0?N=>N:s.adjustScalarBytes,g=s.domain===void 0?(N,$,O)=>{if(Yt(O,"phflag"),$.length||O)throw new Error("Contexts/pre-hash are not supported");return N}:s.domain;function y(N){return c.create(nn(N))}function m(N){let $=P.secretKey;Ee(N,P.secretKey,"secretKey");let O=Ee(n(N),2*$,"hashedSecretKey"),D=p(O.slice(0,$)),Y=O.slice($,2*$),M=y(D);return{head:D,prefix:Y,scalar:M}}function b(N){let{head:$,prefix:O,scalar:D}=m(N),Y=i.multiply(D),M=Y.toBytes();return{head:$,prefix:O,scalar:D,point:Y,pointBytes:M}}function w(N){return b(N).pointBytes}function x(N=Uint8Array.of(),...$){let O=Er(...$);return y(n(g(O,Ee(N,void 0,"context"),!!o)))}function S(N,$,O={}){_t(O,{},{},"options"),N=bs(Ee(N,void 0,"message")),o&&(N=o(N));let{prefix:D,scalar:Y,pointBytes:M}=b($),_=x(O.context,D,N),E=i.multiply(_).toBytes(),A=x(O.context,E,M,N),R=c.create(_+A*Y);if(!c.isValid(R))throw new Error("sign failed: invalid s");let U=Er(E,c.toBytes(R));return Ee(U,P.signature,"result")}let C={zip215:s.zip215};function I(N,$,O,D=C){_t(D);let{context:Y}=D,M=D.zip215===void 0?!!C.zip215:D.zip215,_=P.signature;N=Ee(N,_,"signature"),$=Ee($,void 0,"message"),O=Ee(O,P.publicKey,"publicKey"),M!==void 0&&Yt(M,"zip215"),o&&($=o($));let E=_/2,A=N.subarray(0,E),R=nn(N.subarray(E,_)),U,q,z;try{U=r.fromBytes(O,M),q=r.fromBytes(A,M),z=i.multiplyUnsafe(R)}catch{return!1}if(!M&&U.isSmallOrder())return!1;let X=x(Y,A,O,$);return q.add(U.multiplyUnsafe(X)).subtract(z).clearCofactor().is0()}let L=a.BYTES,P={secretKey:L,publicKey:L,signature:2*L,seed:L};function B(N){return N=N===void 0?d(P.seed):N,Ee(N,P.seed,"seed")}function W(N){return ys(N)&&N.length===P.secretKey}function G(N,$){try{return!!r.fromBytes(N,$===void 0?C.zip215:$)}catch{return!1}}let Z={getExtendedPublicKey:b,randomSecretKey:B,isValidSecretKey:W,isValidPublicKey:G,toMontgomery(N){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(r.fromBytes(N))},toMontgomerySecret(N){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(N)}};return Object.freeze(P),Object.freeze(Z),Object.freeze({keygen:Ci(B,w),getPublicKey:w,sign:S,verify:I,utils:Z,Point:r,lengths:P})}var go=BigInt(0),xr=BigInt(1),fd=BigInt(2);function f8(r,e){return r+e-(e>>xr<<xr)}function xT(r){let e=BigInt(6)*r;return(t,n,s)=>{let o=n+s,a=((e+s-n)*t+n)%r;return{x_2:a,x_3:o-a}}}function vT(r){return _t(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...r})}function h8(r){let e=vT(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let l=i===void 0?Ln:i,u=c?255:448,d=xT(t),f=c?32:56,h=BigInt(c?9:5),p=BigInt(c?121665:39081),g=c?fd**BigInt(254):fd**BigInt(447),y=c?BigInt(8)*(fd**BigInt(251)-xr):BigInt(4)*(fd**BigInt(445)-xr),m=g+y+xr,b=O=>De(O,t),w=x(h);function x(O){return cc(b(O),f)}function S(O){let D=bs(Ee(O,f,"uCoordinate"));return c&&(D[31]&=127),b(nn(D))}function C(O){return nn(s(bs(Ee(O,f,"scalar"))))}let I=new Set(c?[go,xr,t-xr,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[go,xr,t-xr]);function L(O,D){let Y=S(D);if(I.has(Y))throw new Error("invalid private or public key received");let M=G(Y,C(O));if(M===go)throw new Error("invalid private or public key received");return x(M)}function P(O){if(a===void 0)return L(O,w);let D=C(O);sn("scalar",D,g,m);let Y=b(a(D));if(Y===go)throw new Error("invalid private or public key received");return x(Y)}let B=P,W=L;function G(O,D){sn("u",O,go,t),sn("scalar",D,g,m);let Y=D,M=O,_=xr,E=go,A=O,R=xr,U=Y^Y>>xr;for(let X=BigInt(u-1);X>=go;X--){let Q=f8(t,U>>X);({x_2:_,x_3:A}=d(Q,_,A)),{x_2:E,x_3:R}=d(Q,E,R);let ce=_+E,me=b(ce*ce),$e=_-E,Me=b($e*$e),Je=me-Me,Wt=A+R,Be=A-R,qe=b(Be*ce),si=b(Wt*$e),Ha=qe+si,is=qe-si;A=b(Ha*Ha),R=b(M*b(is*is)),_=b(me*Me),E=b(Je*(me+b(p*Je)))}let q=f8(t,Y);({x_2:_,x_3:A}=d(q,_,A)),{x_2:E,x_3:R}=d(q,E,R);let z=o(E);return b(_*z)}let Z={secretKey:f,publicKey:f,seed:f},N=O=>(O=O===void 0?l(f):O,Ee(O,Z.seed,"seed"),O),$={randomSecretKey:N};return Object.freeze(Z),Object.freeze($),Object.freeze({keygen:Ci(N,B),getSharedSecret:W,getPublicKey:B,scalarMult:L,scalarMultBase:P,utils:$,GuBytes:w.slice(),lengths:Z})}var p8=BigInt(0),E2=BigInt(1),m8=BigInt(2),ST=BigInt(3),AT=BigInt(5),TT=BigInt(8),hd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),CT={p:hd,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:TT,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function b8(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=hd,a=r*r%o*r%o,c=Ke(a,m8,o)*a%o,l=Ke(c,E2,o)*r%o,u=Ke(l,AT,o)*l%o,d=Ke(u,e,o)*u%o,f=Ke(d,t,o)*d%o,h=Ke(f,n,o)*f%o,p=Ke(h,s,o)*h%o,g=Ke(p,s,o)*h%o,y=Ke(g,e,o)*u%o;return{pow_p_5_8:Ke(y,m8,o)*r%o,b2:a}}function x2(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var g8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function IT(r,e){let t=hd,n=De(e*e*e,t),s=De(n*n*e,t),o=b8(r*s).pow_p_5_8,i=De(r*n*o,t),a=De(e*i*i,t),c=i,l=De(i*g8,t),u=a===r,d=a===De(-r,t),f=a===De(-r*g8,t);return u&&(i=c),(d||f)&&(i=l),r8(i,t)&&(i=De(-i,t)),{isValid:u||d,value:i}}var fc=u8(CT,{uvRatio:IT}),y8=fc.Fp;function _T(r){let{y:e}=r;return y8.toBytes(y8.div(E2+e,E2-e))}function RT(r){let e=fc.Fp.BYTES;return Ct(r,e),x2(Pn(r.subarray(0,e))).subarray(0,e)}function PT(r){return d8(fc,Pn,Object.assign({adjustScalarBytes:x2,toMontgomery:_T,toMontgomerySecret:RT,zip215:!0},r))}var hc=PT({});var on=(()=>{let r=hd,e=t=>{let{pow_p_5_8:n,b2:s}=b8(t);return De(Ke(n,ST,r)*s,r)};return h8({P:r,type:"x25519",powPminus2:e,adjustScalarBytes:x2,scalarMultBase:t=>{let n=De(t,fc.Fn.ORDER);if(n===p8)return p8;let s=fc.BASE.multiply(n);return De((s.Z+s.Y)*e(De(s.Z-s.Y,r)),r)}})})();var pc=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},mc=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},pd=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var st={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new pd("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");return e}};var yo=32,cr=64,v2=32;var Ii,w8=(async()=>{try{return await st.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function E8(){let r=hc.utils.randomSecretKey(),e=hc.getPublicKey(r);return{privateKey:OT(r,e),publicKey:e}}async function LT(r,e){let t;r.length===cr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:k(r.subarray(32),"base64url"),d:k(t,"base64url"),ext:!0,key_ops:["sign"]},s=await st.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await st.get().subtle.sign({name:"Ed25519"},s,he(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(o,0,o.byteLength)}function kT(r,e){let t=r.subarray(0,v2);return hc.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function x8(r,e){return Ii==null&&(Ii=await w8),Ii?LT(r,e):kT(r,e)}async function DT(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await st.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await st.get().subtle.verify({name:"Ed25519"},n,he(e),he(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function NT(r,e,t){return hc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function v8(r,e,t){return Ii==null&&(Ii=await w8),Ii?DT(r,e,t):NT(r,e,t)}function OT(r,e){let t=new Uint8Array(cr);for(let n=0;n<v2;n++)t[n]=r[n],t[v2+n]=e[n];return t}function _i(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gc=class{type="Ed25519";raw;constructor(e){this.raw=Pi(e,yo)}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=v8(this.raw,t,e);return _i(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},Ri=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Pi(e,cr),this.publicKey=new gc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=x8(this.raw,e);return _i(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}};function S2(r){if(r.length>cr){r=Pi(r,cr+yo);let n=r.subarray(0,cr),s=r.subarray(cr,r.length);return new Ri(n,s)}r=Pi(r,cr);let e=r.subarray(0,cr),t=r.subarray(yo);return new Ri(e,t)}function A2(r){return r=Pi(r,yo),new gc(r)}async function A8(){let{privateKey:r,publicKey:e}=E8();return new Ri(r,e)}function Pi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new v(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var MT=Math.pow(2,7),BT=Math.pow(2,14),UT=Math.pow(2,21),T2=Math.pow(2,28),C2=Math.pow(2,35),I2=Math.pow(2,42),_2=Math.pow(2,49),Pe=128,Rt=127;function Ne(r){if(r<MT)return 1;if(r<BT)return 2;if(r<UT)return 3;if(r<T2)return 4;if(r<C2)return 5;if(r<I2)return 6;if(r<_2)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Li(r,e,t=0){switch(Ne(r)){case 8:e[t++]=r&255|Pe,r/=128;case 7:e[t++]=r&255|Pe,r/=128;case 6:e[t++]=r&255|Pe,r/=128;case 5:e[t++]=r&255|Pe,r/=128;case 4:e[t++]=r&255|Pe,r>>>=7;case 3:e[t++]=r&255|Pe,r>>>=7;case 2:e[t++]=r&255|Pe,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function FT(r,e,t=0){switch(Ne(r)){case 8:e.set(t++,r&255|Pe),r/=128;case 7:e.set(t++,r&255|Pe),r/=128;case 6:e.set(t++,r&255|Pe),r/=128;case 5:e.set(t++,r&255|Pe),r/=128;case 4:e.set(t++,r&255|Pe),r>>>=7;case 3:e.set(t++,r&255|Pe),r>>>=7;case 2:e.set(t++,r&255|Pe),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function R2(r,e){let t=r[e],n=0;if(n+=t&Rt,t<Pe||(t=r[e+1],n+=(t&Rt)<<7,t<Pe)||(t=r[e+2],n+=(t&Rt)<<14,t<Pe)||(t=r[e+3],n+=(t&Rt)<<21,t<Pe)||(t=r[e+4],n+=(t&Rt)*T2,t<Pe)||(t=r[e+5],n+=(t&Rt)*C2,t<Pe)||(t=r[e+6],n+=(t&Rt)*I2,t<Pe)||(t=r[e+7],n+=(t&Rt)*_2,t<Pe))return n;throw new RangeError("Could not decode varint")}function $T(r,e){let t=r.get(e),n=0;if(n+=t&Rt,t<Pe||(t=r.get(e+1),n+=(t&Rt)<<7,t<Pe)||(t=r.get(e+2),n+=(t&Rt)<<14,t<Pe)||(t=r.get(e+3),n+=(t&Rt)<<21,t<Pe)||(t=r.get(e+4),n+=(t&Rt)*T2,t<Pe)||(t=r.get(e+5),n+=(t&Rt)*C2,t<Pe)||(t=r.get(e+6),n+=(t&Rt)*I2,t<Pe)||(t=r.get(e+7),n+=(t&Rt)*_2,t<Pe))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=Ge(Ne(r))),e instanceof Uint8Array?Li(r,e,t):FT(r,e,t)}function Or(r,e=0){return r instanceof Uint8Array?R2(r,e):$T(r,e)}var P2=new Float32Array([-0]),xs=new Uint8Array(P2.buffer);function T8(r,e,t){P2[0]=r,e[t]=xs[0],e[t+1]=xs[1],e[t+2]=xs[2],e[t+3]=xs[3]}function C8(r,e){return xs[0]=r[e],xs[1]=r[e+1],xs[2]=r[e+2],xs[3]=r[e+3],P2[0]}var L2=new Float64Array([-0]),Pt=new Uint8Array(L2.buffer);function I8(r,e,t){L2[0]=r,e[t]=Pt[0],e[t+1]=Pt[1],e[t+2]=Pt[2],e[t+3]=Pt[3],e[t+4]=Pt[4],e[t+5]=Pt[5],e[t+6]=Pt[6],e[t+7]=Pt[7]}function _8(r,e){return Pt[0]=r[e],Pt[1]=r[e+1],Pt[2]=r[e+2],Pt[3]=r[e+3],Pt[4]=r[e+4],Pt[5]=r[e+5],Pt[6]=r[e+6],Pt[7]=r[e+7],L2[0]}var KT=BigInt(Number.MAX_SAFE_INTEGER),VT=BigInt(Number.MIN_SAFE_INTEGER),lr=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 bo;if(e<KT&&e>VT)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>R8&&(s=0n,++n>R8&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return bo;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}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):bo}},bo=new lr(0,0);bo.toBigInt=function(){return 0n};bo.zzEncode=bo.zzDecode=function(){return this};bo.length=function(){return 1};var R8=4294967296n;function P8(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 L8(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function k2(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Mr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function md(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var D2=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=he(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,Mr(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 Mr(this,4);return md(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mr(this,4);return md(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mr(this,4);let e=C8(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mr(this,4);let e=_8(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 Mr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return L8(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while((this.buf[this.pos++]&128)!==0);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 lr(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 Mr(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 Mr(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 Mr(this,8);let e=md(this.buf,this.pos+=4),t=md(this.buf,this.pos+=4);return new lr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=R2(this.buf,this.pos);return this.pos+=Ne(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function yc(r){return new D2(r instanceof Uint8Array?r:r.subarray())}function se(r,e,t){let n=yc(r);return e.decode(n,void 0,t)}function N2(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ge(i);s+i>e&&(n=Ge(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var wo=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function O2(){}var B2=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},HT=N2();function qT(r){return globalThis.Buffer!=null?Ge(r):HT(r)}var wc=class{len;head;tail;states;constructor(){this.len=0,this.head=new wo(O2,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new U2((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(gd,10,lr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=lr.fromBigInt(e);return this._push(gd,t.length(),t)}uint64Number(e){return this._push(Li,Ne(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=lr.fromBigInt(e).zzEncode();return this._push(gd,t.length(),t)}sint64Number(e){let t=lr.fromNumber(e).zzEncode();return this._push(gd,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(M2,1,e?1:0)}fixed32(e){return this._push(bc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=lr.fromBigInt(e);return this._push(bc,4,t.lo)._push(bc,4,t.hi)}fixed64Number(e){let t=lr.fromNumber(e);return this._push(bc,4,t.lo)._push(bc,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(T8,4,e)}double(e){return this._push(I8,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(M2,1,0):this.uint32(t)._push(GT,t,e)}string(e){let t=P8(e);return t!==0?this.uint32(t)._push(k2,t,e):this._push(M2,1,0)}fork(){return this.states=new B2(this),this.head=this.tail=new wo(O2,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 wo(O2,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=qT(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function M2(r,e,t){e[t]=r&255}function zT(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var U2=class extends wo{next;constructor(e,t){super(zT,e,t),this.next=void 0}};function gd(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 bc(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 GT(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(wc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(WT,e,r),this},wc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(jT,e,r),this});function WT(r,e,t){e.set(r,t)}function jT(r,e,t){r.length<40?k2(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function F2(){return new wc}function oe(r,e){let t=F2();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ie(r,e,t){let n=yc(r);yield*e.stream(n,".",void 0,t)}var yd={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function bd(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function lt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i,a){};return bd("enum",yd.VARINT,t,n,s)}function ae(r,e,t){return bd("message",yd.LENGTH_DELIMITED,r,e,t)}var pe=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ec=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Oe||(Oe={}));var $2;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})($2||($2={}));(function(r){r.codec=()=>lt($2)})(Oe||(Oe={}));var an;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Oe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=Oe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Oe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(an||(an={}));var xc;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Oe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=Oe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Oe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(xc||(xc={}));var Sc={};fe(Sc,{MAX_RSA_KEY_SIZE:()=>K2,generateRSAKeyPair:()=>X2,jwkToJWKKeyPair:()=>M8,jwkToPkcs1:()=>ZT,jwkToPkix:()=>z2,jwkToRSAPrivateKey:()=>Y2,pkcs1MessageToJwk:()=>H2,pkcs1MessageToRSAPrivateKey:()=>wd,pkcs1ToJwk:()=>QT,pkcs1ToRSAPrivateKey:()=>G2,pkixMessageToJwk:()=>q2,pkixMessageToRSAPublicKey:()=>j2,pkixToJwk:()=>JT,pkixToRSAPublicKey:()=>W2});var ki=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Sc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return O8(this.jwk,t,e,n)}},vc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Sc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return N8(this.jwk,e,t)}};var K2=8192,V2=18,YT=1062,XT=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function QT(r){let e=wr(r);return H2(e)}function H2(r){return{n:k(r[1],"base64url"),e:k(r[2],"base64url"),d:k(r[3],"base64url"),p:k(r[4],"base64url"),q:k(r[5],"base64url"),dp:k(r[6],"base64url"),dq:k(r[7],"base64url"),qi:k(r[8],"base64url"),kty:"RSA"}}function ZT(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 v("JWK was missing components");return Dr([Ft(Uint8Array.from([0])),Ft(T(r.n,"base64url")),Ft(T(r.e,"base64url")),Ft(T(r.d,"base64url")),Ft(T(r.p,"base64url")),Ft(T(r.q,"base64url")),Ft(T(r.dp,"base64url")),Ft(T(r.dq,"base64url")),Ft(T(r.qi,"base64url"))]).subarray()}function JT(r){let e=wr(r,{offset:0});return q2(e)}function q2(r){let e=wr(r[1],{offset:0});return{kty:"RSA",n:k(e[0],"base64url"),e:k(e[1],"base64url")}}function z2(r){if(r.n==null||r.e==null)throw new v("JWK was missing components");return Dr([XT,rc(Dr([Ft(T(r.n,"base64url")),Ft(T(r.e,"base64url"))]))]).subarray()}function G2(r){let e=wr(r);return wd(e)}function wd(r){let e=H2(r);return Y2(e)}function W2(r,e){if(r.byteLength>=YT)throw new _r("Key size is too large");let t=wr(r,{offset:0});return j2(t,r,e)}function j2(r,e,t){let n=q2(r);if(t==null){let s=It(an.encode({Type:Oe.RSA,Data:e}));t=Ut(V2,s)}return new ki(n,t)}function Y2(r){if(U8(r)>K2)throw new v("Key size is too large");let e=M8(r),t=It(an.encode({Type:Oe.RSA,Data:z2(e.publicKey)})),n=Ut(V2,t);return new vc(e.privateKey,new ki(e.publicKey,n))}async function X2(r){if(r>K2)throw new v("Key size is too large");let e=await B8(r),t=It(an.encode({Type:Oe.RSA,Data:z2(e.publicKey)})),n=Ut(V2,t);return new vc(e.privateKey,new ki(e.publicKey,n))}function M8(r){if(r==null)throw new v("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function B8(r,e){let t=await st.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await eC(t,e);return{privateKey:n[0],publicKey:n[1]}}async function N8(r,e,t){let n=await st.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await st.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,he(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function O8(r,e,t,n){let s=await st.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await st.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,he(e),he(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function eC(r,e){if(r.privateKey==null||r.publicKey==null)throw new v("Private and public key are required");let t=await Promise.all([st.get().subtle.exportKey("jwk",r.privateKey),st.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function U8(r){if(r.kty!=="RSA")throw new v("invalid key type");if(r.n==null)throw new v("invalid key modulus");return T(r.n,"base64url").length*8}var Ed=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Rn(e),Ct(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),tt(s)}update(e){return wi(this),this.iHash.update(e),this}digestInto(e){wi(this),Gu(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Eo=(()=>{let r=((e,t,n)=>new Ed(e,t).update(n).digest());return r.create=(e,t)=>new Ed(e,t),r})();var tC=BigInt(0),Q2=class extends Error{constructor(e=""){super(e)}},Nn={Err:Q2,_tlv:{encode:(r,e)=>{let{Err:t}=Nn;if(kn(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(H5(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=ac(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?ac(s.length/2|128):"";return ac(r)+o+s+e},decode(r,e){let{Err:t}=Nn;e=Ee(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Nn;if(ed(r),r<tC)throw new e("integer: negative integers are not allowed");let t=ac(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Nn;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return rn(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:s}=Nn;if(e!==void 0&&(kn(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=Ee(r,void 0,"signature"),{v:i,l:a}=s.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=s.decode(2,i),{v:u,l:d}=s.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Nn;_t(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},xd=(Object.freeze(Nn._tlv),Object.freeze(Nn._int),Object.freeze(Nn));var F8=(r,e)=>(r+(r>=0?e:-e)/$8)/e;function rC(r,e,t){sn("scalar",r,On,t);let[[n,s],[o,i]]=e,a=F8(i*r,t),c=F8(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<On,f=u<On;d&&(l=-l),f&&(u=-u);let h=lc(Math.ceil(vi(t)/2))+xo;if(l<On||l>=h||u<On||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function em(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Z2(r,e){_t(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Yt(t.lowS,"lowS"),Yt(t.prehash,"prehash"),t.format!==void 0&&em(t.format),t}var On=BigInt(0),xo=BigInt(1),$8=BigInt(2),J2=BigInt(3),nC=BigInt(4);function K8(r,e={}){let t=cd("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;_t(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:f,toBytes:h}=e,p=e.randomBytes===void 0?Ln:e.randomBytes;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(_=>[..._])}:void 0,y=H8(n,s);function m(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function b(_,E,A){if(E.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:R,y:U}=E.toAffine(),q=n.toBytes(R);if(Yt(A,"isCompressed"),A){m();let z=!n.isOdd(U);return Er(V8(z),q)}else return Er(Uint8Array.of(4),q,n.toBytes(U))}function w(_){Ee(_,void 0,"Point");let{publicKey:E,publicKeyUncompressed:A}=y,R=_.length,U=_[0],q=_.subarray(1);if(l&&R===1&&U===0)return{x:n.ZERO,y:n.ZERO};if(R===E&&(U===2||U===3)){let z=n.fromBytes(q);if(!n.isValid(z))throw new Error("bad point: is not on curve, wrong x");let X=L(z),Q;try{Q=n.sqrt(X)}catch($e){let Me=$e instanceof Error?": "+$e.message:"";throw new Error("bad point: is not on curve, sqrt error"+Me)}m();let ce=n.isOdd(Q);return(U&1)===1!==ce&&(Q=n.neg(Q)),{x:z,y:Q}}else if(R===A&&U===4){let z=n.BYTES,X=n.fromBytes(q.subarray(0,z)),Q=n.fromBytes(q.subarray(z,z*2));if(!P(X,Q))throw new Error("bad point: is not on curve");return{x:X,y:Q}}else throw new Error(`bad point: got length ${R}, expected compressed=${E} or uncompressed=${A}`)}let x=h===void 0?b:h,S=f===void 0?w:f,C=n.mul(o.b,J2),I=n.is0(o.a)?_=>n.ZERO:_=>n.mul(o.a,_);function L(_){let E=n.sqr(_),A=n.mul(E,_);return n.add(n.add(A,n.mul(_,o.a)),o.b)}function P(_,E){let A=n.sqr(E),R=L(_);return n.eql(A,R)}if(!P(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let B=n.mul(n.pow(o.a,J2),nC),W=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(B,W)))throw new Error("bad curve params: a or b");function G(_,E,A=!1){if(!n.isValid(E)||A&&n.is0(E))throw new Error(`bad point coordinate ${_}`);return typeof E=="object"&&E!==null?n.create(E):E}function Z(_){if(!(_ instanceof D))throw new Error("Weierstrass Point expected")}function N(_){if(!g||!g.basises)throw new Error("no endo");return rC(_,g.basises,s.ORDER)}function $(_,E,A,R){if(!s.isValid(R))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:U,k1:q,k2neg:z,k2:X}=N(R),Q=new D(n.mul(A.X,g.beta),A.Y,A.Z);_.push(U?A.negate():A,z?Q.negate():Q),E.push(q,X)}else _.push(A),E.push(R)}let O=new WeakSet;class D{static BASE=new D(o.Gx,o.Gy,n.ONE);static ZERO=new D(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(E,A,R){this.X=G("x",E),this.Y=G("y",A,!0),this.Z=G("z",R),Object.freeze(this)}static CURVE(){return o}static fromAffine(E){let{x:A,y:R}=E||{};if(!E||!n.isValid(A)||!n.isValid(R))throw new Error("invalid affine point");if(E instanceof D)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(R)?D.ZERO:new D(A,R,n.ONE)}static fromBytes(E){let A=D.fromAffine(S(Ee(E,void 0,"point")));return A.assertValidity(),A}static fromHex(E){return D.fromBytes(xi(E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,A=!0){return M.setWindowSize(this,E),A||this.multiply(J2),this}assertValidity(){let E=this;if(E.is0()){if(l&&n.is0(E.X)&&n.eql(E.Y,n.ONE)&&n.is0(E.Z))return;throw new Error("bad point: ZERO")}if(O.has(E))return;let{x:A,y:R}=E.toAffine();if(!n.isValid(A)||!n.isValid(R))throw new Error("bad point: x or y not field elements");if(!P(A,R))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");O.add(E)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){Z(E);let{X:A,Y:R,Z:U}=this,{X:q,Y:z,Z:X}=E,Q=n.eql(n.mul(A,X),n.mul(q,U)),ce=n.eql(n.mul(R,X),n.mul(z,U));return Q&&ce}negate(){return new D(this.X,n.neg(this.Y),this.Z)}double(){let{X:E,Y:A,Z:R}=this,U=n.ZERO,q=n.ZERO,z=n.ZERO,X=n.mul(E,E),Q=n.mul(A,A),ce=n.mul(R,R),me=n.mul(E,A);return me=n.add(me,me),z=n.mul(E,R),z=n.add(z,z),U=I(z),q=n.mul(C,ce),q=n.add(U,q),U=n.sub(Q,q),q=n.add(Q,q),q=n.mul(U,q),U=n.mul(me,U),z=n.mul(C,z),ce=I(ce),me=n.sub(X,ce),me=I(me),me=n.add(me,z),z=n.add(X,X),X=n.add(z,X),X=n.add(X,ce),X=n.mul(X,me),q=n.add(q,X),ce=n.mul(A,R),ce=n.add(ce,ce),X=n.mul(ce,me),U=n.sub(U,X),z=n.mul(ce,Q),z=n.add(z,z),z=n.add(z,z),new D(U,q,z)}add(E){Z(E);let{X:A,Y:R,Z:U}=this,{X:q,Y:z,Z:X}=E,Q=n.ZERO,ce=n.ZERO,me=n.ZERO,$e=n.mul(A,q),Me=n.mul(R,z),Je=n.mul(U,X),Wt=n.add(A,R),Be=n.add(q,z);Wt=n.mul(Wt,Be),Be=n.add($e,Me),Wt=n.sub(Wt,Be),Be=n.add(A,U);let qe=n.add(q,X);return Be=n.mul(Be,qe),qe=n.add($e,Je),Be=n.sub(Be,qe),qe=n.add(R,U),Q=n.add(z,X),qe=n.mul(qe,Q),Q=n.add(Me,Je),qe=n.sub(qe,Q),me=I(Be),Q=n.mul(C,Je),me=n.add(Q,me),Q=n.sub(Me,me),me=n.add(Me,me),ce=n.mul(Q,me),Me=n.add($e,$e),Me=n.add(Me,$e),Je=I(Je),Be=n.mul(C,Be),Me=n.add(Me,Je),Je=n.sub($e,Je),Je=I(Je),Be=n.add(Be,Je),$e=n.mul(Me,Be),ce=n.add(ce,$e),$e=n.mul(qe,Be),Q=n.mul(Wt,Q),Q=n.sub(Q,$e),$e=n.mul(Wt,Me),me=n.mul(qe,me),me=n.add(me,$e),new D(Q,ce,me)}subtract(E){return Z(E),this.add(E.negate())}is0(){return this.equals(D.ZERO)}multiply(E){if(!s.isValidNot0(E))throw new RangeError("invalid scalar: out of range");let{p:A,f:R}=M.mulSecret(this,E,i,Y);return Y([A,R])[0]}multiplyUnsafe(E){let A=this,R=E;if(!s.isValid(R))throw new RangeError("invalid scalar: out of range");if(R===On||A.is0())return D.ZERO;if(R===xo)return A;if(M.hasWindowSize(this))return M.mulUnsafe(A,R,Y);let U=[],q=[];return $(U,q,A,R),ad(D,U,q)}mulAddUnsafe(E,A,R){Z(A);let U=[],q=[];return $(U,q,this,E),$(U,q,A,R),ad(D,U,q)}toAffine(E){let A=this,R=E;if(R!=null&&!n.isValid(R))throw new RangeError('"invertedZ" expected valid field element');let{X:U,Y:q,Z:z}=A;if(n.eql(z,n.ONE))return{x:U,y:q};let X=A.is0();R==null&&(R=X?n.ONE:n.inv(z));let Q=n.mul(U,R),ce=n.mul(q,R),me=n.mul(z,R);if(X)return{x:n.ZERO,y:n.ZERO};if(!n.eql(me,n.ONE))throw new Error("invZ was invalid");return{x:Q,y:ce}}isTorsionFree(){return i===xo?!0:d?d(D,this):M.mulUnsafe(this,a).is0()}clearCofactor(){return i===xo?this:u?u(D,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===xo?this.is0():this.clearCofactor().is0()}toBytes(E=!0){return Yt(E,"isCompressed"),this.assertValidity(),x(D,this,E)}toHex(E=!0){return ic(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Y=_=>id(D,_),M=new Ti(D,p);return M.bits>=6&&D.BASE.precompute(6),Object.freeze(D.prototype),Object.freeze(D),D}function V8(r){return Uint8Array.of(r?2:3)}function H8(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function sC(r,e={}){Es(r);let{Fn:t}=r,n=e.randomBytes===void 0?Ln:e.randomBytes,s=Object.assign(H8(r.Fp,t),{seed:Math.max(sd(t.ORDER),16)});function o(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:y}=s;try{let m=h.length;return p===!0&&m!==g||p===!1&&m!==y?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(s.seed):h,od(Ee(h,s.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:y}=s,m=t._lengths;if(!ys(h))return;let b=Ee(h,void 0,"key").length,w=b===g||b===y,x=b===p||!!m?.includes(b);if(!(w&&x))return w}function u(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h),m=r.fromBytes(p);if(m.is0())throw new Error("invalid public key: point at infinity");return m.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=Ci(a,c);return Object.freeze(d),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:s})}function q8(r,e,t={}){Es(r);let n=e;Rn(n),_t(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},t),o=s.randomBytes===void 0?Ln:s.randomBytes,i=s.hmac===void 0?(_,E)=>Eo(n,_,E):s.hmac,{Fp:a,Fn:c}=r,{ORDER:l,BITS:u}=c,d=sd(l),f=w2(o,d),{keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m}=sC(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},w=l*$8+xo<a.ORDER;function x(_){let E=l>>xo;return _>E}function S(_,E){if(!c.isValidNot0(E))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return E}function C(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function I(_,E,A){return C(),(_===A?0:2)|Number(a.isOdd(E))}function L(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(_,E){em(E);let A=m.signature,R=E==="compact"?A:E==="recovered"?A+1:void 0;return Ee(_,R)}class B{r;s;recovery;constructor(E,A,R){if(this.r=S("r",E),this.s=S("s",A),R!=null){if(L(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(E,A=b.format){P(E,A);let R;if(A==="der"){if(E.length>2*c.BYTES+16)throw new xd.Err("invalid signature: DER signature too long");let{r:X,s:Q}=xd.toSig(Ee(E),c.BYTES+1);return new B(X,Q)}A==="recovered"&&(R=E[0],A="compact",E=E.subarray(1));let U=m.signature/2,q=E.subarray(0,U),z=E.subarray(U,U*2);return new B(c.fromBytes(q),c.fromBytes(z),R)}static fromHex(E,A){return this.fromBytes(xi(E),A)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new B(this.r,this.s,E)}recoverPublicKey(E){let{r:A,s:R}=this,U=this.assertRecovery(),q=U===2||U===3?A+l:A;if(!a.isValid(q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let z=a.toBytes(q),X=r.fromBytes(Er(V8((U&1)===0),z)),Q=c.inv(q),ce=G(Ee(E,void 0,"msgHash")),me=c.create(-ce*Q),$e=c.create(R*Q),Me=r.BASE.mulAddUnsafe(me,X,$e);if(Me.is0())throw new Error("invalid recovery: point at infinify");return Me.assertValidity(),Me}hasHighS(){return x(this.s)}toBytes(E=b.format){if(em(E),E==="der")return xi(xd.hexFromSig(this));let{r:A,s:R}=this,U=c.toBytes(A),q=c.toBytes(R);return E==="recovered"?(L(),Er(Uint8Array.of(this.assertRecovery()),U,q)):Er(U,q)}toHex(E){return ic(this.toBytes(E))}}Object.freeze(B.prototype),Object.freeze(B);let W=s.bits2int===void 0?function(E){if(E.length>8192)throw new Error("input is too large");let A=rn(E),R=E.length*8-u;return R>0?A>>BigInt(R):A}:s.bits2int,G=s.bits2int_modN===void 0?function(E){return c.create(W(E))}:s.bits2int_modN,Z=lc(u);function N(_){return sn("num < 2^"+u,_,On,Z),c.toBytes(_)}function $(_,E){return Ee(_,void 0,"message"),E?Ee(n(_),void 0,"prehashed message"):_}function O(_,E,A){let{lowS:R,prehash:U,extraEntropy:q}=Z2(A,b);_=$(_,U);let z=G(_),X=c.fromBytes(E);if(!c.isValidNot0(X))throw new Error("invalid private key");let Q=[N(X),N(z)];if(q!=null&&q!==!1){let Me=q===!0?o(m.secretKey):q;Q.push(Ee(Me,void 0,"extraEntropy"))}let ce=Er(...Q),me=z;function $e(Me){let Je=W(Me);if(!c.isValidNot0(Je))return;let Wt=r.BASE.multiply(Je).toAffine(),Be=c.create(Wt.x);if(Be===On)return;let qe;if(f!==void 0){let is=rn(od(f(d),l)),hS=c.inv(c.mul(is,Je)),pS=c.mul(is,me),mS=c.mul(is,X);qe=c.create(hS*c.create(pS+mS*Be))}else{let is=J5(Je,l);qe=c.create(is*c.create(me+Be*X))}if(qe===On)return;let si=I(Wt.x,Wt.y,Be),Ha=qe;return R&&x(qe)&&(Ha=c.neg(qe),si^=1),new B(Be,Ha,w?void 0:si)}return{seed:ce,k2sig:$e}}function D(_,E,A={}){let{seed:R,k2sig:U}=O(_,E,A);return z5(n.outputLen,c.BYTES,i)(R,U).toBytes(A.format)}function Y(_,E,A,R={}){let{lowS:U,prehash:q,format:z}=Z2(R,b);if(A=Ee(A,void 0,"publicKey"),E=$(E,q),!ys(_)){let X=_ instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+X)}P(_,z);try{let X=B.fromBytes(_,z),Q=r.fromBytes(A);if(Q.is0()||U&&X.hasHighS())return!1;let{r:ce,s:me}=X,$e=G(E),Me=c.inv(me),Je=c.create($e*Me),Wt=c.create(ce*Me),Be=r.BASE.mulAddUnsafe(Je,Q,Wt);if(Be.is0())return!1;let qe=Be.toAffine();return!(c.create(qe.x)!==ce||z==="recovered"&&X.recovery!==I(qe.x,qe.y,ce))}catch{return!1}}function M(_,E,A={}){let{prehash:R}=Z2(A,b);return E=$(E,R),B.fromBytes(_,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m,Point:r,sign:D,verify:Y,recoverPublicKey:M,Signature:B,hash:n})}var rm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oC={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var z8=BigInt(2);function iC(r){let e=rm.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ke(u,t,e)*u%e,f=Ke(d,t,e)*u%e,h=Ke(f,z8,e)*l%e,p=Ke(h,s,e)*h%e,g=Ke(p,o,e)*p%e,y=Ke(g,a,e)*g%e,m=Ke(y,c,e)*y%e,b=Ke(m,a,e)*g%e,w=Ke(b,t,e)*u%e,x=Ke(w,i,e)*p%e,S=Ke(x,n,e)*l%e,C=Ke(S,z8,e);if(!tm.eql(tm.sqr(C),r))throw new Error("Cannot find square root");return C}var tm=Ai(rm.p,{sqrt:iC}),aC=K8(rm,{Fp:tm,endo:oC}),Br=q8(aC,It);var G8=32;function W8(r,e,t){let n=yt.digest(e instanceof Uint8Array?e:e.subarray());if(_i(n))return n.then(({digest:s})=>(t?.signal?.throwIfAborted(),Br.sign(s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new pc(String(s))});try{return Br.sign(n.digest,r,{prehash:!1,format:"der"})}catch(s){throw new pc(String(s))}}function j8(r,e,t,n){let s=yt.digest(t instanceof Uint8Array?t:t.subarray());if(_i(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Br.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new mc(String(o))});try{return n?.signal?.throwIfAborted(),Br.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new mc(String(o))}}var Ac=class{type="secp256k1";raw;_key;constructor(e){this._key=Q8(e),this.raw=Y8(this._key)}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return j8(this._key,t,e,n)}},Tc=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=X8(e),this.publicKey=new Ac(t??Z8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return W8(this.raw,e,t)}};function nm(r){return new Tc(r)}function sm(r){return new Ac(r)}async function J8(){let r=cC();return new Tc(r)}function Y8(r){return Br.Point.fromBytes(r).toBytes()}function X8(r){try{return Br.getPublicKey(r,!0),r}catch(e){throw new qa(String(e))}}function Q8(r){try{return Br.Point.fromBytes(r),r}catch(e){throw new _r(String(e))}}function Z8(r){try{return Br.getPublicKey(r,!0)}catch(e){throw new qa(String(e))}}function cC(){return Br.utils.randomSecretKey()}async function vd(r,e){if(r==="Ed25519")return A8();if(r==="secp256k1")return J8();if(r==="RSA")return X2(lC(e));if(r==="ECDSA")return A5(uC(e));throw new Lr}function We(r,e){let{Type:t,Data:n}=an.decode(r),s=n??new Uint8Array;switch(t){case Oe.RSA:return W2(s,e);case Oe.Ed25519:return A2(s);case Oe.secp256k1:return sm(s);case Oe.ECDSA:return Jp(s);default:throw new Lr}}function e7(r){let{Type:e,Data:t}=an.decode(r.digest),n=t??new Uint8Array;switch(e){case Oe.Ed25519:return A2(n);case Oe.secp256k1:return sm(n);case Oe.ECDSA:return Jp(n);default:throw new Lr}}function nt(r){return an.encode({Type:Oe[r.type],Data:r.raw})}function t7(r){let e=xc.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Oe.RSA:return G2(t);case Oe.Ed25519:return S2(t);case Oe.secp256k1:return nm(t);case Oe.ECDSA:return w5(t);default:throw new Lr}}function r7(r){if(r.byteLength===cr)return S2(r);if(r.byteLength===G8)return nm(r);let e=wr(r),t=e[2]?.[0];if(t===e5||t===t5||t===r5)return Zp(e);if(e.length>8)return wd(e);throw new v("Could not extract private key from raw bytes")}function vo(r){return xc.encode({Type:Oe[r.type],Data:r.raw})}function lC(r){return r==null?2048:parseInt(r,10)}function uC(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new v("Unsupported curve, should be P-256, P-384 or P-521")}var Cc=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),vs=new Uint32Array(80),om=class extends po{A=Cc[0]|0;B=Cc[1]|0;C=Cc[2]|0;D=Cc[3]|0;E=Cc[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o}=this;return[e,t,n,s,o]}set(e,t,n,s,o){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let c=0;c<16;c++,t+=4)vs[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)vs[c]=Wu(vs[c-3]^vs[c-8]^vs[c-14]^vs[c-16],1);let{A:n,B:s,C:o,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Xu(s,o,i),u=1518500249):c<40?(l=s^o^i,u=1859775393):c<60?(l=Qu(s,o,i),u=2400959708):(l=s^o^i,u=3395469782);let d=Wu(n,5)+l+a+u+vs[c]|0;a=i,i=o,o=Wu(s,30),s=n,n=d}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,s,o,i,a)}roundClean(){tt(vs)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),tt(this.buffer)}},n7=oc(()=>new om);function s7(r,e,t,n){Rn(r);let s=o2({dkLen:32,asyncTick:10},n),{c:o,dkLen:i,asyncTick:a}=s;if(bt(o,"c"),bt(i,"dkLen"),bt(a,"asyncTick"),o<1)throw new Error('"c" (iterations) must be >= 1');if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=n2(e,"password");try{let l=n2(t,"salt");try{let u=new Uint8Array(i),{iHash:d,oHash:f,outputLen:h}=Eo.create(r,c),p=new Uint8Array(h),g=dC(d,f,l,p);return{c:o,dkLen:i,asyncTick:a,DK:u,outputLen:h,eng:g}}finally{typeof t=="string"&&tt(l)}}finally{typeof e=="string"&&tt(c)}}function dC(r,e,t,n){let s=new Uint8Array(4),o=Ei(s),i=r._cloneInto().update(t),a=e._cloneInto(),c=r._cloneInto,l=e._cloneInto;return{u1:(u,d)=>{o.setInt32(0,u,!1),i._cloneInto(a).update(s).digestInto(n),e._cloneInto(a).update(n).digestInto(n),d.set(n.subarray(0,d.length))},rounds:(u,d)=>{for(let f=1;f<u;f++){c.call(r,a).update(n).digestInto(n),l.call(e,a).update(n).digestInto(n);for(let h=0;h<d.length;h++)d[h]^=n[h]}},output:u=>(r.destroy(),e.destroy(),i.destroy(),a.destroy(),tt(n),u)}}function o7(r,e,t,n){let{c:s,dkLen:o,DK:i,outputLen:a,eng:c}=s7(r,e,t,n);for(let l=1,u=0;u<o;l++,u+=a){let d=i.subarray(u,u+a);c.u1(l,d),c.rounds(s,d)}return c.output(i)}async function Sd(r,e,t,n){let{c:s,dkLen:o,asyncTick:i,DK:a,outputLen:c,eng:l}=s7(r,e,t,n),u=()=>{l.output(a),tt(a)};for(let d=1,f=0;f<o;d++,f+=c){let h=a.subarray(f,f+c);l.u1(d,h),await B5(s-1,i,()=>{l.rounds(2,h)},u)}return l.output(a)}var i7={sha1:n7,"sha2-256":It,"sha2-512":Pn};function Ic(r,e,t,n,s){if(s!=="sha1"&&s!=="sha2-256"&&s!=="sha2-512"){let a=Object.keys(i7).join(" / ");throw new v(`Hash '${s}' is unknown or not supported. Must be ${a}`)}let o=i7[s],i=o7(o,r,e,{c:t,dkLen:n});return _n.encode(i).substring(1)}var Mn="/",a7=new TextEncoder().encode(Mn),Ad=a7[0],Lt=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(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]!==Ad)throw new Error("Invalid key")}toString(e="utf8"){return k(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mn))}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=a7),this._buf[0]!==Ad){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ad,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ad;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>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(Mn).slice(1)}type(){return fC(this.baseNamespace())}name(){return hC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mn)||(e+=Mn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mn):new r(e.slice(0,-1).join(Mn))}child(e){return this.toString()===Mn?e:e.toString()===Mn?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(),...pC(e.map(t=>t.namespaces()))])}};function fC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function hC(r){let e=r.split(":");return e[e.length-1]}function pC(r){return[].concat(...r)}var ay=oi(g7(),1);var im={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var Di={};fe(Di,{create:()=>IC,derivedEmptyPasswordKey:()=>Td});var Td={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function IC(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,s=r?.digest??"SHA-256",o=r?.saltLength??16,i=r?.iterations??32767,a=st.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof f=="string"&&(f=T(f));let y;if(f.length===0){y=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},w=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},w=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(g,y,he(d));return et([h,g.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,o),p=d.subarray(o,o+n),g=d.subarray(o+n),y={name:e,iv:p};typeof f=="string"&&(f=T(f));let m;if(f.length===0)try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},x=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},x=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,m,he(g));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var we=oi(y7());function So(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 Ss(r,e,t=-1){let n=t,s=r,o=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),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[o-u-1]=Math.floor(s/d),s-=l[o-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function _d(...r){let e=0,t=0;for(let o of r)e+=o.length;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let o of r)s.set(o,t),t+=o.length;return s}function cm(){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=So(t,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=r[a];return o[0]&=127,So(o,8)-n}function b7(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=Ss(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Ss(e,8,n),o=new Uint8Array(s);if(o[0]&128){let i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function w7(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}function Qt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,s=Array.from({length:n});for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(t)}var q$=Math.log(2);function Rd(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function lm(r){let e=0,t=0;for(let s=0;s<r.length;s++){let o=r[s];e+=o.byteLength}let n=new Uint8Array(e);for(let s=0;s<r.length;s++){let o=r[s];n.set(new Uint8Array(o),t),t+=o.byteLength}return n.buffer}function Vn(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 Pc=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return lm(this.items)}},_c=[new Uint8Array([1])],E7="0123456789";var Oi="",un=new ArrayBuffer(0),um=new Uint8Array(0),Lc="EndOfContent",v7="OCTET STRING",S7="BIT STRING";function Hn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var s;super(...n);let o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?we.BufferSourceConverter.toUint8Array(o.valueHex):um}fromBER(n,s,o,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Vn(this,a,s,o))return-1;let c=s+o;return this.valueHexView=a.subarray(s,c),this.valueHexView.length?(this.blockLength=o,c):(this.warnings.push("Zero buffer length"),s)}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",un)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:we.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Un=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Oi,warnings:n=[],valueBeforeDecode:s=um}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=we.BufferSourceConverter.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:we.Convert.ToHex(this.valueBeforeDecodeView)}}};Un.NAME="baseBlock";var wt=class extends Un{fromBER(e,t,n,s){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'")}};wt.NAME="valueBlock";var Pd=class extends Hn(Un){constructor({idBlock:e={}}={}){var t,n,s,o;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?we.BufferSourceConverter.toUint8Array(e.valueHex):um,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!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",un}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,t|=o,s[0]=t}return s.buffer}if(!this.isHexOnly){let s=Ss(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,t,n){let s=we.BufferSourceConverter.toUint8Array(e);if(!Vn(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[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=(o[0]&32)===32,this.isHexOnly=!1;let a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(o[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=o[u+1]&127;this.blockLength<=9?this.tagNumber=So(l,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}}};Pd.NAME="identificationBlock";var Ld=class extends Un{constructor({lenBlock:e={}}={}){var t,n,s;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=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,t,n){let s=we.BufferSourceConverter.toUint8Array(e);if(!Vn(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=So(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 s=Ss(this.length,8);if(s.byteLength>127)return this.error="Too big length",un;if(t=new ArrayBuffer(s.byteLength+1),e)return t;let o=new Uint8Array(s);n=new Uint8Array(t),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[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}}};Ld.NAME="lengthBlock";var H={},ht=class extends Un{constructor({name:e=Oi,optional:t=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Pd(s),this.lenBlock=new Ld(s),this.valueBlock=o?new o(s):new wt(s)}fromBER(e,t,n,s){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);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 Pc;t||A7(this);let s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return t?un: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():we.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=we.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return w7(t,n)}};ht.NAME="BaseBlock";function A7(r){var e;if(r instanceof H.Constructed)for(let t of r.valueBlock.value)A7(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var kd=class extends ht{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Oi,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(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),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};kd.NAME="BaseStringBlock";var Dd=class extends Hn(wt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Dd.NAME="PrimitiveValueBlock";var T7,Nd=class extends ht{constructor(e={}){super(e,Dd),this.idBlock.isConstructed=!1}};T7=Nd;H.Primitive=T7;Nd.NAME="PRIMITIVE";var MC=100,BC=1e4,UC=16*1024*1024,FC="Maximum ASN.1 nesting depth exceeded",$C="Maximum ASN.1 node count exceeded",KC="Maximum ASN.1 content length exceeded";function Bc(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:MC,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:BC,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:UC}}function VC(r){let e=new ht({},wt);return e.error=r,{offset:-1,result:e}}function HC(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return $C}function qC(r,e){if(r>e.maxContentLength)return KC}function dm(r,e,t,n){let s=n.depth+1;if(s>n.maxDepth)return VC(FC);n.depth=s;try{return C7(r,e,t,n)}finally{n.depth-=1}}function zC(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 C7(r,e=0,t=r.length,n=Bc()){let s=e,o=new ht({},wt),i=new Un;if(!Vn(i,r,e,t))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let c=HC(n);if(c)return o.error=c,{offset:-1,result:o};let l=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),l===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=l,t-=o.idBlock.blockLength,l=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),l===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};e=l,t-=o.lenBlock.blockLength;let u=o.lenBlock.isIndefiniteForm?t:o.lenBlock.length,d=qC(u,n);if(d)return o.error=d,{offset:-1,result:o};if(!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let f=ht;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};f=H.EndOfContent;break;case 1:f=H.Boolean;break;case 2:f=H.Integer;break;case 3:f=H.BitString;break;case 4:f=H.OctetString;break;case 5:f=H.Null;break;case 6:f=H.ObjectIdentifier;break;case 10:f=H.Enumerated;break;case 12:f=H.Utf8String;break;case 13:f=H.RelativeObjectIdentifier;break;case 14:f=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:f=H.Sequence;break;case 17:f=H.Set;break;case 18:f=H.NumericString;break;case 19:f=H.PrintableString;break;case 20:f=H.TeletexString;break;case 21:f=H.VideotexString;break;case 22:f=H.IA5String;break;case 23:f=H.UTCTime;break;case 24:f=H.GeneralizedTime;break;case 25:f=H.GraphicString;break;case 26:f=H.VisibleString;break;case 27:f=H.GeneralString;break;case 28:f=H.UniversalString;break;case 29:f=H.CharacterString;break;case 30:f=H.BmpString;break;case 31:f=H.DATE;break;case 32:f=H.TimeOfDay;break;case 33:f=H.DateTime;break;case 34:f=H.Duration;break;default:{let h=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;h.idBlock=o.idBlock,h.lenBlock=o.lenBlock,h.warnings=o.warnings,o=h}}break;default:f=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=zC(o,f),l=o.fromBER(r,e,u,n),o.valueBeforeDecodeView=r.subarray(s,s+o.blockLength),{offset:l,result:o}}function mf(r,e={}){if(!r.byteLength){let t=new ht({},wt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return C7(we.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,Bc(e))}function GC(r,e){return r?1:e}var cn=class extends wt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,s){let o=we.BufferSourceConverter.toUint8Array(e),i=s??Bc();if(!Vn(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 a=t;for(;GC(this.isIndefiniteForm,n)>0;){let c=dm(o,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Lc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Lc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Pc;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return t?un:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};cn.NAME="ConstructedValueBlock";var I7,As=class extends ht{constructor(e={}){super(e,cn),this.idBlock.isConstructed=!0}fromBER(e,t,n,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);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 HeliaLibp2P=(()=>{var gS=Object.create;var Ru=Object.defineProperty;var yS=Object.getOwnPropertyDescriptor;var bS=Object.getOwnPropertyNames;var wS=Object.getPrototypeOf,ES=Object.prototype.hasOwnProperty;var Ir=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},fe=(r,e)=>{for(var t in e)Ru(r,t,{get:e[t],enumerable:!0})},M6=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bS(e))!ES.call(r,s)&&s!==t&&Ru(r,s,{get:()=>e[s],enumerable:!(n=yS(e,s))||n.enumerable});return r};var oi=(r,e,t)=>(t=r!=null?gS(wS(r)):{},M6(e||!r||!r.__esModule?Ru(t,"default",{value:r,enumerable:!0}):t,r)),xS=r=>M6(Ru({},"__esModule",{value:!0}),r);var l7=Ir((D$,c7)=>{"use strict";function mC(r){return r>=55296&&r<=56319}function gC(r){return r>=56320&&r<=57343}c7.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var s=t.length,o=0,i,a,c=0;c<s;c+=1){if(i=t.charCodeAt(c),a=t[c],mC(i)&&gC(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var d7=Ir((N$,u7)=>{"use strict";function yC(r){return r>=55296&&r<=56319}function bC(r){return r>=56320&&r<=57343}u7.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,s=null,o=null,i=0;i<t;i++)s=e.charCodeAt(i),bC(s)?o!=null&&yC(o)?n+=1:n+=3:s<=127?n+=1:s>=128&&s<=2047?n+=2:s>=2048&&s<=65535&&(n+=3),o=s;return n}});var h7=Ir((O$,f7)=>{"use strict";var wC=l7(),EC=d7();f7.exports=wC.bind(null,EC)});var g7=Ir((M$,m7)=>{"use strict";var xC=h7(),vC=/[\/\?<>\\:\*\|"]/g,SC=/[\x00-\x1f\x80-\x9f]/g,AC=/^\.+$/,TC=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function CC(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function p7(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(vC,e).replace(SC,e).replace(AC,e).replace(TC,e);return t=CC(t,e),xC(t,255)}m7.exports=function(r,e){var t=e&&e.replacement||"",n=p7(r,t);return t===""?n:p7(n,"")}});var y7=Ir(Ni=>{"use strict";var _C="[object ArrayBuffer]",Bn=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===_C}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),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])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 s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},am="string",RC=/^[0-9a-f\s]+$/i,PC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,LC=/^[a-zA-Z0-9-_]+$/,Cd=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Bn.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},vr=class{static toString(e,t=!1){let n=Bn.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},Id=class r{static isHex(e){return typeof e===am&&RC.test(e)}static isBase64(e){return typeof e===am&&PC.test(e)}static isBase64Url(e){return typeof e===am&&LC.test(e)}static ToString(e,t="utf8"){let n=Bn.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 vr.toString(n,!0);case"utf16":case"utf16be":return vr.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 vr.fromString(e,!0);case"utf16":case"utf16be":return vr.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Bn.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 Cd.fromString(e);case"utf16":case"utf16be":return vr.fromString(e);case"utf16le":case"usc2":return vr.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 Cd.toString(e);case"utf16":case"utf16be":return vr.toString(e);case"utf16le":case"usc2":return vr.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 s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Bn.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Bn.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];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 s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return vr.toString(e,t)}static FromUtf16String(e,t=!1){return vr.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,"")||""}};Id.DEFAULT_UTF8_ENCODING="utf8";function kC(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function DC(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function NC(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}Ni.BufferSourceConverter=Bn;Ni.Convert=Id;Ni.assign=kC;Ni.combine=DC;Ni.isEqual=NC});var _m=Ir(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.Netmask4Impl=void 0;Hi.ip2long=Vi;Hi.long2ip=dn;function dn(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[e,t,n,s].join(".")}var OI=48,MI=97,BI=65;function UI(r){let e=0,t=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,t=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,t=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)e=e*t+(r.charCodeAt(s)-OI)>>>0;else if(t===16)if("a"<=r[s]&&r[s]<="f")e=e*t+(10+r.charCodeAt(s)-MI)>>>0;else if("A"<=r[s]&&r[s]<="F")e=e*t+(10+r.charCodeAt(s)-BI)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[e,s]}function Vi(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=UI(r);r=r.substring(s),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var Im=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let s=e.split("/",2);e=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Vi(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Vi(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=dn(this.netLong),this.mask=dn(this.maskLong),this.hostmask=dn(~this.maskLong),this.first=this.bitmask<=30?dn(this.netLong+1):this.base,this.last=this.bitmask<=30?dn(this.netLong+this.size-2):dn(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?dn(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(Vi(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(dn(this.netLong+this.size*e),this.mask)}forEach(e){let t=Vi(this.first),n=Vi(this.last),s=0;for(;t<=n;)e(dn(t),t,s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Hi.Netmask4Impl=Im});var Ly=Ir(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.Netmask6Impl=void 0;qi.ip6bigint=Pm;qi.bigint2ip6=No;var FI=_m(),Rm=(1n<<128n)-1n;function Pm(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),s=(0,FI.ip2long)(n),o=r.substring(0,t+1)+"0:0";return Py(o)&~0xffffffffn|BigInt(s)}return Py(r)}function Py(r){let e=r.indexOf("::"),t;if(e!==-1){let s=r.substring(0,e),o=r.substring(e+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let s=0;s<8;s++){let o=t[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function No(r){if(r<0n||r>Rm)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)e[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(t=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(t=s,n=o),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var Lm=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let s=e.indexOf("/");s!==-1?(n=parseInt(e.substring(s+1),10),e=e.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Rm>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Pm(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=No(this.netBigint),this.mask=No(this.maskBigint),this.hostmask=No(~this.maskBigint&Rm),this.first=this.base,this.last=No(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(Pm(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(No(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;t<=s;)e(No(t),Number(t),o),o++,t++}toString(){return this.base+"/"+this.bitmask}};qi.Netmask6Impl=Lm});var ky=Ir(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.long2ip=Ts.ip2long=Ts.Netmask=void 0;var _f=_m();Object.defineProperty(Ts,"ip2long",{enumerable:!0,get:function(){return _f.ip2long}});Object.defineProperty(Ts,"long2ip",{enumerable:!0,get:function(){return _f.long2ip}});var $I=Ly(),km=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new $I.Netmask6Impl(e,t):this._impl=new _f.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof _f.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};Ts.Netmask=km});var J9=Ir((vX,_3)=>{"use strict";var kR=Object.prototype.hasOwnProperty,qt="~";function xl(){}Object.create&&(xl.prototype=Object.create(null),new xl().__proto__||(qt=!1));function DR(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Z9(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new DR(t,n||r,s),i=qt?qt+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Xh(r,e){--r._eventsCount===0?r._events=new xl:delete r._events[e]}function Nt(){this._events=new xl,this._eventsCount=0}Nt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)kR.call(t,n)&&e.push(qt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Nt.prototype.listeners=function(e){var t=qt?qt+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};Nt.prototype.listenerCount=function(e){var t=qt?qt+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(e,t,n,s,o,i){var a=qt?qt+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){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,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};Nt.prototype.on=function(e,t,n){return Z9(this,e,t,n,!1)};Nt.prototype.once=function(e,t,n){return Z9(this,e,t,n,!0)};Nt.prototype.removeListener=function(e,t,n,s){var o=qt?qt+e:e;if(!this._events[o])return this;if(!t)return Xh(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Xh(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Xh(this,o)}return this};Nt.prototype.removeAllListeners=function(e){var t;return e?(t=qt?qt+e:e,this._events[t]&&Xh(this,t)):(this._events=new xl,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=qt;Nt.EventEmitter=Nt;typeof _3<"u"&&(_3.exports=Nt)});var rb=Ir((qX,tb)=>{tb.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var bx=Ir(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.parseCookie=gx;Cn.parse=gx;Cn.stringifyCookie=sN;Cn.stringifySetCookie=E0;Cn.serialize=E0;Cn.parseSetCookie=oN;Cn.stringifySetCookie=E0;Cn.serialize=E0;var px=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mx=/^[\u0021-\u003A\u003C-\u007E]*$/,JD=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,eN=/^[\u0020-\u003A\u003D-\u007E]*$/,tN=/^-?\d+$/,rN=Object.prototype.toString,nN=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function gx(r,e){let t=new nN,n=r.length;if(n<2)return t;let s=e?.decode||yx,o=0;do{let i=z4(r,o,n);if(i===-1)break;let a=q4(r,o,n);if(i>a){o=r.lastIndexOf(";",i-1)+1;continue}let c=Ks(r,o,i);t[c]===void 0&&(t[c]=s(Ks(r,i+1,a))),o=a+1}while(o<n);return t}function sN(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let s of Object.keys(r)){let o=r[s];if(o===void 0)continue;if(!px.test(s))throw new TypeError(`cookie name is invalid: ${s}`);let i=t(o);if(!mx.test(i))throw new TypeError(`cookie val is invalid: ${o}`);n.push(`${s}=${i}`)}return n.join("; ")}function E0(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},o=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!px.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?o(n.value):"";if(!mx.test(i))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+i;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!JD.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!eN.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!iN(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function oN(r,e){let t=e?.decode||yx,n=r.length,s=q4(r,0,n),o=z4(r,0,s),i=o===-1?{name:"",value:t(Ks(r,0,s))}:{name:Ks(r,0,o),value:t(Ks(r,o+1,s))},a=s+1;for(;a<n;){let c=q4(r,a,n),l=z4(r,a,c),u=l===-1?Ks(r,a,c):Ks(r,a,l),d=l===-1?void 0:Ks(r,l+1,c);switch(u.toLowerCase()){case"httponly":i.httpOnly=!0;break;case"secure":i.secure=!0;break;case"partitioned":i.partitioned=!0;break;case"domain":i.domain=d;break;case"path":i.path=d;break;case"max-age":d&&tN.test(d)&&(i.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(i.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(i.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(i.sameSite=p);break}a=c+1}return i}function q4(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function z4(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Ks(r,e,t){let n=e,s=t;do{let o=r.charCodeAt(n);if(o!==32&&o!==9)break}while(++n<s);for(;s>n;){let o=r.charCodeAt(s-1);if(o!==32&&o!==9)break;s--}return r.slice(n,s)}function yx(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function iN(r){return rN.call(r)==="[object Date]"}});var mO={};fe(mO,{libp2pDefaults:()=>Ip,withLibp2p:()=>pO,withLibp2pLight:()=>fS});var B6=Symbol.for("@libp2p/connection");var Qs=Symbol.for("@libp2p/content-routing");var jt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},ii=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ai=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},v=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_r=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},qa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},za=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Zs=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},ci=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Rr=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},li=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Qr=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Js=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Ue=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ui=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Zr=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Pu=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Lu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ku=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},le=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},eo=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},as=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Pr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var cs=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},to=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Ga=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Du=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},di=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Lr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Nu=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},ls=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Ou=class extends ls{constructor(e,t){super(!0,e,t)}},Mu=class extends ls{constructor(e,t){super(!1,e,t)}};var ro=Symbol.for("@libp2p/peer-discovery");var Bu=Symbol.for("@libp2p/peer-id");function Jr(r){return!!r?.[Bu]}var no=Symbol.for("@libp2p/peer-routing");var so="keep-alive";function Uu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function kr(...r){let e=[];for(let t of r)Uu(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function en(...r){let e=[];for(let t of r)Uu(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var us=Symbol.for("@libp2p/transport");var Wa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Wa||(Wa={}));function vS(r){return typeof r?.handleEvent=="function"}function SS(r){return r===!0||r===!1}function AS(r){return SS(r)?r:r?.capture??!1}function _p(r){let e={capture:AS(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function U6(r,e){return _p(r).capture===_p(e).capture}var ue=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=_p(n);if(s?.signal?.aborted===!0)return;let o=l=>{s.once&&this.removeEventListener(e,t,s),vS(t)?t.handleEvent(l):t(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==t?!1:U6(l.options,s)))return;super.addEventListener(e,o,s);let c=()=>{this.removeEventListener(e,t,s)};s.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:o,options:s,onAbort:c})}removeEventListener(e,t,n){let s=this.#e.get(e);if(s==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,s.filter(o=>o.callback===t&&U6(o.options,n)?(super.removeEventListener(e,o.wrapper,n),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ye=Symbol.for("@libp2p/service-capabilities"),ir=Symbol.for("@libp2p/service-dependencies");var Dp={};fe(Dp,{base58btc:()=>Ie,base58flickr:()=>kS});var JO=new Uint8Array(0);function $6(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 yr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return oo(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return oo(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function K6(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var F6=4096;function V6(r){let e=r.length;if(e<=F6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=F6));return t}function TS(r){return r?.buffer instanceof ArrayBuffer}function oo(r){return TS(r)?r:r.slice()}function CS(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),l!==a&&(n[l]=o)}}var u=r.length,d=r.charAt(0),f=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function p(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var b=0,w=0,x=0,S=m.length;x!==S&&m[x]===0;)x++,b++;for(var C=(S-x)*h+1>>>0,I=new Uint8Array(C);x!==S;){for(var L=m[x],P=0,B=C-1;(L!==0||P<w)&&B!==-1;B--,P++)L+=256*I[B]>>>0,I[B]=L%u>>>0,L=L/u>>>0;if(L!==0)throw new Error("Non-zero carry");w=P,x++}for(var W=C-w;W!==C&&I[W]===0;)W++;for(var G=d.repeat(b);W<C;++W)G+=r.charAt(I[W]);return G}function g(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var w=0,x=0;m[b]===d;)w++,b++;for(var S=(m.length-b)*f+1>>>0,C=new Uint8Array(S);m[b];){var I=n[m.charCodeAt(b)];if(I===255)return;for(var L=0,P=S-1;(I!==0||L<x)&&P!==-1;P--,L++)I+=u*C[P]>>>0,C[P]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=L,b++}if(m[b]!==" "){for(var B=S-x;B!==S&&C[B]===0;)B++;for(var W=new Uint8Array(w+(S-B)),G=w;B!==S;)W[G++]=C[B++];return W}}}function y(m){var b=g(m);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:g,decode:y}}var IS=CS,_S=IS,q6=_S;var Rp=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")}},Pp=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 z6(this,e)}},Lp=class{decoders;constructor(e){this.decoders=e}or(e){return z6(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 z6(r,e){return new Lp({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kp=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Rp(e,t,n),this.decoder=new Pp(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fi({name:r,prefix:e,encode:t,decode:n}){return new kp(r,e,t,n)}function ds({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=q6(t,r,n);return fi({prefix:e,name:r,encode:s,decode:i=>yr(o(i))})}function RS(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function PS(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function LS(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function Ye({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=LS(n,s);return fi({prefix:e,name:r,encode(i){return PS(i,n,t)},decode(i){return RS(i,o,t,r)}})}var Ie=ds({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kS=ds({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Np={};fe(Np,{base32:()=>br,base32hex:()=>MS,base32hexpad:()=>US,base32hexpadupper:()=>FS,base32hexupper:()=>BS,base32pad:()=>NS,base32padupper:()=>OS,base32upper:()=>DS,base32z:()=>$S});var br=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),DS=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),NS=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),OS=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),MS=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),BS=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),US=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),FS=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),$S=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Op={};fe(Op,{base36:()=>io,base36upper:()=>KS});var io=ds({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),KS=ds({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var ze={};fe(ze,{Digest:()=>ao,create:()=>Ut,decode:()=>_e,equals:()=>Bp,hasCode:()=>iA});var VS=j6,G6=128,HS=127,qS=~HS,zS=Math.pow(2,31);function j6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zS;)e[t++]=r&255|G6,r/=128;for(;r&qS;)e[t++]=r&255|G6,r>>>=7;return e[t]=r|0,j6.bytes=t-n+1,e}var GS=Mp,WS=128,W6=127;function Mp(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Mp.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&W6)<<s:(i&W6)*Math.pow(2,s),s+=7}while(i>=WS);return Mp.bytes=o-n,t}var jS=Math.pow(2,7),YS=Math.pow(2,14),XS=Math.pow(2,21),QS=Math.pow(2,28),ZS=Math.pow(2,35),JS=Math.pow(2,42),eA=Math.pow(2,49),tA=Math.pow(2,56),rA=Math.pow(2,63),nA=function(r){return r<jS?1:r<YS?2:r<XS?3:r<QS?4:r<ZS?5:r<JS?6:r<eA?7:r<tA?8:r<rA?9:10},sA={encode:VS,decode:GS,encodingLength:nA},oA=sA,ja=oA;function Ya(r,e=0){let t=ja.decode(r,e),n=ja.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function hi(r,e,t=0){return ja.encode(r,e,t),e}function pi(r){return ja.encodingLength(r)}function Ut(r,e){let t=e.byteLength,n=pi(r),s=n+pi(t),o=new Uint8Array(s+t);return hi(r,o,0),hi(t,o,n),o.set(e,s),new ao(r,t,e,o)}function _e(r){let e=yr(r),[t,n]=Ya(e),[s,o]=Ya(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ao(t,s,i,e)}function Bp(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$6(r.bytes,t.bytes)}}var ao=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=oo(n),this.bytes=oo(s)}};function iA(r,e){return r.code===e}function Y6(r,e){let{bytes:t,version:n}=r;return n===0?cA(t,Up(r),e??Ie.encoder):lA(t,Up(r),e??br.encoder)}var X6=new WeakMap;function Up(r){let e=X6.get(r);if(e==null){let t=new Map;return X6.set(r,t),t}return e}var ge=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=oo(s),this["/"]=this.bytes}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!==Xa)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==uA)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=Ut(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&&Bp(e.multihash,n.multihash)}toString(e){return Y6(this,e)}toJSON(){return{"/":Y6(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:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Q6(n,s,o.bytes))}else if(t[dA]===!0){let{version:n,multihash:s,code:o}=t,i=_e(s);return r.create(n,o,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!==Xa)throw new Error(`Version 0 CID must use dag-pb (code: ${Xa}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Q6(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Xa,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,s=yr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ao(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Ya(e.subarray(t));return t+=f,d},s=n(),o=Xa;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=aA(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Up(o).set(n,e),o}};function aA(r,e){switch(r[0]){case"Q":{let t=e??Ie;return[Ie.prefix,t.decode(`${Ie.prefix}${r}`)]}case Ie.prefix:{let t=e??Ie;return[Ie.prefix,t.decode(r)]}case br.prefix:{let t=e??br;return[br.prefix,t.decode(r)]}case io.prefix:{let t=e??io;return[io.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function cA(r,e,t){let{prefix:n}=t;if(n!==Ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function lA(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Xa=112,uA=18;function Q6(r,e,t){let n=pi(r),s=n+pi(e),o=new Uint8Array(s+t.byteLength);return hi(r,o,0),hi(e,o,n),o.set(t,s),o}var dA=Symbol.for("@ipld/js-cid/CID");var Fp={};fe(Fp,{identity:()=>ar});var Z6=0,fA="identity",J6=yr;function hA(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ut(Z6,J6(r))}var ar={code:Z6,name:fA,encode:J6,digest:hA};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 pA(r){return r.buffer instanceof ArrayBuffer}function he(r){return pA(r)?r:r.slice()}var e5="1.2.840.10045.3.1.7",t5="1.3.132.0.34",r5="1.3.132.0.35";async function n5(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function s5(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,he(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function o5(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,he(e),he(t.subarray()));return n?.signal?.throwIfAborted(),o}function ne(r=0){return new Uint8Array(r)}function Ge(r=0){return new Uint8Array(r)}function mA(r){return r?.buffer instanceof ArrayBuffer}function $u(r){if(mA(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function et(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ge(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return $u(t)}var a5=Symbol.for("@achingbrain/uint8arraylist");function i5(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function mi(r){return!!r?.[a5]}var j=class r{bufs;length;[a5]=!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(mi(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}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(mi(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=i5(this.bufs,e);return t.buf[t.index]}set(e,t){let n=i5(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(mi(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:s}=this._subList(e,t);return et(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:et(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){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(!mi(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}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=Ge(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 s=ne(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,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=Ge(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 s=ne(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,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 s=ne(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,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 s=ne(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,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((s,o)=>s+o.byteLength,0)),n.length=t,n}};var $p={};fe($p,{base10:()=>gA});var gA=ds({prefix:"9",name:"base10",alphabet:"0123456789"});var Kp={};fe(Kp,{base16:()=>yA,base16upper:()=>bA});var yA=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),bA=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Vp={};fe(Vp,{base2:()=>wA});var wA=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hp={};fe(Hp,{base256emoji:()=>AA});var c5=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}"),EA=c5.reduce((r,e,t)=>(r[t]=e,r),[]),xA=c5.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function vA(r){return r.reduce((e,t)=>(e+=EA[t],e),"")}function SA(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=xA[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var AA=fi({prefix:"\u{1F680}",name:"base256emoji",encode:vA,decode:SA});var qp={};fe(qp,{base64:()=>_n,base64pad:()=>Qa,base64url:()=>Za,base64urlpad:()=>TA});var _n=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qa=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Za=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),TA=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var zp={};fe(zp,{base8:()=>CA});var CA=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gp={};fe(Gp,{identity:()=>IA});var IA=fi({prefix:"\0",name:"identity",encode:r=>V6(yr(r)),decode:r=>yr(K6(r))});var UM=new TextEncoder,FM=new TextDecoder;var Ku=85;var Yp={};fe(Yp,{sha256:()=>yt,sha512:()=>PA});var RA=20;function Ja({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new jp(r,e,t,n,s)}var jp=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??RA,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?l5(n,this.code,t?.truncate):n.then(s=>l5(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function l5(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ut(e,r)}function d5(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var yt=Ja({name:"sha2-256",code:18,encode:d5("SHA-256")}),PA=Ja({name:"sha2-512",code:19,encode:d5("SHA-512")});var co={...Gp,...Vp,...zp,...$p,...Kp,...Np,...Op,...Dp,...qp,...Hp},QM={...Yp,...Fp};function h5(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var f5=h5("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xp=h5("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=Ge(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),LA={utf8:f5,"utf-8":f5,hex:co.base16,latin1:Xp,ascii:Xp,binary:Xp,...co},Vu=LA;function T(r,e="utf8"){let t=Vu[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function k(r,e="utf8"){let t=Vu[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var kA=parseInt("11111",2),Qp=parseInt("10000000",2),DA=parseInt("01111111",2),p5={0:ec,1:ec,2:NA,3:BA,4:UA,5:MA,6:OA,16:ec,22:ec,48:ec};function wr(r,e={offset:0}){let t=r[e.offset]&kA;if(e.offset++,p5[t]!=null)return p5[t](r,e);throw new Error("No decoder for tag "+t)}function tc(r,e){let t=0;if((r[e.offset]&Qp)===Qp){let n=r[e.offset]&DA,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");s+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(s,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function ec(r,e){tc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wr(r,e);if(n===null)break;t.push(n)}return t}function NA(r,e){let t=tc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function OA(r,e){let t=tc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function MA(r,e){return e.offset++,null}function BA(r,e){let t=tc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function UA(r,e){let t=tc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function FA(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new j;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Hu(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=FA(r.byteLength);return new j(Uint8Array.from([e.byteLength|Qp]),e)}function Ft(r){let e=new j,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new j(Uint8Array.from([2]),Hu(e),e)}function rc(r){let e=Uint8Array.from([0]),t=new j(e,r);return new j(Uint8Array.from([3]),Hu(t),t)}function m5(r){return new j(Uint8Array.from([4]),Hu(r),r)}function Dr(r,e=48){let t=new j;for(let n of r)t.append(n);return new j(Uint8Array.from([e]),Hu(t),t)}var $A=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),KA=Uint8Array.from([6,5,43,129,4,0,34]),VA=Uint8Array.from([6,5,43,129,4,0,35]),g5={ext:!0,kty:"EC",crv:"P-256"},y5={ext:!0,kty:"EC",crv:"P-384"},b5={ext:!0,kty:"EC",crv:"P-521"},gi=32,yi=48,bi=66;function w5(r){let e=wr(r);return Zp(e)}function Zp(r){let e=r[1],t=k(e,"base64url"),n=r[2][1][0],s=1,o,i;if(e.byteLength===gi)return o=k(n.subarray(s,s+gi),"base64url"),i=k(n.subarray(s+gi),"base64url"),new uo({...g5,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===yi)return o=k(n.subarray(s,s+yi),"base64url"),i=k(n.subarray(s+yi),"base64url"),new uo({...y5,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===bi)return o=k(n.subarray(s,s+bi),"base64url"),i=k(n.subarray(s+bi),"base64url"),new uo({...b5,key_ops:["sign"],d:t,x:o,y:i});throw new v(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Jp(r){let e=wr(r);return E5(e)}function E5(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===gi*2+1)return n=k(e.subarray(t,t+gi),"base64url"),s=k(e.subarray(t+gi),"base64url"),new lo({...g5,key_ops:["verify"],x:n,y:s});if(e.byteLength===yi*2+1)return n=k(e.subarray(t,t+yi),"base64url"),s=k(e.subarray(t+yi),"base64url"),new lo({...y5,key_ops:["verify"],x:n,y:s});if(e.byteLength===bi*2+1)return n=k(e.subarray(t,t+bi),"base64url"),s=k(e.subarray(t+bi),"base64url"),new lo({...b5,key_ops:["verify"],x:n,y:s});throw new v(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function x5(r){return Dr([Ft(Uint8Array.from([1])),m5(T(r.d??"","base64url")),Dr([S5(r.crv)],160),Dr([rc(new j(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function v5(r){return Dr([Ft(Uint8Array.from([1])),Dr([S5(r.crv)],160),Dr([rc(new j(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function S5(r){if(r==="P-256")return $A;if(r==="P-384")return KA;if(r==="P-521")return VA;throw new v(`Invalid curve ${r}`)}async function A5(r="P-256"){let e=await n5(r);return new uo(e.privateKey)}var lo=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=v5(this.jwk)),this._raw}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async verify(e,t,n){return o5(this.jwk,t,e,n)}},uo=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new lo({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=x5(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async sign(e,t){return s5(this.jwk,e,t)}};var qu=BigInt(4294967295),T5=BigInt(32);function HA(r,e=!1){return e?{h:Number(r&qu),l:Number(r>>T5&qu)}:{h:Number(r>>T5&qu)|0,l:Number(r&qu)|0}}function C5(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=HA(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var qA=r=>r/2**32|0,zA=r=>r>>>0;function I5(r,e,t,n){let s=qA(t),o=zA(t);r.setUint32(e,n?o:s,n),r.setUint32(e+4,n?s:o,n)}var e2=(r,e,t)=>r>>>t,t2=(r,e,t)=>r<<32-t|e>>>t,fo=(r,e,t)=>r>>>t|e<<32-t,ho=(r,e,t)=>r<<32-t|e>>>t,nc=(r,e,t)=>r<<64-t|e>>>t-32,sc=(r,e,t)=>r>>>t-32|e<<64-t;function tn(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var _5=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),R5=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,P5=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),L5=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,k5=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),D5=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;function zu(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var r2=r=>r?`"${r}" `:"";function bt(r,e=""){if(typeof r!="number")throw new TypeError(r2(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(r2(e)+"expected integer >= 0, got "+r);return r}function Ct(r,e,t=""){if(zu(r)&&(e===void 0||r.length===e))return r;e!==void 0&&bt(e,"length");let n=zu(r),s=e!==void 0?` of length ${e}`:"",o=n?`length=${r.length}`:`type=${typeof r}`,i=r2(t)+"expected Uint8Array"+s+", got "+o;throw n?new RangeError(i):new TypeError(i)}function Rn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(bt(r.outputLen),bt(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var WA=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},N5=(r,e)=>{WA(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function wi(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Gu(r,e){Ct(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function tt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ei(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Nr(r,e){return r<<32-e|r>>>e}function Wu(r,e){return r<<e|r>>>32-e>>>0}var M5=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jA=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ju(r){if(Ct(r),M5)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=jA[r[t]];return e}function O5(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function Yu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(M5)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=O5(r.charCodeAt(o)),a=O5(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function YA(r){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return r&&t.catch(r),t}return new Promise(t=>e.setTimeout(t,0))}async function B5(r,e,t,n){if(bt(r,"iters"),bt(e,"tick"),typeof t!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-s;i>=0&&i<e||(await YA(n),s=Date.now())}}function XA(r){if(typeof r!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(r);try{return new Uint8Array(e)}finally{tt(e)}}function n2(r,e=""){return typeof r=="string"?XA(r):Ct(r,void 0,e)}function s2(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Ct(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function o2(r,e,t="opts"){return N5(r,"defaults"),e!==void 0&&N5(e,t),Object.assign(Object.create(null),r,e)}function oc(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=o2({},e,"info");let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function U5(r=32){bt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var i2=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Xu(r,e,t){return r&e^~r&t}function Qu(r,e,t){return r&e^r&t^e&t}var po=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ei(this.buffer)}update(e){wi(this),Ct(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length,i=!1;for(let a=0;a<o;){let c=Math.min(s-this.pos,o-a);if(c===s){let l=Ei(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}n.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){wi(this),Gu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>s-i&&(this.process(n,0),t.fill(0)),I5(n,s-8,this.length*8,o),this.process(n,0),this.roundClean();let a=e===t?n:Ei(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},F5=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $5=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var QA=Uint32Array.from([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]),fs=new Uint32Array(64),a2=class extends po{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)fs[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=fs[d-15],h=fs[d-2],p=Nr(f,7)^Nr(f,18)^f>>>3,g=Nr(h,17)^Nr(h,19)^h>>>10;fs[d]=g+fs[d-7]+p+fs[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Nr(a,6)^Nr(a,11)^Nr(a,25),h=u+f+Xu(a,c,l)+QA[d]+fs[d]|0,g=(Nr(n,2)^Nr(n,13)^Nr(n,22))+Qu(n,s,o)|0;u=l,l=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+g|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){tt(fs)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),tt(this.buffer)}},c2=class extends a2{constructor(){super(32,F5)}};var K5=C5(["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))),ZA=K5[0],JA=K5[1],hs=new Uint32Array(80),ps=new Uint32Array(80),l2=class extends po{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:g,Hl:y}=this;return[e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y]}set(e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let w=0;w<16;w++,t+=4)hs[w]=e.getUint32(t),ps[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=hs[w-15]|0,S=ps[w-15]|0,C=fo(x,S,1)^fo(x,S,8)^e2(x,S,7),I=ho(x,S,1)^ho(x,S,8)^t2(x,S,7),L=hs[w-2]|0,P=ps[w-2]|0,B=fo(L,P,19)^nc(L,P,61)^e2(L,P,6),W=ho(L,P,19)^sc(L,P,61)^t2(L,P,6),G=P5(I,W,ps[w-7],ps[w-16]),Z=L5(G,C,B,hs[w-7],hs[w-16]);hs[w]=Z|0,ps[w]=G|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:g,Gl:y,Hh:m,Hl:b}=this;for(let w=0;w<80;w++){let x=fo(d,f,14)^fo(d,f,18)^nc(d,f,41),S=ho(d,f,14)^ho(d,f,18)^sc(d,f,41),C=d&h^~d&g,I=f&p^~f&y,L=k5(b,S,I,JA[w],ps[w]),P=D5(L,m,x,C,ZA[w],hs[w]),B=L|0,W=fo(n,s,28)^nc(n,s,34)^nc(n,s,39),G=ho(n,s,28)^sc(n,s,34)^sc(n,s,39),Z=n&o^n&a^o&a,N=s&i^s&c^i&c;m=g|0,b=y|0,g=h|0,y=p|0,h=d|0,p=f|0,{h:d,l:f}=tn(l|0,u|0,P|0,B|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let $=_5(B,G,N);n=R5($,P,W,Z),s=$|0}({h:n,l:s}=tn(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=tn(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=tn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=tn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=tn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=tn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:y}=tn(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:b}=tn(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,s,o,i,a,c,l,u,d,f,h,p,g,y,m,b)}roundClean(){tt(hs,ps)}destroy(){this.destroyed=!0,tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},u2=class extends l2{constructor(){super(64,$5)}};var It=oc(()=>new c2,i2(1));var Pn=oc(()=>new u2,i2(3));function Ju(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var Ee=(r,e,t)=>Ct(r,e,t),d2=bt;function H5(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function ms(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function mo(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var ic=ju,Er=(...r)=>s2(...r),xi=r=>Yu(r),ys=zu,Ln=r=>U5(r),Zu=BigInt(0),V5=BigInt(1),eT=r=>r?`"${r}" `:"";function Yt(r,e=""){if(typeof r!="boolean")throw new TypeError(eT(e)+"expected boolean, got type="+typeof r);return r}function ed(r){if(typeof r=="bigint"){if(!gs(r))throw new RangeError("positive bigint expected, got "+r)}else d2(r);return r}function kn(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function ac(r){let e=ed(r).toString(16);return e.length&1?"0"+e:e}function q5(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Zu:BigInt("0x"+r)}function rn(r){return q5(ju(r))}function nn(r){return q5(ju(bs(Ct(r)).reverse()))}function td(r,e){if(bt(e),e===0)throw new Error("zero output length is invalid");r=ed(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return Yu(n.padStart(t,"0"))}function cc(r,e){return td(r,e).reverse()}function bs(r){return Uint8Array.from(Ee(r))}function gs(r){return typeof r=="bigint"&&Zu<=r}function f2(r,e,t){return gs(r)&&gs(e)&&gs(t)&&e<=r&&r<t}function sn(r,e,t,n){if(!f2(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function vi(r){if(r<Zu)throw new Error("expected non-negative bigint, got "+r);return r===Zu?0:r.toString(2).length}var lc=r=>(kn(r,"n"),(V5<<BigInt(r))-V5);function z5(r,e,t){if(bt(r,"hashLen"),bt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...y)=>t(l,Er(c,...y)),h=(y=s)=>{l=f(o,y),c=f(),y.length!==0&&(l=f(i,y),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=f();let b=c.slice();m.push(b),y+=c.length}return Er(...m)};return(y,m)=>{d(),h(y);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function _t(r,e={},t={},n="object"){ms(r,n),ms(e,"fields"),ms(t,"optFields");function s(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let d=typeof u;if(d!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(t,!0)}var ct=BigInt(0),Re=BigInt(1),ws=BigInt(2),j5=BigInt(3),h2=BigInt(4),Y5=BigInt(5),tT=BigInt(7),X5=BigInt(8),rT=BigInt(9),nT=BigInt(15),Q5=BigInt(16),sT=BigInt("0x10000000000000000");function De(r,e){if(e<=ct)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ct?t:e+t}function Z5(r,e,t){if(t<=Re)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<ct)throw new Error("invalid exponent, negatives unsupported");if(e===ct)return Re;if(e===Re)return r;let n=r%t;if(n<ct&&(n+=t),e<sT){let a=Re;for(;e>ct;)e&Re&&(a=a*n%t),n=n*n%t,e>>=Re;return a}let s=[];for(;e>ct;)s.push(Number(e&nT)),e>>=h2;let o=new Array(16);o[0]=Re,o[1]=n;for(let a=2;a<16;a++)o[a]=o[a-1]*n%t;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=s[a];c!==0&&(i=i*o[c]%t)}return i}function Ke(r,e,t){if(t<=Re)throw new Error("pow2: expected modulus > 1, got "+t);if(e<ct)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >ct;)n*=n,n%=t;return n}function G5(r,e){if(r===ct)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected modulus > 1, got "+e);let t=De(r,e),n=e,s=ct,o=Re;for(;t!==ct;){let a=n/t,c=n-t*a,l=s-o*a;n=t,t=c,s=o,o=l}if(n!==Re)throw new Error("invert: does not exist");return De(s,e)}function J5(r,e){if(e<=Re)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=De(r,e);if(t===ct)throw new Error("invertCt: expected non-zero number");let n=Z5(t,e-ws,e);if(De(t*n,e)!==Re)throw new Error("invertCt: does not exist");return n}function p2(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function m2(r,e){if((r&Re)===ct)throw new Error(e+": expected odd modulus, got "+r)}function e8(r,e){let t=r,n=(t.ORDER+Re)/h2,s=t.pow(e,n);return p2(t,s,e),s}function oT(r,e){let t=r,n=(t.ORDER-Y5)/X5,s=t.mul(e,ws),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,ws),o),c=t.mul(i,t.sub(a,t.ONE));return p2(t,c,e),c}function iT(r){let e=Ai(r),t=t8(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+tT)/Q5;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,s),h=l.mul(u,o),p=l.eql(l.sqr(d),c),g=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,g);let y=l.eql(l.sqr(d),c),m=l.cmov(u,d,y);return p2(l,m,c),m})}function t8(r){if(r<j5)throw new Error("sqrt is not defined for small field");m2(r,"tonelliShanks");let e=r-Re,t=0;for(;e%ws===ct;)e/=ws,t++;let n=ws,s=Ai(r);for(;uc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return e8;let o=s.pow(n,e),i=(e+Re)/ws;return function(c,l){let u=c;if(u.is0(l))return l;if(uc(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,o),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(h);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let m=Re<<BigInt(d-g-1),b=u.pow(f,m);d=g,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function aT(r){return m2(r,"Fp.sqrt"),r%h2===j5?e8:r%X5===Y5?oT:r%Q5===rT?iT(r):t8(r)}var r8=(r,e)=>(De(r,e)&Re)===Re,cT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Si(r){if(ms(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);kn(r.BYTES,"BYTES"),kn(r.BITS,"BITS");for(let e of cT)mo(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Re)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function nd(r,e,t=!1){Si(r),Ju(e,"nums"),Yt(t,"passZero");let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,l)=>n.is0(c)?a:(s[l]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,l)=>n.is0(c)?a:(s[l]=n.mul(a,s[l]),n.mul(a,c)),i),s}function uc(r,e){Si(r);let t=r;m2(t.ORDER,"FpLegendre");let n=(t.ORDER-Re)/ws,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function lT(r,e){if(e!==void 0&&d2(e),r<=ct)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=vi(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var W5=new WeakMap,rd=class{ORDER;BITS;BYTES;isLE;ZERO=ct;ONE=Re;_lengths;_mod;constructor(e,t={}){if(e<=Re)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=lT(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return De(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ct<=e&&e<this.ORDER}is0(e){return e===ct}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Re)===Re}neg(e){return De(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return De(e*e,this.ORDER)}add(e,t){return De(e+t,this.ORDER)}sub(e,t){return De(e-t,this.ORDER)}mul(e,t){return De(e*t,this.ORDER)}pow(e,t){return Z5(e,t,this.ORDER)}div(e,t){return De(e*G5(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return G5(e,this.ORDER)}sqrt(e){let t=W5.get(this);return t||W5.set(this,t=aT(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?cc(e,this.BYTES):td(e,this.BYTES)}fromBytes(e,t=!1){Ee(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?nn(e):rn(e);if(a&&(c=De(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return nd(this,e,!0)}cmov(e,t,n){return Yt(n,"condition"),n?t:e}};function Ai(r,e={}){return Object.freeze(rd.prototype),new rd(r,e)}function n8(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Re)throw new Error("field order must be greater than 1");let e=vi(r-Re);return Math.ceil(e/8)}function sd(r){let e=n8(r);return e+Math.ceil(e/2)}function od(r,e,t=!1){Ee(r);let n=r.length,s=n8(e),o=Math.max(sd(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?nn(r):rn(r),a=De(i,e-Re)+Re;return t?cc(a,s):td(a,s)}var b2=BigInt(0),dc=BigInt(1),uT=BigInt(4),g2=16,s8=128,dT=5,o8=2**31;function Es(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);mo(e.fromAffine,"Point.fromAffine"),mo(e.fromBytes,"Point.fromBytes"),mo(e.fromHex,"Point.fromHex"),ms(e.BASE,"Point.BASE"),ms(e.ZERO,"Point.ZERO"),Si(e.Fp),Si(e.Fn)}function id(r,e){Es(r),a8(e,r);let t=nd(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function fT(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function hT(r,e){let t=r*(4*e+128);if(t>o8)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+o8/2**20+" MiB")}function w2(r,e){if(r!==void 0){mo(r,"randomBytes");try{let t=r(e);if(!ys(t)||t.length!==e)return}catch{return}return r}}function a8(r,e){Ju(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function pT(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,s)=>{if(!(t===void 0?e.isValid(n):gs(n)&&n<t))throw new Error("invalid scalar at index "+s)})}var c8=new WeakMap;function y2(r){return c8.get(r)||1}function mT(r,e){let t=r.double(),n=[r];for(let s=1;s<e;s++)n.push(n[s-1].add(t));return n}function gT(r,e){let t=2**e,n=t/2,s=BigInt(t-1),o=[];for(;r>b2;){let i=0;r&dc&&(i=Number(r&s),i>=n&&(i-=t),r-=BigInt(i)),o.push(i),r>>=dc}return o}function yT(r,e,t){let n=2**e,s=n/2,o=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(r&o);r>>=i,l>s&&(l-=n,r+=dc),a.push(l)}if(r!==b2)throw new Error("invalid wnaf");return a}function bT(r,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let s=r;for(let o=n-1;o>=0;o--){o!==n-1&&(s=s.double());for(let i=0;i<t.length;i++){let a=t[i][o];if(a){let c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}var Ti=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Es(e),this.randomBytes=w2(t,g2),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let s=Math.ceil(n/t)+1,o=2**(t-1),i=[],a=e;for(let c=0;c<s;c++){let l=a;for(let u=0;u<o;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:s,comp:i}}wnafCachedCT(e,t){let{W:n,windows:s,comp:o}=e,i=2**(n-1),a=yT(t,n,s),c=this.ZERO,l=this.BASE;for(let u=0;u<s;u++){let d=a[u],f=u*i,h=Math.abs(d)-1,p=o[f];for(let y=1;y<i;y++)p=y===h?o[f+y]:p;let g=p.negate();d===0?l=l.add(o[f]):c=c.add(d<0?g:p)}return{p:c,f:l}}getWnafPrecomputes(e,t,n,s){let o=this.wnafPrecomputes.get(t),i=o?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!f2(t,dc,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,s){let o=y2(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,s),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let s=this.Point.Fn.BITS+s8,o=this.randomBytes(g2);if(!ys(o)||o.length!==g2)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+rn(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,n)}fixedWindowCT(e,t,n){let s=dT,o=1<<s,i=lc(s),a=new Array(o);a[0]=this.ZERO;for(let u=1;u<o;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/s),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let h=0;h<s;h++)l=l.double();let d=Number(t>>BigInt(u*s)&i),f=a[0];for(let h=1;h<o;h++)f=h===d?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===dc?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,s){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,s):this.mulCT(e,t,s)}mulUnsafe(e,t,n){if(this.assertPoint(e),!gs(t))throw new Error("invalid scalar");let s=y2(e);if(s===1||t>=this.Point.Fn.ORDER)return ad(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(s,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),fT(t,this.bits);let n=Math.ceil((this.bits+s8)/t)+1;hT(n*2**(t-1),this.Point.Fp.BYTES),c8.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return y2(e)!==1}};function ad(r,e,t,n=!1){if(Es(r),a8(e,r),Yt(n,"allowOversized"),pT(t,r.Fn,n?r.Fn.ORDER**uT:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let s=e.map(i=>mT(i,4)),o=t.map(i=>gT(i,4));return bT(r.ZERO,s,o)}function i8(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Si(e),e}else return Ai(r,{isLE:t})}function cd(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);_t(t);for(let c of["p","n","h"]){let l=e[c];if(!(gs(l)&&l!==b2))throw new Error(`CURVE.${c} must be positive bigint`)}let s=i8(e.p,t.Fp,n),o=i8(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Ci(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var ld=BigInt(0),ud=BigInt(1),dd=BigInt(2),wT=BigInt(4),l8=BigInt(8);function ET(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function u8(r,e={}){_t(e,{},{},"extraOpts");let t=e,n=cd("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;if(uc(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(uc(s,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");_t(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Ln:t.randomBytes,l=dd<<BigInt(s.BYTES*8)-ud;function u(b){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(b)}let d=t.uvRatio===void 0?(b,w)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,w))}}catch{return{isValid:!1,value:ld}}}:t.uvRatio;if(!ET(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=s.eql(i.a,s.neg(s.ONE))?b=>s.neg(b):s.eql(i.a,s.ONE)?b=>b:b=>s.mul(i.a,b);function h(b,w,x=!1){let S=x?ud:ld;return sn("coordinate "+b,w,S,l),w}function p(b){if(!(b instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new g(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(w,x,S,C){this.X=h("x",w),this.Y=h("y",x),this.Z=h("z",S,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");let{x,y:S}=w||{};return h("x",x),h("y",S),new g(x,S,s.ONE,s.mul(x,S))}static fromBytes(w,x=!1){let S=s.BYTES,{a:C,d:I}=i;w=bs(Ee(w,S,"point")),Yt(x,"zip215");let L=bs(w),P=w[S-1];L[S-1]=P&-129;let B=nn(L),W=x?l:s.ORDER;sn("point.y",B,ld,W);let G=s.sqr(B),Z=s.sub(G,s.ONE),N=s.sub(s.mulN(I,G),C),{isValid:$,value:O}=d(Z,N);if(!$)throw new Error("bad point: invalid y coordinate");let D=u(O),Y=(P&128)!==0;if(!x&&s.is0(O)&&Y)throw new Error("bad point: x=0 and x_0=1");return Y!==D&&(O=s.neg(O)),g.fromAffine({x:O,y:B})}static fromHex(w,x=!1){return g.fromBytes(xi(w),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=6,x=!0){return m.setWindowSize(this,w),x||this.multiply(dd),this}assertValidity(){let w=this,{a:x,d:S}=i;if(w.is0())throw new Error("bad point: ZERO");let{X:C,Y:I,Z:L,T:P}=w,B=s.sqr(C),W=s.sqr(I),G=s.sqr(L),Z=s.sqr(G),N=s.mul(B,x),$=s.mul(s.add(N,W),G),O=s.add(Z,s.mul(S,s.mul(B,W)));if(!s.eql($,O))throw new Error("bad point: equation left != right (1)");let D=s.mul(C,I),Y=s.mul(L,P);if(!s.eql(D,Y))throw new Error("bad point: equation left != right (2)")}equals(w){p(w);let{X:x,Y:S,Z:C}=this,{X:I,Y:L,Z:P}=w,B=s.mul(x,P),W=s.mul(I,C),G=s.mul(S,P),Z=s.mul(L,C);return s.eql(B,W)&&s.eql(G,Z)}is0(){return this.equals(g.ZERO)}negate(){return new g(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){let{X:w,Y:x,Z:S}=this,C=s.sqr(w),I=s.sqr(x),L=s.mul(s.sqr(S),dd),P=f(C),B=s.addN(w,x),W=s.sub(s.subN(s.sqr(B),C),I),G=s.addN(P,I),Z=s.subN(G,L),N=s.subN(P,I),$=s.mul(W,Z),O=s.mul(G,N),D=s.mul(W,N),Y=s.mul(Z,G);return new g($,O,Y,D)}add(w){p(w);let{d:x}=i,{X:S,Y:C,Z:I,T:L}=this,{X:P,Y:B,Z:W,T:G}=w,Z=s.mul(S,P),N=s.mul(C,B),$=s.mul(s.mulN(L,x),G),O=s.mul(I,W),D=s.sub(s.subN(s.mulN(s.addN(S,C),s.addN(P,B)),Z),N),Y=s.subN(O,$),M=s.addN(O,$),_=s.sub(N,f(Z)),E=s.mul(D,Y),A=s.mul(M,_),R=s.mul(D,_),U=s.mul(Y,M);return new g(E,A,U,R)}subtract(w){return p(w),this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:S}=m.mulSecret(this,w,a,y);return y([x,S])[0]}multiplyUnsafe(w){if(!o.isValid(w))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return w===ld?g.ZERO:this.is0()||w===ud?this:m.mulUnsafe(this,w,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.mulUnsafe(this,i.n).is0()}toAffine(w){let x=this,S=w;if(S!=null&&typeof S!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof S);let{X:C,Y:I,Z:L}=x,P=x.is0();S==null&&(S=P?s.create(l8):s.inv(L));let B=s.mul(C,S),W=s.mul(I,S),G=s.mul(L,S);if(P)return{x:s.ZERO,y:s.ONE};if(!s.eql(G,s.ONE))throw new Error("invZ was invalid");return{x:B,y:W}}clearCofactor(){return a===ud?this:a===dd?this.double():a===wT?this.double().double():a===l8?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:w,y:x}=this.toAffine(),S=s.toBytes(x);return S[S.length-1]|=u(w)?128:0,S}toHex(){return ic(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=b=>id(g,b),m=new Ti(g,c);return m.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function d8(r,e,t={}){if(Es(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;_t(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(kn(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=s.randomBytes===void 0?Ln:s.randomBytes,f=s.toMontgomery,h=s.toMontgomerySecret,p=s.adjustScalarBytes===void 0?N=>N:s.adjustScalarBytes,g=s.domain===void 0?(N,$,O)=>{if(Yt(O,"phflag"),$.length||O)throw new Error("Contexts/pre-hash are not supported");return N}:s.domain;function y(N){return c.create(nn(N))}function m(N){let $=P.secretKey;Ee(N,P.secretKey,"secretKey");let O=Ee(n(N),2*$,"hashedSecretKey"),D=p(O.slice(0,$)),Y=O.slice($,2*$),M=y(D);return{head:D,prefix:Y,scalar:M}}function b(N){let{head:$,prefix:O,scalar:D}=m(N),Y=i.multiply(D),M=Y.toBytes();return{head:$,prefix:O,scalar:D,point:Y,pointBytes:M}}function w(N){return b(N).pointBytes}function x(N=Uint8Array.of(),...$){let O=Er(...$);return y(n(g(O,Ee(N,void 0,"context"),!!o)))}function S(N,$,O={}){_t(O,{},{},"options"),N=bs(Ee(N,void 0,"message")),o&&(N=o(N));let{prefix:D,scalar:Y,pointBytes:M}=b($),_=x(O.context,D,N),E=i.multiply(_).toBytes(),A=x(O.context,E,M,N),R=c.create(_+A*Y);if(!c.isValid(R))throw new Error("sign failed: invalid s");let U=Er(E,c.toBytes(R));return Ee(U,P.signature,"result")}let C={zip215:s.zip215};function I(N,$,O,D=C){_t(D);let{context:Y}=D,M=D.zip215===void 0?!!C.zip215:D.zip215,_=P.signature;N=Ee(N,_,"signature"),$=Ee($,void 0,"message"),O=Ee(O,P.publicKey,"publicKey"),M!==void 0&&Yt(M,"zip215"),o&&($=o($));let E=_/2,A=N.subarray(0,E),R=nn(N.subarray(E,_)),U,q,z;try{U=r.fromBytes(O,M),q=r.fromBytes(A,M),z=i.multiplyUnsafe(R)}catch{return!1}if(!M&&U.isSmallOrder())return!1;let X=x(Y,A,O,$);return q.add(U.multiplyUnsafe(X)).subtract(z).clearCofactor().is0()}let L=a.BYTES,P={secretKey:L,publicKey:L,signature:2*L,seed:L};function B(N){return N=N===void 0?d(P.seed):N,Ee(N,P.seed,"seed")}function W(N){return ys(N)&&N.length===P.secretKey}function G(N,$){try{return!!r.fromBytes(N,$===void 0?C.zip215:$)}catch{return!1}}let Z={getExtendedPublicKey:b,randomSecretKey:B,isValidSecretKey:W,isValidPublicKey:G,toMontgomery(N){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(r.fromBytes(N))},toMontgomerySecret(N){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(N)}};return Object.freeze(P),Object.freeze(Z),Object.freeze({keygen:Ci(B,w),getPublicKey:w,sign:S,verify:I,utils:Z,Point:r,lengths:P})}var go=BigInt(0),xr=BigInt(1),fd=BigInt(2);function f8(r,e){return r+e-(e>>xr<<xr)}function xT(r){let e=BigInt(6)*r;return(t,n,s)=>{let o=n+s,a=((e+s-n)*t+n)%r;return{x_2:a,x_3:o-a}}}function vT(r){return _t(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...r})}function h8(r){let e=vT(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let l=i===void 0?Ln:i,u=c?255:448,d=xT(t),f=c?32:56,h=BigInt(c?9:5),p=BigInt(c?121665:39081),g=c?fd**BigInt(254):fd**BigInt(447),y=c?BigInt(8)*(fd**BigInt(251)-xr):BigInt(4)*(fd**BigInt(445)-xr),m=g+y+xr,b=O=>De(O,t),w=x(h);function x(O){return cc(b(O),f)}function S(O){let D=bs(Ee(O,f,"uCoordinate"));return c&&(D[31]&=127),b(nn(D))}function C(O){return nn(s(bs(Ee(O,f,"scalar"))))}let I=new Set(c?[go,xr,t-xr,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[go,xr,t-xr]);function L(O,D){let Y=S(D);if(I.has(Y))throw new Error("invalid private or public key received");let M=G(Y,C(O));if(M===go)throw new Error("invalid private or public key received");return x(M)}function P(O){if(a===void 0)return L(O,w);let D=C(O);sn("scalar",D,g,m);let Y=b(a(D));if(Y===go)throw new Error("invalid private or public key received");return x(Y)}let B=P,W=L;function G(O,D){sn("u",O,go,t),sn("scalar",D,g,m);let Y=D,M=O,_=xr,E=go,A=O,R=xr,U=Y^Y>>xr;for(let X=BigInt(u-1);X>=go;X--){let Q=f8(t,U>>X);({x_2:_,x_3:A}=d(Q,_,A)),{x_2:E,x_3:R}=d(Q,E,R);let ce=_+E,me=b(ce*ce),$e=_-E,Me=b($e*$e),Je=me-Me,Wt=A+R,Be=A-R,qe=b(Be*ce),si=b(Wt*$e),Ha=qe+si,is=qe-si;A=b(Ha*Ha),R=b(M*b(is*is)),_=b(me*Me),E=b(Je*(me+b(p*Je)))}let q=f8(t,Y);({x_2:_,x_3:A}=d(q,_,A)),{x_2:E,x_3:R}=d(q,E,R);let z=o(E);return b(_*z)}let Z={secretKey:f,publicKey:f,seed:f},N=O=>(O=O===void 0?l(f):O,Ee(O,Z.seed,"seed"),O),$={randomSecretKey:N};return Object.freeze(Z),Object.freeze($),Object.freeze({keygen:Ci(N,B),getSharedSecret:W,getPublicKey:B,scalarMult:L,scalarMultBase:P,utils:$,GuBytes:w.slice(),lengths:Z})}var p8=BigInt(0),E2=BigInt(1),m8=BigInt(2),ST=BigInt(3),AT=BigInt(5),TT=BigInt(8),hd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),CT={p:hd,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:TT,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function b8(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=hd,a=r*r%o*r%o,c=Ke(a,m8,o)*a%o,l=Ke(c,E2,o)*r%o,u=Ke(l,AT,o)*l%o,d=Ke(u,e,o)*u%o,f=Ke(d,t,o)*d%o,h=Ke(f,n,o)*f%o,p=Ke(h,s,o)*h%o,g=Ke(p,s,o)*h%o,y=Ke(g,e,o)*u%o;return{pow_p_5_8:Ke(y,m8,o)*r%o,b2:a}}function x2(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var g8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function IT(r,e){let t=hd,n=De(e*e*e,t),s=De(n*n*e,t),o=b8(r*s).pow_p_5_8,i=De(r*n*o,t),a=De(e*i*i,t),c=i,l=De(i*g8,t),u=a===r,d=a===De(-r,t),f=a===De(-r*g8,t);return u&&(i=c),(d||f)&&(i=l),r8(i,t)&&(i=De(-i,t)),{isValid:u||d,value:i}}var fc=u8(CT,{uvRatio:IT}),y8=fc.Fp;function _T(r){let{y:e}=r;return y8.toBytes(y8.div(E2+e,E2-e))}function RT(r){let e=fc.Fp.BYTES;return Ct(r,e),x2(Pn(r.subarray(0,e))).subarray(0,e)}function PT(r){return d8(fc,Pn,Object.assign({adjustScalarBytes:x2,toMontgomery:_T,toMontgomerySecret:RT,zip215:!0},r))}var hc=PT({});var on=(()=>{let r=hd,e=t=>{let{pow_p_5_8:n,b2:s}=b8(t);return De(Ke(n,ST,r)*s,r)};return h8({P:r,type:"x25519",powPminus2:e,adjustScalarBytes:x2,scalarMultBase:t=>{let n=De(t,fc.Fn.ORDER);if(n===p8)return p8;let s=fc.BASE.multiply(n);return De((s.Z+s.Y)*e(De(s.Z-s.Y,r)),r)}})})();var pc=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},mc=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},pd=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var st={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new pd("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");return e}};var yo=32,cr=64,v2=32;var Ii,w8=(async()=>{try{return await st.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function E8(){let r=hc.utils.randomSecretKey(),e=hc.getPublicKey(r);return{privateKey:OT(r,e),publicKey:e}}async function LT(r,e){let t;r.length===cr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:k(r.subarray(32),"base64url"),d:k(t,"base64url"),ext:!0,key_ops:["sign"]},s=await st.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await st.get().subtle.sign({name:"Ed25519"},s,he(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(o,0,o.byteLength)}function kT(r,e){let t=r.subarray(0,v2);return hc.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function x8(r,e){return Ii==null&&(Ii=await w8),Ii?LT(r,e):kT(r,e)}async function DT(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await st.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await st.get().subtle.verify({name:"Ed25519"},n,he(e),he(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function NT(r,e,t){return hc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function v8(r,e,t){return Ii==null&&(Ii=await w8),Ii?DT(r,e,t):NT(r,e,t)}function OT(r,e){let t=new Uint8Array(cr);for(let n=0;n<v2;n++)t[n]=r[n],t[v2+n]=e[n];return t}function _i(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gc=class{type="Ed25519";raw;constructor(e){this.raw=Pi(e,yo)}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=v8(this.raw,t,e);return _i(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},Ri=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Pi(e,cr),this.publicKey=new gc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=x8(this.raw,e);return _i(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}};function S2(r){if(r.length>cr){r=Pi(r,cr+yo);let n=r.subarray(0,cr),s=r.subarray(cr,r.length);return new Ri(n,s)}r=Pi(r,cr);let e=r.subarray(0,cr),t=r.subarray(yo);return new Ri(e,t)}function A2(r){return r=Pi(r,yo),new gc(r)}async function A8(){let{privateKey:r,publicKey:e}=E8();return new Ri(r,e)}function Pi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new v(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var MT=Math.pow(2,7),BT=Math.pow(2,14),UT=Math.pow(2,21),T2=Math.pow(2,28),C2=Math.pow(2,35),I2=Math.pow(2,42),_2=Math.pow(2,49),Pe=128,Rt=127;function Ne(r){if(r<MT)return 1;if(r<BT)return 2;if(r<UT)return 3;if(r<T2)return 4;if(r<C2)return 5;if(r<I2)return 6;if(r<_2)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Li(r,e,t=0){switch(Ne(r)){case 8:e[t++]=r&255|Pe,r/=128;case 7:e[t++]=r&255|Pe,r/=128;case 6:e[t++]=r&255|Pe,r/=128;case 5:e[t++]=r&255|Pe,r/=128;case 4:e[t++]=r&255|Pe,r>>>=7;case 3:e[t++]=r&255|Pe,r>>>=7;case 2:e[t++]=r&255|Pe,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function FT(r,e,t=0){switch(Ne(r)){case 8:e.set(t++,r&255|Pe),r/=128;case 7:e.set(t++,r&255|Pe),r/=128;case 6:e.set(t++,r&255|Pe),r/=128;case 5:e.set(t++,r&255|Pe),r/=128;case 4:e.set(t++,r&255|Pe),r>>>=7;case 3:e.set(t++,r&255|Pe),r>>>=7;case 2:e.set(t++,r&255|Pe),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function R2(r,e){let t=r[e],n=0;if(n+=t&Rt,t<Pe||(t=r[e+1],n+=(t&Rt)<<7,t<Pe)||(t=r[e+2],n+=(t&Rt)<<14,t<Pe)||(t=r[e+3],n+=(t&Rt)<<21,t<Pe)||(t=r[e+4],n+=(t&Rt)*T2,t<Pe)||(t=r[e+5],n+=(t&Rt)*C2,t<Pe)||(t=r[e+6],n+=(t&Rt)*I2,t<Pe)||(t=r[e+7],n+=(t&Rt)*_2,t<Pe))return n;throw new RangeError("Could not decode varint")}function $T(r,e){let t=r.get(e),n=0;if(n+=t&Rt,t<Pe||(t=r.get(e+1),n+=(t&Rt)<<7,t<Pe)||(t=r.get(e+2),n+=(t&Rt)<<14,t<Pe)||(t=r.get(e+3),n+=(t&Rt)<<21,t<Pe)||(t=r.get(e+4),n+=(t&Rt)*T2,t<Pe)||(t=r.get(e+5),n+=(t&Rt)*C2,t<Pe)||(t=r.get(e+6),n+=(t&Rt)*I2,t<Pe)||(t=r.get(e+7),n+=(t&Rt)*_2,t<Pe))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=Ge(Ne(r))),e instanceof Uint8Array?Li(r,e,t):FT(r,e,t)}function Or(r,e=0){return r instanceof Uint8Array?R2(r,e):$T(r,e)}var P2=new Float32Array([-0]),xs=new Uint8Array(P2.buffer);function T8(r,e,t){P2[0]=r,e[t]=xs[0],e[t+1]=xs[1],e[t+2]=xs[2],e[t+3]=xs[3]}function C8(r,e){return xs[0]=r[e],xs[1]=r[e+1],xs[2]=r[e+2],xs[3]=r[e+3],P2[0]}var L2=new Float64Array([-0]),Pt=new Uint8Array(L2.buffer);function I8(r,e,t){L2[0]=r,e[t]=Pt[0],e[t+1]=Pt[1],e[t+2]=Pt[2],e[t+3]=Pt[3],e[t+4]=Pt[4],e[t+5]=Pt[5],e[t+6]=Pt[6],e[t+7]=Pt[7]}function _8(r,e){return Pt[0]=r[e],Pt[1]=r[e+1],Pt[2]=r[e+2],Pt[3]=r[e+3],Pt[4]=r[e+4],Pt[5]=r[e+5],Pt[6]=r[e+6],Pt[7]=r[e+7],L2[0]}var KT=BigInt(Number.MAX_SAFE_INTEGER),VT=BigInt(Number.MIN_SAFE_INTEGER),lr=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 bo;if(e<KT&&e>VT)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>R8&&(s=0n,++n>R8&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return bo;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}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):bo}},bo=new lr(0,0);bo.toBigInt=function(){return 0n};bo.zzEncode=bo.zzDecode=function(){return this};bo.length=function(){return 1};var R8=4294967296n;function P8(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 L8(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function k2(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Mr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function md(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var D2=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=he(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,Mr(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 Mr(this,4);return md(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mr(this,4);return md(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mr(this,4);let e=C8(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mr(this,4);let e=_8(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 Mr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return L8(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while((this.buf[this.pos++]&128)!==0);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 lr(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 Mr(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 Mr(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 Mr(this,8);let e=md(this.buf,this.pos+=4),t=md(this.buf,this.pos+=4);return new lr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=R2(this.buf,this.pos);return this.pos+=Ne(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function yc(r){return new D2(r instanceof Uint8Array?r:r.subarray())}function se(r,e,t){let n=yc(r);return e.decode(n,void 0,t)}function N2(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ge(i);s+i>e&&(n=Ge(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var wo=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function O2(){}var B2=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},HT=N2();function qT(r){return globalThis.Buffer!=null?Ge(r):HT(r)}var wc=class{len;head;tail;states;constructor(){this.len=0,this.head=new wo(O2,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new U2((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(gd,10,lr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=lr.fromBigInt(e);return this._push(gd,t.length(),t)}uint64Number(e){return this._push(Li,Ne(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=lr.fromBigInt(e).zzEncode();return this._push(gd,t.length(),t)}sint64Number(e){let t=lr.fromNumber(e).zzEncode();return this._push(gd,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(M2,1,e?1:0)}fixed32(e){return this._push(bc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=lr.fromBigInt(e);return this._push(bc,4,t.lo)._push(bc,4,t.hi)}fixed64Number(e){let t=lr.fromNumber(e);return this._push(bc,4,t.lo)._push(bc,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(T8,4,e)}double(e){return this._push(I8,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(M2,1,0):this.uint32(t)._push(GT,t,e)}string(e){let t=P8(e);return t!==0?this.uint32(t)._push(k2,t,e):this._push(M2,1,0)}fork(){return this.states=new B2(this),this.head=this.tail=new wo(O2,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 wo(O2,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=qT(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function M2(r,e,t){e[t]=r&255}function zT(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var U2=class extends wo{next;constructor(e,t){super(zT,e,t),this.next=void 0}};function gd(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 bc(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 GT(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(wc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(WT,e,r),this},wc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(jT,e,r),this});function WT(r,e,t){e.set(r,t)}function jT(r,e,t){r.length<40?k2(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function F2(){return new wc}function oe(r,e){let t=F2();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ie(r,e,t){let n=yc(r);yield*e.stream(n,void 0,".",t)}var yd={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function bd(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function lt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i,a){};return bd("enum",yd.VARINT,t,n,s)}function ae(r,e,t){return bd("message",yd.LENGTH_DELIMITED,r,e,t)}var pe=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ec=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Oe||(Oe={}));var $2;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})($2||($2={}));(function(r){r.codec=()=>lt($2)})(Oe||(Oe={}));var an;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Oe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=Oe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Oe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(an||(an={}));var xc;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Oe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=Oe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Oe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(xc||(xc={}));var Sc={};fe(Sc,{MAX_RSA_KEY_SIZE:()=>K2,generateRSAKeyPair:()=>X2,jwkToJWKKeyPair:()=>M8,jwkToPkcs1:()=>ZT,jwkToPkix:()=>z2,jwkToRSAPrivateKey:()=>Y2,pkcs1MessageToJwk:()=>H2,pkcs1MessageToRSAPrivateKey:()=>wd,pkcs1ToJwk:()=>QT,pkcs1ToRSAPrivateKey:()=>G2,pkixMessageToJwk:()=>q2,pkixMessageToRSAPublicKey:()=>j2,pkixToJwk:()=>JT,pkixToRSAPublicKey:()=>W2});var ki=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Sc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return O8(this.jwk,t,e,n)}},vc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Sc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return N8(this.jwk,e,t)}};var K2=8192,V2=18,YT=1062,XT=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function QT(r){let e=wr(r);return H2(e)}function H2(r){return{n:k(r[1],"base64url"),e:k(r[2],"base64url"),d:k(r[3],"base64url"),p:k(r[4],"base64url"),q:k(r[5],"base64url"),dp:k(r[6],"base64url"),dq:k(r[7],"base64url"),qi:k(r[8],"base64url"),kty:"RSA"}}function ZT(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 v("JWK was missing components");return Dr([Ft(Uint8Array.from([0])),Ft(T(r.n,"base64url")),Ft(T(r.e,"base64url")),Ft(T(r.d,"base64url")),Ft(T(r.p,"base64url")),Ft(T(r.q,"base64url")),Ft(T(r.dp,"base64url")),Ft(T(r.dq,"base64url")),Ft(T(r.qi,"base64url"))]).subarray()}function JT(r){let e=wr(r,{offset:0});return q2(e)}function q2(r){let e=wr(r[1],{offset:0});return{kty:"RSA",n:k(e[0],"base64url"),e:k(e[1],"base64url")}}function z2(r){if(r.n==null||r.e==null)throw new v("JWK was missing components");return Dr([XT,rc(Dr([Ft(T(r.n,"base64url")),Ft(T(r.e,"base64url"))]))]).subarray()}function G2(r){let e=wr(r);return wd(e)}function wd(r){let e=H2(r);return Y2(e)}function W2(r,e){if(r.byteLength>=YT)throw new _r("Key size is too large");let t=wr(r,{offset:0});return j2(t,r,e)}function j2(r,e,t){let n=q2(r);if(t==null){let s=It(an.encode({Type:Oe.RSA,Data:e}));t=Ut(V2,s)}return new ki(n,t)}function Y2(r){if(U8(r)>K2)throw new v("Key size is too large");let e=M8(r),t=It(an.encode({Type:Oe.RSA,Data:z2(e.publicKey)})),n=Ut(V2,t);return new vc(e.privateKey,new ki(e.publicKey,n))}async function X2(r){if(r>K2)throw new v("Key size is too large");let e=await B8(r),t=It(an.encode({Type:Oe.RSA,Data:z2(e.publicKey)})),n=Ut(V2,t);return new vc(e.privateKey,new ki(e.publicKey,n))}function M8(r){if(r==null)throw new v("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function B8(r,e){let t=await st.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await eC(t,e);return{privateKey:n[0],publicKey:n[1]}}async function N8(r,e,t){let n=await st.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await st.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,he(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function O8(r,e,t,n){let s=await st.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await st.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,he(e),he(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function eC(r,e){if(r.privateKey==null||r.publicKey==null)throw new v("Private and public key are required");let t=await Promise.all([st.get().subtle.exportKey("jwk",r.privateKey),st.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function U8(r){if(r.kty!=="RSA")throw new v("invalid key type");if(r.n==null)throw new v("invalid key modulus");return T(r.n,"base64url").length*8}var Ed=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Rn(e),Ct(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),tt(s)}update(e){return wi(this),this.iHash.update(e),this}digestInto(e){wi(this),Gu(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Eo=(()=>{let r=((e,t,n)=>new Ed(e,t).update(n).digest());return r.create=(e,t)=>new Ed(e,t),r})();var tC=BigInt(0),Q2=class extends Error{constructor(e=""){super(e)}},Nn={Err:Q2,_tlv:{encode:(r,e)=>{let{Err:t}=Nn;if(kn(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(H5(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=ac(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?ac(s.length/2|128):"";return ac(r)+o+s+e},decode(r,e){let{Err:t}=Nn;e=Ee(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Nn;if(ed(r),r<tC)throw new e("integer: negative integers are not allowed");let t=ac(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Nn;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return rn(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:s}=Nn;if(e!==void 0&&(kn(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=Ee(r,void 0,"signature"),{v:i,l:a}=s.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=s.decode(2,i),{v:u,l:d}=s.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Nn;_t(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},xd=(Object.freeze(Nn._tlv),Object.freeze(Nn._int),Object.freeze(Nn));var F8=(r,e)=>(r+(r>=0?e:-e)/$8)/e;function rC(r,e,t){sn("scalar",r,On,t);let[[n,s],[o,i]]=e,a=F8(i*r,t),c=F8(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<On,f=u<On;d&&(l=-l),f&&(u=-u);let h=lc(Math.ceil(vi(t)/2))+xo;if(l<On||l>=h||u<On||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function em(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Z2(r,e){_t(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Yt(t.lowS,"lowS"),Yt(t.prehash,"prehash"),t.format!==void 0&&em(t.format),t}var On=BigInt(0),xo=BigInt(1),$8=BigInt(2),J2=BigInt(3),nC=BigInt(4);function K8(r,e={}){let t=cd("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;_t(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:f,toBytes:h}=e,p=e.randomBytes===void 0?Ln:e.randomBytes;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(_=>[..._])}:void 0,y=H8(n,s);function m(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function b(_,E,A){if(E.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:R,y:U}=E.toAffine(),q=n.toBytes(R);if(Yt(A,"isCompressed"),A){m();let z=!n.isOdd(U);return Er(V8(z),q)}else return Er(Uint8Array.of(4),q,n.toBytes(U))}function w(_){Ee(_,void 0,"Point");let{publicKey:E,publicKeyUncompressed:A}=y,R=_.length,U=_[0],q=_.subarray(1);if(l&&R===1&&U===0)return{x:n.ZERO,y:n.ZERO};if(R===E&&(U===2||U===3)){let z=n.fromBytes(q);if(!n.isValid(z))throw new Error("bad point: is not on curve, wrong x");let X=L(z),Q;try{Q=n.sqrt(X)}catch($e){let Me=$e instanceof Error?": "+$e.message:"";throw new Error("bad point: is not on curve, sqrt error"+Me)}m();let ce=n.isOdd(Q);return(U&1)===1!==ce&&(Q=n.neg(Q)),{x:z,y:Q}}else if(R===A&&U===4){let z=n.BYTES,X=n.fromBytes(q.subarray(0,z)),Q=n.fromBytes(q.subarray(z,z*2));if(!P(X,Q))throw new Error("bad point: is not on curve");return{x:X,y:Q}}else throw new Error(`bad point: got length ${R}, expected compressed=${E} or uncompressed=${A}`)}let x=h===void 0?b:h,S=f===void 0?w:f,C=n.mul(o.b,J2),I=n.is0(o.a)?_=>n.ZERO:_=>n.mul(o.a,_);function L(_){let E=n.sqr(_),A=n.mul(E,_);return n.add(n.add(A,n.mul(_,o.a)),o.b)}function P(_,E){let A=n.sqr(E),R=L(_);return n.eql(A,R)}if(!P(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let B=n.mul(n.pow(o.a,J2),nC),W=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(B,W)))throw new Error("bad curve params: a or b");function G(_,E,A=!1){if(!n.isValid(E)||A&&n.is0(E))throw new Error(`bad point coordinate ${_}`);return typeof E=="object"&&E!==null?n.create(E):E}function Z(_){if(!(_ instanceof D))throw new Error("Weierstrass Point expected")}function N(_){if(!g||!g.basises)throw new Error("no endo");return rC(_,g.basises,s.ORDER)}function $(_,E,A,R){if(!s.isValid(R))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:U,k1:q,k2neg:z,k2:X}=N(R),Q=new D(n.mul(A.X,g.beta),A.Y,A.Z);_.push(U?A.negate():A,z?Q.negate():Q),E.push(q,X)}else _.push(A),E.push(R)}let O=new WeakSet;class D{static BASE=new D(o.Gx,o.Gy,n.ONE);static ZERO=new D(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(E,A,R){this.X=G("x",E),this.Y=G("y",A,!0),this.Z=G("z",R),Object.freeze(this)}static CURVE(){return o}static fromAffine(E){let{x:A,y:R}=E||{};if(!E||!n.isValid(A)||!n.isValid(R))throw new Error("invalid affine point");if(E instanceof D)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(R)?D.ZERO:new D(A,R,n.ONE)}static fromBytes(E){let A=D.fromAffine(S(Ee(E,void 0,"point")));return A.assertValidity(),A}static fromHex(E){return D.fromBytes(xi(E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,A=!0){return M.setWindowSize(this,E),A||this.multiply(J2),this}assertValidity(){let E=this;if(E.is0()){if(l&&n.is0(E.X)&&n.eql(E.Y,n.ONE)&&n.is0(E.Z))return;throw new Error("bad point: ZERO")}if(O.has(E))return;let{x:A,y:R}=E.toAffine();if(!n.isValid(A)||!n.isValid(R))throw new Error("bad point: x or y not field elements");if(!P(A,R))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");O.add(E)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){Z(E);let{X:A,Y:R,Z:U}=this,{X:q,Y:z,Z:X}=E,Q=n.eql(n.mul(A,X),n.mul(q,U)),ce=n.eql(n.mul(R,X),n.mul(z,U));return Q&&ce}negate(){return new D(this.X,n.neg(this.Y),this.Z)}double(){let{X:E,Y:A,Z:R}=this,U=n.ZERO,q=n.ZERO,z=n.ZERO,X=n.mul(E,E),Q=n.mul(A,A),ce=n.mul(R,R),me=n.mul(E,A);return me=n.add(me,me),z=n.mul(E,R),z=n.add(z,z),U=I(z),q=n.mul(C,ce),q=n.add(U,q),U=n.sub(Q,q),q=n.add(Q,q),q=n.mul(U,q),U=n.mul(me,U),z=n.mul(C,z),ce=I(ce),me=n.sub(X,ce),me=I(me),me=n.add(me,z),z=n.add(X,X),X=n.add(z,X),X=n.add(X,ce),X=n.mul(X,me),q=n.add(q,X),ce=n.mul(A,R),ce=n.add(ce,ce),X=n.mul(ce,me),U=n.sub(U,X),z=n.mul(ce,Q),z=n.add(z,z),z=n.add(z,z),new D(U,q,z)}add(E){Z(E);let{X:A,Y:R,Z:U}=this,{X:q,Y:z,Z:X}=E,Q=n.ZERO,ce=n.ZERO,me=n.ZERO,$e=n.mul(A,q),Me=n.mul(R,z),Je=n.mul(U,X),Wt=n.add(A,R),Be=n.add(q,z);Wt=n.mul(Wt,Be),Be=n.add($e,Me),Wt=n.sub(Wt,Be),Be=n.add(A,U);let qe=n.add(q,X);return Be=n.mul(Be,qe),qe=n.add($e,Je),Be=n.sub(Be,qe),qe=n.add(R,U),Q=n.add(z,X),qe=n.mul(qe,Q),Q=n.add(Me,Je),qe=n.sub(qe,Q),me=I(Be),Q=n.mul(C,Je),me=n.add(Q,me),Q=n.sub(Me,me),me=n.add(Me,me),ce=n.mul(Q,me),Me=n.add($e,$e),Me=n.add(Me,$e),Je=I(Je),Be=n.mul(C,Be),Me=n.add(Me,Je),Je=n.sub($e,Je),Je=I(Je),Be=n.add(Be,Je),$e=n.mul(Me,Be),ce=n.add(ce,$e),$e=n.mul(qe,Be),Q=n.mul(Wt,Q),Q=n.sub(Q,$e),$e=n.mul(Wt,Me),me=n.mul(qe,me),me=n.add(me,$e),new D(Q,ce,me)}subtract(E){return Z(E),this.add(E.negate())}is0(){return this.equals(D.ZERO)}multiply(E){if(!s.isValidNot0(E))throw new RangeError("invalid scalar: out of range");let{p:A,f:R}=M.mulSecret(this,E,i,Y);return Y([A,R])[0]}multiplyUnsafe(E){let A=this,R=E;if(!s.isValid(R))throw new RangeError("invalid scalar: out of range");if(R===On||A.is0())return D.ZERO;if(R===xo)return A;if(M.hasWindowSize(this))return M.mulUnsafe(A,R,Y);let U=[],q=[];return $(U,q,A,R),ad(D,U,q)}mulAddUnsafe(E,A,R){Z(A);let U=[],q=[];return $(U,q,this,E),$(U,q,A,R),ad(D,U,q)}toAffine(E){let A=this,R=E;if(R!=null&&!n.isValid(R))throw new RangeError('"invertedZ" expected valid field element');let{X:U,Y:q,Z:z}=A;if(n.eql(z,n.ONE))return{x:U,y:q};let X=A.is0();R==null&&(R=X?n.ONE:n.inv(z));let Q=n.mul(U,R),ce=n.mul(q,R),me=n.mul(z,R);if(X)return{x:n.ZERO,y:n.ZERO};if(!n.eql(me,n.ONE))throw new Error("invZ was invalid");return{x:Q,y:ce}}isTorsionFree(){return i===xo?!0:d?d(D,this):M.mulUnsafe(this,a).is0()}clearCofactor(){return i===xo?this:u?u(D,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===xo?this.is0():this.clearCofactor().is0()}toBytes(E=!0){return Yt(E,"isCompressed"),this.assertValidity(),x(D,this,E)}toHex(E=!0){return ic(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Y=_=>id(D,_),M=new Ti(D,p);return M.bits>=6&&D.BASE.precompute(6),Object.freeze(D.prototype),Object.freeze(D),D}function V8(r){return Uint8Array.of(r?2:3)}function H8(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function sC(r,e={}){Es(r);let{Fn:t}=r,n=e.randomBytes===void 0?Ln:e.randomBytes,s=Object.assign(H8(r.Fp,t),{seed:Math.max(sd(t.ORDER),16)});function o(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:y}=s;try{let m=h.length;return p===!0&&m!==g||p===!1&&m!==y?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(s.seed):h,od(Ee(h,s.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:y}=s,m=t._lengths;if(!ys(h))return;let b=Ee(h,void 0,"key").length,w=b===g||b===y,x=b===p||!!m?.includes(b);if(!(w&&x))return w}function u(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h),m=r.fromBytes(p);if(m.is0())throw new Error("invalid public key: point at infinity");return m.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=Ci(a,c);return Object.freeze(d),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:s})}function q8(r,e,t={}){Es(r);let n=e;Rn(n),_t(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},t),o=s.randomBytes===void 0?Ln:s.randomBytes,i=s.hmac===void 0?(_,E)=>Eo(n,_,E):s.hmac,{Fp:a,Fn:c}=r,{ORDER:l,BITS:u}=c,d=sd(l),f=w2(o,d),{keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m}=sC(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},w=l*$8+xo<a.ORDER;function x(_){let E=l>>xo;return _>E}function S(_,E){if(!c.isValidNot0(E))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return E}function C(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function I(_,E,A){return C(),(_===A?0:2)|Number(a.isOdd(E))}function L(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(_,E){em(E);let A=m.signature,R=E==="compact"?A:E==="recovered"?A+1:void 0;return Ee(_,R)}class B{r;s;recovery;constructor(E,A,R){if(this.r=S("r",E),this.s=S("s",A),R!=null){if(L(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(E,A=b.format){P(E,A);let R;if(A==="der"){if(E.length>2*c.BYTES+16)throw new xd.Err("invalid signature: DER signature too long");let{r:X,s:Q}=xd.toSig(Ee(E),c.BYTES+1);return new B(X,Q)}A==="recovered"&&(R=E[0],A="compact",E=E.subarray(1));let U=m.signature/2,q=E.subarray(0,U),z=E.subarray(U,U*2);return new B(c.fromBytes(q),c.fromBytes(z),R)}static fromHex(E,A){return this.fromBytes(xi(E),A)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new B(this.r,this.s,E)}recoverPublicKey(E){let{r:A,s:R}=this,U=this.assertRecovery(),q=U===2||U===3?A+l:A;if(!a.isValid(q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let z=a.toBytes(q),X=r.fromBytes(Er(V8((U&1)===0),z)),Q=c.inv(q),ce=G(Ee(E,void 0,"msgHash")),me=c.create(-ce*Q),$e=c.create(R*Q),Me=r.BASE.mulAddUnsafe(me,X,$e);if(Me.is0())throw new Error("invalid recovery: point at infinify");return Me.assertValidity(),Me}hasHighS(){return x(this.s)}toBytes(E=b.format){if(em(E),E==="der")return xi(xd.hexFromSig(this));let{r:A,s:R}=this,U=c.toBytes(A),q=c.toBytes(R);return E==="recovered"?(L(),Er(Uint8Array.of(this.assertRecovery()),U,q)):Er(U,q)}toHex(E){return ic(this.toBytes(E))}}Object.freeze(B.prototype),Object.freeze(B);let W=s.bits2int===void 0?function(E){if(E.length>8192)throw new Error("input is too large");let A=rn(E),R=E.length*8-u;return R>0?A>>BigInt(R):A}:s.bits2int,G=s.bits2int_modN===void 0?function(E){return c.create(W(E))}:s.bits2int_modN,Z=lc(u);function N(_){return sn("num < 2^"+u,_,On,Z),c.toBytes(_)}function $(_,E){return Ee(_,void 0,"message"),E?Ee(n(_),void 0,"prehashed message"):_}function O(_,E,A){let{lowS:R,prehash:U,extraEntropy:q}=Z2(A,b);_=$(_,U);let z=G(_),X=c.fromBytes(E);if(!c.isValidNot0(X))throw new Error("invalid private key");let Q=[N(X),N(z)];if(q!=null&&q!==!1){let Me=q===!0?o(m.secretKey):q;Q.push(Ee(Me,void 0,"extraEntropy"))}let ce=Er(...Q),me=z;function $e(Me){let Je=W(Me);if(!c.isValidNot0(Je))return;let Wt=r.BASE.multiply(Je).toAffine(),Be=c.create(Wt.x);if(Be===On)return;let qe;if(f!==void 0){let is=rn(od(f(d),l)),hS=c.inv(c.mul(is,Je)),pS=c.mul(is,me),mS=c.mul(is,X);qe=c.create(hS*c.create(pS+mS*Be))}else{let is=J5(Je,l);qe=c.create(is*c.create(me+Be*X))}if(qe===On)return;let si=I(Wt.x,Wt.y,Be),Ha=qe;return R&&x(qe)&&(Ha=c.neg(qe),si^=1),new B(Be,Ha,w?void 0:si)}return{seed:ce,k2sig:$e}}function D(_,E,A={}){let{seed:R,k2sig:U}=O(_,E,A);return z5(n.outputLen,c.BYTES,i)(R,U).toBytes(A.format)}function Y(_,E,A,R={}){let{lowS:U,prehash:q,format:z}=Z2(R,b);if(A=Ee(A,void 0,"publicKey"),E=$(E,q),!ys(_)){let X=_ instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+X)}P(_,z);try{let X=B.fromBytes(_,z),Q=r.fromBytes(A);if(Q.is0()||U&&X.hasHighS())return!1;let{r:ce,s:me}=X,$e=G(E),Me=c.inv(me),Je=c.create($e*Me),Wt=c.create(ce*Me),Be=r.BASE.mulAddUnsafe(Je,Q,Wt);if(Be.is0())return!1;let qe=Be.toAffine();return!(c.create(qe.x)!==ce||z==="recovered"&&X.recovery!==I(qe.x,qe.y,ce))}catch{return!1}}function M(_,E,A={}){let{prehash:R}=Z2(A,b);return E=$(E,R),B.fromBytes(_,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m,Point:r,sign:D,verify:Y,recoverPublicKey:M,Signature:B,hash:n})}var rm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oC={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var z8=BigInt(2);function iC(r){let e=rm.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ke(u,t,e)*u%e,f=Ke(d,t,e)*u%e,h=Ke(f,z8,e)*l%e,p=Ke(h,s,e)*h%e,g=Ke(p,o,e)*p%e,y=Ke(g,a,e)*g%e,m=Ke(y,c,e)*y%e,b=Ke(m,a,e)*g%e,w=Ke(b,t,e)*u%e,x=Ke(w,i,e)*p%e,S=Ke(x,n,e)*l%e,C=Ke(S,z8,e);if(!tm.eql(tm.sqr(C),r))throw new Error("Cannot find square root");return C}var tm=Ai(rm.p,{sqrt:iC}),aC=K8(rm,{Fp:tm,endo:oC}),Br=q8(aC,It);var G8=32;function W8(r,e,t){let n=yt.digest(e instanceof Uint8Array?e:e.subarray());if(_i(n))return n.then(({digest:s})=>(t?.signal?.throwIfAborted(),Br.sign(s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new pc(String(s))});try{return Br.sign(n.digest,r,{prehash:!1,format:"der"})}catch(s){throw new pc(String(s))}}function j8(r,e,t,n){let s=yt.digest(t instanceof Uint8Array?t:t.subarray());if(_i(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Br.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new mc(String(o))});try{return n?.signal?.throwIfAborted(),Br.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new mc(String(o))}}var Ac=class{type="secp256k1";raw;_key;constructor(e){this._key=Q8(e),this.raw=Y8(this._key)}toMultihash(){return ar.digest(nt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return Ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return j8(this._key,t,e,n)}},Tc=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=X8(e),this.publicKey=new Ac(t??Z8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return W8(this.raw,e,t)}};function nm(r){return new Tc(r)}function sm(r){return new Ac(r)}async function J8(){let r=cC();return new Tc(r)}function Y8(r){return Br.Point.fromBytes(r).toBytes()}function X8(r){try{return Br.getPublicKey(r,!0),r}catch(e){throw new qa(String(e))}}function Q8(r){try{return Br.Point.fromBytes(r),r}catch(e){throw new _r(String(e))}}function Z8(r){try{return Br.getPublicKey(r,!0)}catch(e){throw new qa(String(e))}}function cC(){return Br.utils.randomSecretKey()}async function vd(r,e){if(r==="Ed25519")return A8();if(r==="secp256k1")return J8();if(r==="RSA")return X2(lC(e));if(r==="ECDSA")return A5(uC(e));throw new Lr}function We(r,e){let{Type:t,Data:n}=an.decode(r),s=n??new Uint8Array;switch(t){case Oe.RSA:return W2(s,e);case Oe.Ed25519:return A2(s);case Oe.secp256k1:return sm(s);case Oe.ECDSA:return Jp(s);default:throw new Lr}}function e7(r){let{Type:e,Data:t}=an.decode(r.digest),n=t??new Uint8Array;switch(e){case Oe.Ed25519:return A2(n);case Oe.secp256k1:return sm(n);case Oe.ECDSA:return Jp(n);default:throw new Lr}}function nt(r){return an.encode({Type:Oe[r.type],Data:r.raw})}function t7(r){let e=xc.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Oe.RSA:return G2(t);case Oe.Ed25519:return S2(t);case Oe.secp256k1:return nm(t);case Oe.ECDSA:return w5(t);default:throw new Lr}}function r7(r){if(r.byteLength===cr)return S2(r);if(r.byteLength===G8)return nm(r);let e=wr(r),t=e[2]?.[0];if(t===e5||t===t5||t===r5)return Zp(e);if(e.length>8)return wd(e);throw new v("Could not extract private key from raw bytes")}function vo(r){return xc.encode({Type:Oe[r.type],Data:r.raw})}function lC(r){return r==null?2048:parseInt(r,10)}function uC(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new v("Unsupported curve, should be P-256, P-384 or P-521")}var Cc=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),vs=new Uint32Array(80),om=class extends po{A=Cc[0]|0;B=Cc[1]|0;C=Cc[2]|0;D=Cc[3]|0;E=Cc[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o}=this;return[e,t,n,s,o]}set(e,t,n,s,o){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let c=0;c<16;c++,t+=4)vs[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)vs[c]=Wu(vs[c-3]^vs[c-8]^vs[c-14]^vs[c-16],1);let{A:n,B:s,C:o,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Xu(s,o,i),u=1518500249):c<40?(l=s^o^i,u=1859775393):c<60?(l=Qu(s,o,i),u=2400959708):(l=s^o^i,u=3395469782);let d=Wu(n,5)+l+a+u+vs[c]|0;a=i,i=o,o=Wu(s,30),s=n,n=d}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,s,o,i,a)}roundClean(){tt(vs)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),tt(this.buffer)}},n7=oc(()=>new om);function s7(r,e,t,n){Rn(r);let s=o2({dkLen:32,asyncTick:10},n),{c:o,dkLen:i,asyncTick:a}=s;if(bt(o,"c"),bt(i,"dkLen"),bt(a,"asyncTick"),o<1)throw new Error('"c" (iterations) must be >= 1');if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=n2(e,"password");try{let l=n2(t,"salt");try{let u=new Uint8Array(i),{iHash:d,oHash:f,outputLen:h}=Eo.create(r,c),p=new Uint8Array(h),g=dC(d,f,l,p);return{c:o,dkLen:i,asyncTick:a,DK:u,outputLen:h,eng:g}}finally{typeof t=="string"&&tt(l)}}finally{typeof e=="string"&&tt(c)}}function dC(r,e,t,n){let s=new Uint8Array(4),o=Ei(s),i=r._cloneInto().update(t),a=e._cloneInto(),c=r._cloneInto,l=e._cloneInto;return{u1:(u,d)=>{o.setInt32(0,u,!1),i._cloneInto(a).update(s).digestInto(n),e._cloneInto(a).update(n).digestInto(n),d.set(n.subarray(0,d.length))},rounds:(u,d)=>{for(let f=1;f<u;f++){c.call(r,a).update(n).digestInto(n),l.call(e,a).update(n).digestInto(n);for(let h=0;h<d.length;h++)d[h]^=n[h]}},output:u=>(r.destroy(),e.destroy(),i.destroy(),a.destroy(),tt(n),u)}}function o7(r,e,t,n){let{c:s,dkLen:o,DK:i,outputLen:a,eng:c}=s7(r,e,t,n);for(let l=1,u=0;u<o;l++,u+=a){let d=i.subarray(u,u+a);c.u1(l,d),c.rounds(s,d)}return c.output(i)}async function Sd(r,e,t,n){let{c:s,dkLen:o,asyncTick:i,DK:a,outputLen:c,eng:l}=s7(r,e,t,n),u=()=>{l.output(a),tt(a)};for(let d=1,f=0;f<o;d++,f+=c){let h=a.subarray(f,f+c);l.u1(d,h),await B5(s-1,i,()=>{l.rounds(2,h)},u)}return l.output(a)}var i7={sha1:n7,"sha2-256":It,"sha2-512":Pn};function Ic(r,e,t,n,s){if(s!=="sha1"&&s!=="sha2-256"&&s!=="sha2-512"){let a=Object.keys(i7).join(" / ");throw new v(`Hash '${s}' is unknown or not supported. Must be ${a}`)}let o=i7[s],i=o7(o,r,e,{c:t,dkLen:n});return _n.encode(i).substring(1)}var Mn="/",a7=new TextEncoder().encode(Mn),Ad=a7[0],Lt=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(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]!==Ad)throw new Error("Invalid key")}toString(e="utf8"){return k(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mn))}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=a7),this._buf[0]!==Ad){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ad,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ad;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>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(Mn).slice(1)}type(){return fC(this.baseNamespace())}name(){return hC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mn)||(e+=Mn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mn):new r(e.slice(0,-1).join(Mn))}child(e){return this.toString()===Mn?e:e.toString()===Mn?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(),...pC(e.map(t=>t.namespaces()))])}};function fC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function hC(r){let e=r.split(":");return e[e.length-1]}function pC(r){return[].concat(...r)}var ay=oi(g7(),1);var im={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var Di={};fe(Di,{create:()=>IC,derivedEmptyPasswordKey:()=>Td});var Td={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function IC(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,s=r?.digest??"SHA-256",o=r?.saltLength??16,i=r?.iterations??32767,a=st.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof f=="string"&&(f=T(f));let y;if(f.length===0){y=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},w=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},w=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(g,y,he(d));return et([h,g.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,o),p=d.subarray(o,o+n),g=d.subarray(o+n),y={name:e,iv:p};typeof f=="string"&&(f=T(f));let m;if(f.length===0)try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},x=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",Td,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:s}},x=await a.subtle.importKey("raw",he(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,m,he(g));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var we=oi(y7());function So(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 Ss(r,e,t=-1){let n=t,s=r,o=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),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[o-u-1]=Math.floor(s/d),s-=l[o-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function _d(...r){let e=0,t=0;for(let o of r)e+=o.length;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let o of r)s.set(o,t),t+=o.length;return s}function cm(){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=So(t,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=r[a];return o[0]&=127,So(o,8)-n}function b7(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=Ss(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Ss(e,8,n),o=new Uint8Array(s);if(o[0]&128){let i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function w7(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}function Qt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,s=Array.from({length:n});for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(t)}var q$=Math.log(2);function Rd(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function lm(r){let e=0,t=0;for(let s=0;s<r.length;s++){let o=r[s];e+=o.byteLength}let n=new Uint8Array(e);for(let s=0;s<r.length;s++){let o=r[s];n.set(new Uint8Array(o),t),t+=o.byteLength}return n.buffer}function Vn(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 Pc=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return lm(this.items)}},_c=[new Uint8Array([1])],E7="0123456789";var Oi="",un=new ArrayBuffer(0),um=new Uint8Array(0),Lc="EndOfContent",v7="OCTET STRING",S7="BIT STRING";function Hn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var s;super(...n);let o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?we.BufferSourceConverter.toUint8Array(o.valueHex):um}fromBER(n,s,o,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Vn(this,a,s,o))return-1;let c=s+o;return this.valueHexView=a.subarray(s,c),this.valueHexView.length?(this.blockLength=o,c):(this.warnings.push("Zero buffer length"),s)}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",un)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:we.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Un=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Oi,warnings:n=[],valueBeforeDecode:s=um}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=we.BufferSourceConverter.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:we.Convert.ToHex(this.valueBeforeDecodeView)}}};Un.NAME="baseBlock";var wt=class extends Un{fromBER(e,t,n,s){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'")}};wt.NAME="valueBlock";var Pd=class extends Hn(Un){constructor({idBlock:e={}}={}){var t,n,s,o;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?we.BufferSourceConverter.toUint8Array(e.valueHex):um,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!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",un}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,t|=o,s[0]=t}return s.buffer}if(!this.isHexOnly){let s=Ss(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,t,n){let s=we.BufferSourceConverter.toUint8Array(e);if(!Vn(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[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=(o[0]&32)===32,this.isHexOnly=!1;let a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(o[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=o[u+1]&127;this.blockLength<=9?this.tagNumber=So(l,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}}};Pd.NAME="identificationBlock";var Ld=class extends Un{constructor({lenBlock:e={}}={}){var t,n,s;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=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,t,n){let s=we.BufferSourceConverter.toUint8Array(e);if(!Vn(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=So(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 s=Ss(this.length,8);if(s.byteLength>127)return this.error="Too big length",un;if(t=new ArrayBuffer(s.byteLength+1),e)return t;let o=new Uint8Array(s);n=new Uint8Array(t),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[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}}};Ld.NAME="lengthBlock";var H={},ht=class extends Un{constructor({name:e=Oi,optional:t=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Pd(s),this.lenBlock=new Ld(s),this.valueBlock=o?new o(s):new wt(s)}fromBER(e,t,n,s){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);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 Pc;t||A7(this);let s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return t?un: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():we.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=we.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return w7(t,n)}};ht.NAME="BaseBlock";function A7(r){var e;if(r instanceof H.Constructed)for(let t of r.valueBlock.value)A7(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var kd=class extends ht{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Oi,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(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),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};kd.NAME="BaseStringBlock";var Dd=class extends Hn(wt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Dd.NAME="PrimitiveValueBlock";var T7,Nd=class extends ht{constructor(e={}){super(e,Dd),this.idBlock.isConstructed=!1}};T7=Nd;H.Primitive=T7;Nd.NAME="PRIMITIVE";var MC=100,BC=1e4,UC=16*1024*1024,FC="Maximum ASN.1 nesting depth exceeded",$C="Maximum ASN.1 node count exceeded",KC="Maximum ASN.1 content length exceeded";function Bc(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:MC,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:BC,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:UC}}function VC(r){let e=new ht({},wt);return e.error=r,{offset:-1,result:e}}function HC(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return $C}function qC(r,e){if(r>e.maxContentLength)return KC}function dm(r,e,t,n){let s=n.depth+1;if(s>n.maxDepth)return VC(FC);n.depth=s;try{return C7(r,e,t,n)}finally{n.depth-=1}}function zC(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 C7(r,e=0,t=r.length,n=Bc()){let s=e,o=new ht({},wt),i=new Un;if(!Vn(i,r,e,t))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let c=HC(n);if(c)return o.error=c,{offset:-1,result:o};let l=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),l===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=l,t-=o.idBlock.blockLength,l=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),l===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};e=l,t-=o.lenBlock.blockLength;let u=o.lenBlock.isIndefiniteForm?t:o.lenBlock.length,d=qC(u,n);if(d)return o.error=d,{offset:-1,result:o};if(!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let f=ht;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};f=H.EndOfContent;break;case 1:f=H.Boolean;break;case 2:f=H.Integer;break;case 3:f=H.BitString;break;case 4:f=H.OctetString;break;case 5:f=H.Null;break;case 6:f=H.ObjectIdentifier;break;case 10:f=H.Enumerated;break;case 12:f=H.Utf8String;break;case 13:f=H.RelativeObjectIdentifier;break;case 14:f=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:f=H.Sequence;break;case 17:f=H.Set;break;case 18:f=H.NumericString;break;case 19:f=H.PrintableString;break;case 20:f=H.TeletexString;break;case 21:f=H.VideotexString;break;case 22:f=H.IA5String;break;case 23:f=H.UTCTime;break;case 24:f=H.GeneralizedTime;break;case 25:f=H.GraphicString;break;case 26:f=H.VisibleString;break;case 27:f=H.GeneralString;break;case 28:f=H.UniversalString;break;case 29:f=H.CharacterString;break;case 30:f=H.BmpString;break;case 31:f=H.DATE;break;case 32:f=H.TimeOfDay;break;case 33:f=H.DateTime;break;case 34:f=H.Duration;break;default:{let h=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;h.idBlock=o.idBlock,h.lenBlock=o.lenBlock,h.warnings=o.warnings,o=h}}break;default:f=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=zC(o,f),l=o.fromBER(r,e,u,n),o.valueBeforeDecodeView=r.subarray(s,s+o.blockLength),{offset:l,result:o}}function mf(r,e={}){if(!r.byteLength){let t=new ht({},wt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return C7(we.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,Bc(e))}function GC(r,e){return r?1:e}var cn=class extends wt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,s){let o=we.BufferSourceConverter.toUint8Array(e),i=s??Bc();if(!Vn(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 a=t;for(;GC(this.isIndefiniteForm,n)>0;){let c=dm(o,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Lc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Lc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Pc;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return t?un:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};cn.NAME="ConstructedValueBlock";var I7,As=class extends ht{constructor(e={}){super(e,cn),this.idBlock.isConstructed=!0}fromBER(e,t,n,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);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(s=>` ${s}`).join(`
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
@@ -14,7 +14,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
14
14
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function yI(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function dy(r,e=""){if(yI(r)){let t=ly(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
15
15
|
${e}${r.errors.map(n=>`${dy(n,`${e}`)}`).join(`
|
|
16
16
|
${e}`)}`):t+=`
|
|
17
|
-
${e}[Error list was empty]`,t.trim()}return ly(r,e)}Jt.formatters.e=r=>r==null?"undefined":dy(r);function bI(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Ui(r){return{forComponent(e){return fy(e,r)}}}function fy(r,e){let t=bI(`${r}:trace`);return Jt.enabled(`${r}:trace`)&&Jt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Jt(`${r}:trace`,e)),Object.assign(Jt(r,e),{error:Jt(`${r}:error`,e),trace:t,newScope:n=>fy(`${r}:${n}`,e)})}function uy(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}async function ym(r,e={}){let t=e.selfKey??"self",n=bf(e)({datastore:r,logger:Ui()}),s;return await r.has(new Lt(`/pkcs8/${t}`))?s=await n.exportKey(t):(s=await vd(e.keyType??"Ed25519"),await n.importKey(t,s)),s}var hy=Symbol.for("nodejs.util.inspect.custom"),wI=114,$c=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bu]=!0;toString(){return this.string==null&&(this.string=Ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(wI,this.multihash)}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 this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[hy](){return`PeerId(${this.toString()})`}},Kc=class extends $c{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Vc=class extends $c{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Hc=class extends $c{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},EI=2336,qc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ar.digest(T(this.url))}[hy](){return`PeerId(${this.url})`}[Bu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(EI,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=k(e)),e.toString()===this.toString())}};var xI=114,py=2336;function Ve(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=_e(Ie.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return xt(ge.parse(r));if(e==null)throw new v('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=_e(e.decode(r))}return ot(t)}function ur(r){if(r.type==="Ed25519")return new Vc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Hc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Kc({multihash:r.toCID().multihash,publicKey:r});throw new Lr}function my(r){return ur(r.publicKey)}function ot(r){if(SI(r))return new Kc({multihash:r});if(vI(r))try{let e=e7(r);if(e.type==="Ed25519")return new Vc({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Hc({multihash:r,publicKey:e})}catch{let t=k(r.digest);return new qc(new URL(t))}throw new Lu("Supplied PeerID Multihash is invalid")}function xt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==xI&&r.code!==py)throw new Pu("Supplied PeerID CID is invalid");if(r.code===py){let e=k(r.multihash.digest);return new qc(new URL(e))}return ot(r.multihash)}function vI(r){return r.code===ar.code}function SI(r){return r.code===yt.code}function AI(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Fi=AI;function TI(r){return r[Symbol.asyncIterator]!=null}function gy(r){return r?.then!=null}function CI(r,e){let t=0;if(TI(r))return(async function*(){for await(let c of r){let l=e(c,t++);gy(l)&&await l,yield c}})();let n=Fi(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i?.then=="function")return(async function*(){await i,yield s;for(let c of n){let l=e(c,t++);gy(l)&&await l,yield c}})();let a=e;return(function*(){yield s;for(let c of n)a(c,t++),yield c})()}var bm=CI;async function yy(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new v("Private network is enforced, but no protector was provided");return r}function _o(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function xf(r){let e=_e(Ie.decode(`z${r}`));return ot(e)}var kt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return _o(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return _o(this.map.values(),e=>e.key)}values(){return _o(this.map.values(),e=>e.value)}get size(){return this.map.size}};var dr=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 _o(this.set.entries(),e=>{let t=xf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return _o(this.set.values(),e=>xf(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}};function wm(){return new dr}var Em={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},by={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},wy=new globalThis.TextEncoder;function II(r,e){let t=Em[e],n=by[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function _I(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Em[e],s=by[e],o=r;for(;o.length>0;){let i=wy.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function xm(r,{size:e=32,utf8Buffer:t}={}){if(!Em[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return _I(r,e,t);r=wy.encode(r)}return II(r,e)}var zc={hash:r=>Number(xm(r,{size:32})),hashV:(r,e)=>RI(zc.hash(r,e))};function RI(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var vm=64,Ur=class{fp;h;seed;constructor(e,t,n,s=2){if(s>vm)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ne(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function Ro(r,e){return Math.floor(Math.random()*(e-r))+r}var Po=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");let t=Ro(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var PI=500,Gc=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??zc,this.seed=e.seed??Ro(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Po(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Po(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Ro(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Po(this.bucketSize));for(let a=0;a<PI;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Po(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},LI={1:.5,2:.84,4:.95,8:.98};function kI(r=.001){return r>.002?2:r>1e-5?4:8}function Ey(r,e=.001){let t=kI(e),n=LI[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),vm);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var vf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??zc,this.seed=e.seed??Ro(0,Math.pow(2,10)),this.filterSeries=[new Gc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Gc({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function er(r,e=.001,t){return new vf({...Ey(r,e),...t??{}})}function Sm(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function ee(r){let e=Sm(r);if(e==null)throw new v(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Sf=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var xy=45,DI=15,$i=new Sf;function Af(r){if(!(r.length>DI))return $i.new(r).parseWith(()=>$i.readIPv4Addr())}function Tf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>xy))return $i.new(r).parseWith(()=>$i.readIPv6Addr())}function Ki(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>xy)return;let t=$i.new(r).parseWith(()=>$i.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function vy(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Sy(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Am(r){switch(r.length){case Lo:return r.join(".");case ko:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Ay(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Ty(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Lo=4,ko=16,nH=parseInt("0xFFFF",16),NI=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Wc(r,e){e.length===ko&&r.length===Lo&&vy(e,0,11)&&(e=e.slice(12)),e.length===Lo&&r.length===ko&&Sy(r,NI,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Cy(r,e){if(typeof e=="string"&&(e=Ki(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Tm(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Lo,s=Af(e);if(s==null&&(n=ko,s=Tf(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Cm(o,8*n);return{network:Wc(s,i),mask:i}}function Cm(r,e){if(e!==8*Lo&&e!==8*ko)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var Do=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Tm(e));else{let n=Ki(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=Ki(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=Cm(s,8*n.length);this.network=Wc(n,this.mask)}}contains(e){return Cy({network:this.network,mask:this.mask},e)}toString(){let e=Ay(this.mask),t=e!==-1?String(e):Ty(this.mask);return Am(this.network)+"/"+t}};function Iy(r,e){return new Do(r).contains(e)}function Cf(r){try{let e=ee(r);return e.type==="ip6"?Iy("2000::/3",e.host):!1}catch{return!1}}function _y(r){try{let e=ee(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Ry(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let s=n.split(".");return s.length===4&&s[0]==="127"&&s.every(o=>/^\d{1,3}$/.test(o))}function jc(r){try{let e=ee(r);switch(e.type){case"ip4":case"ip6":return Ry(e.host);default:return!1}}catch{return!1}}function vt(r){return Sm(r)!==null}function Fr(r){return!!Af(r)}function If(r){return!!Tf(r)}var Dy=oi(ky(),1),KI=["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"],VI=KI.map(r=>new Dy.Netmask(r));function Dm(r){for(let e of VI)if(e.contains(r))return!0;return!1}function HI(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function qI(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Dm(s)}function zI(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function GI(r){let e=r.split(":"),t=e[e.length-1];return Dm(t)}function WI(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function zi(r){if(Fr(r))return Dm(r);if(HI(r))return qI(r);if(zI(r))return GI(r);if(If(r))return WI(r)}function it(r){try{let e=ee(r);switch(e.type){case"ip4":case"ip6":return zi(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function qn(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Sr(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=Ge(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return $u(t)}var St=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},zn=class extends Error{static name="ValidationError";name="ValidationError"},Rf=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Pf=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Om(r){return e=>k(e,r)}function Mm(r){return e=>T(e,r)}function Gi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Oo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}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!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oo(n);return et([t,s],t.length+s.length)}function Oy(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=br.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 s=Oo(n);return et([t,s],t.length+s.length)}function Bm(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=k(e,"base32"),s=Gi(t);return`${n}:${s}`}var Um=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new St("Invalid byte value in IP address");e[n]=s}),e},My=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Fr(t[n]),i;o&&(i=Um(t[n]),t[n]=k(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,k(i.subarray(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 o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new St("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},By=function(r){if(r.byteLength!==4)throw new St("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Uy=function(r){if(r.byteLength!==16)throw new St("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${t}"`)}};function Fy(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${r}"`)}}var Nm=Object.values(co).map(r=>r.decoder),jI=(function(){let r=Nm[0].or(Nm[1]);return Nm.slice(2).forEach(e=>r=r.or(e)),r})();function $y(r){return jI.decode(r)}function Ky(r){return e=>r.encoder.encode(e)}function YI(r){if(parseInt(r).toString()!==r)throw new zn("Value must be an integer")}function XI(r){if(r<0)throw new zn("Value must be a positive integer, or zero")}function QI(r){return e=>{if(e>r)throw new zn(`Value must be smaller than or equal to ${r}`)}}function ZI(...r){return e=>{for(let t of r)t(e)}}var Yc=ZI(YI,XI,QI(65535));var pt=-1,Fm=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Pf(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Wn=new Fm,f_=[{code:4,name:"ip4",size:32,valueToBytes:Um,bytesToValue:By,validate:r=>{if(!Fr(r))throw new zn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:273,name:"udp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:33,name:"dccp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:41,name:"ip6",size:128,valueToBytes:My,bytesToValue:Uy,stringToValue:Fy,validate:r=>{if(!If(r))throw new zn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pt},{code:43,name:"ipcidr",size:8,bytesToValue:Om("base10"),valueToBytes:Mm("base10")},{code:53,name:"dns",size:pt},{code:54,name:"dns4",size:pt},{code:55,name:"dns6",size:pt},{code:56,name:"dnsaddr",size:pt},{code:132,name:"sctp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pt,bytesToValue:Om("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Mm("base58btc")(r):ge.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bm,valueToBytes:Ny},{code:445,name:"onion3",size:296,bytesToValue:Bm,valueToBytes:Oy},{code:446,name:"garlic64",size:pt},{code:447,name:"garlic32",size:pt},{code:448,name:"tls"},{code:449,name:"sni",size:pt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pt,bytesToValue:Ky(Za),valueToBytes:$y},{code:480,name:"http"},{code:481,name:"http-path",size:pt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pt}];f_.forEach(r=>{Wn.addProtocol(r)});function Vy(r){let e=[],t=0;for(;t<r.length;){let n=Or(r,t),s=Wn.getProtocol(n),o=Ne(n),i=h_(s,r,t+o),a=0;i>0&&s.size===pt&&(a=Ne(i));let c=o+a+i,l={code:n,name:s.name,bytes:he(r.subarray(t,t+c))};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??k(d)}e.push(l),t+=c}return e}function Hy(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Wn.getProtocol(n.code),o=Ne(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,s.size===pt&&(c=Ne(a)));let l=new Uint8Array(o+c+a),u=0;Li(n.code,l,u),u+=o,i!=null&&(s.size===pt&&(Li(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return et(t,e)}function qy(r){if(r.charAt(0)!=="/")throw new St('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Wn.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new St(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new St(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new St("Incomplete multiaddr");return e}function zy(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Wn.getProtocol(e.code);if(t==null)throw new St(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function h_(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Or(e,t)}var p_=Symbol.for("nodejs.util.inspect.custom"),jm=Symbol.for("@multiformats/multiaddr");function m_(r){if(r==null&&(r="/"),hn(r))return r.getComponents();if(r instanceof Uint8Array)return Vy(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qy(r);if(Array.isArray(r))return r;throw new St("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Of=class r{[jm]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=m_(e),t.validate!==!1&&g_(this)}get bytes(){return this.#r==null&&(this.#r=Hy(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=zy(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Rf(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return te(this.bytes,e.bytes)}[p_](){return`Multiaddr(${this.toString()})`}};function g_(r){r.getComponents().forEach(e=>{let t=Wn.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function hn(r){return!!r?.[jm]}function F(r){return new Of(r)}var Le=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),J=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Gy=r=>({match:e=>r.match(e)===!1?e:!1}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Dt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),xe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ke(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var y_=J(421),Wy=ke(y_),Bf=J(54),Uf=J(55),Ff=J(56),Xm=J(53),qq=ke(Bf,be(J(421))),zq=ke(Uf,be(J(421))),Gq=ke(Ff,be(J(421))),jy=ke(Dt(Xm,Ff,Bf,Uf),be(J(421))),Yy=xe(J(4),be(J(43))),Xy=xe(be(J(42)),J(41),be(J(43))),Qm=Dt(Yy,Xy),Xi=Dt(Qm,Xm,Bf,Uf,Ff),Qy=ke(Dt(Qm,xe(Dt(Xm,Ff,Bf,Uf),be(J(421))))),Zm=ke(Yy),Jm=ke(Xy),Zy=ke(Qm),e3=xe(Xi,J(6)),tl=xe(Xi,J(273)),Bo=ke(xe(e3,be(J(421)))),Wq=ke(tl),t3=xe(tl,Le(460),be(J(421))),$f=xe(tl,Le(461),be(J(421))),b_=Dt(t3,$f),jq=ke(t3),Jy=ke($f),Ym=Dt(Xi,e3,tl,t3,$f),e9=Dt(xe(Ym,Le(477),be(J(421)))),jn=ke(e9),t9=Dt(xe(Ym,Le(478),be(J(421))),xe(Ym,Le(448),be(J(449)),Le(477),be(J(421)))),Uo=ke(t9),r9=xe(tl,Le(280),be(J(466)),be(J(466)),be(J(421))),rl=ke(r9),n9=xe($f,Le(465),be(J(466)),be(J(466)),be(J(421))),r3=ke(n9),Mf=Dt(e9,t9,xe(e3,be(J(421))),xe(b_,be(J(421))),xe(Xi,be(J(421))),r9,n9,J(421)),Qi=ke(Mf),w_=xe(be(Mf),Le(290),Gy(Le(281)),be(J(421))),mt=ke(w_),E_=Dt(xe(Mf,Le(290),Le(281),be(J(421))),xe(Mf,Le(281),be(J(421))),xe(Le(281),be(J(421)))),nl=ke(E_),x_=xe(Xi,Dt(xe(J(6,"80")),xe(J(6),Le(480)),Le(480)),be(J(481)),be(J(421))),Yq=ke(x_),v_=xe(Xi,Dt(xe(J(6,"443")),xe(J(6,"443"),Le(480)),xe(J(6),Le(443)),xe(J(6),Le(448),Le(480)),xe(Le(448),Le(480)),Le(448),Le(443)),be(J(481)),be(J(421))),Xq=ke(v_),S_=Dt(xe(J(777),be(J(421)))),Qq=ke(S_),A_=Dt(xe(J(400),be(J(421)))),Zq=ke(A_);function s9(r,e){let t=Bo.exactMatch(r),n=Bo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let s=Uo.exactMatch(r),o=Uo.exactMatch(e);if(s&&!o)return-1;if(!s&&o)return 1;let i=jn.exactMatch(r),a=jn.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nl.exactMatch(r),l=nl.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=rl.exactMatch(r),d=rl.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=r3.exactMatch(r),h=r3.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function o9(r,e){let t=jc(r),n=jc(e);return t&&!n?1:!t&&n?-1:0}function i9(r,e){let t=it(r),n=it(e);return t&&!n?1:!t&&n?-1:0}function a9(r,e){let t=mt.exactMatch(r),n=mt.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Xe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Kf=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},Zi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Kf(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 Kf(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 n3=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(r={}){return T_(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 T_(r,e){e=e??{};let t=e.onEnd,n=new Zi,s,o,i,a=Xe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(w){m(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Xe()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new Zi,o!=null?o({error:y}):(n.push({error:y}),s)),d=y=>{if(i)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Zi,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,w;m!=null&&(b=new Promise((x,S)=>{w=()=>{S(new n3)},m.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&m!=null&&m?.removeEventListener("abort",w)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},s}var s3=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},c9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Vt(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(c9(i));return}if(i&&(c=()=>{f(c9(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new s3;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?f(s):(h.message=s??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var C_=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function I_(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=C_(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Vt(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Ar(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=I_(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Yn(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Vf=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Hf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Fo=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},qf=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},zf=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function __(r){return r.reason}function de(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??__;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;return Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}var Gf=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Xe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function R_(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var l9=new WeakMap,Wf=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=R_(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 jt),this.cleanup())}async join(e){let t=new Gf(e);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 de(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=l9.get(t);if(n==null&&(n=new WeakSet,l9.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new jt),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var tr=class extends ue{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Yn(this.emitEmpty.bind(this),1),this.emitIdle=Yn(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Hf;let n=new Wf(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new jt)}),this.clear()}async onEmpty(e){this.size!==0&&await Ar(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ar(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ar(this,"idle",e)}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=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var P_=Math.pow(2,20)*4,pn=class extends ue{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??P_,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new j,this.writeBuffer=new j,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new zf)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),de(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Kt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Qr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new Ou(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new Mu(new li))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new ls))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new j(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Nu(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Js(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Js(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Is=class extends pn{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function jf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var _s=class extends ue{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await de(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Rr;let t=this.onCreateStream({...this.streamOptions,...e});return jf(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new qf(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Rs=class extends pn{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Ar(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};function ve(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var Ji=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var L_=1.2,k_=2,D_=5e3,N_=6e4,O_=5e3,Vr=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??O_;this.success=new Ji(t),this.failure=new Ji(t),this.next=new Ji(t),this.failureMultiplier=e.failureMultiplier??k_,this.timeoutMultiplier=e.timeoutMultiplier??L_,this.minTimeout=e.minTimeout??D_,this.maxTimeout=e.maxTimeout??N_,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=ve([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var o3=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Xe(),this.haveNext=Xe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Xe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),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 this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Xe(),await de(this.readNext.promise,t?.signal,t)}};function u9(){return new o3}function d9(r){return r[Symbol.asyncIterator]!=null}async function M_(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:s,done:o}=await n.next();if(o===!0)break;await e.push(s,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*B_(r){let e=new AbortController,t=u9(),n=r.map(s=>d9(s)?s[Symbol.asyncIterator]():s[Symbol.iterator]());M_(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let s of n)try{Promise.resolve(s.return?.()).catch(()=>{})}catch{}}}function*U_(r){for(let e of r)yield*e}function F_(...r){let e=[];for(let t of r)d9(t)||e.push(t);return e.length===r.length?U_(e):B_(r)}var Xn=F_;function sl(r,...e){if(r==null)throw new Error("Empty pipeline");if(i3(r)){let n=r;r=()=>n.source}else if(h9(r)||f9(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&i3(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)i3(t[n])&&(t[n]=K_(t[n]));return $_(...t)}var $_=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},f9=r=>r?.[Symbol.asyncIterator]!=null,h9=r=>r?.[Symbol.iterator]!=null,i3=r=>r==null?!1:r.sink!=null&&r.source!=null,K_=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(f9(o))s=async function*(){yield*o,n.end()};else if(h9(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Xn(n,s())}return r.source};var V_=4194304,Yf=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ol=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},c3=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},l3=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function H_(r){return typeof r?.closeRead=="function"}function q_(r){return typeof r?.close=="function"}function a3(r){return H_(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:q_(r)?r.status!=="open":!1}function z_(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Xf(r,e){let t=e?.maxBufferSize??V_,n=new j,s,o=!1,i;if(!z_(r))throw new v("Argument should be a Stream or a Multiaddr");let a=d=>{if(i==null){if(n.append(d.data),n.byteLength>t){let f=n.byteLength;n.consume(f);let h=new Js(`Read buffer overflow - ${f} > ${t}`);i=h,s?.reject(h),queueMicrotask(()=>{r.abort(h)});return}s?.resolve()}};r.addEventListener("message",a);let c=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};r.addEventListener("close",c);let l=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",l);let u={readBuffer:n,async read(d){if(o===!0)throw new Yf("Stream was unwrapped");if(i!=null)throw i;if(a3(r)){if(n.byteLength===0&&d?.bytes==null)return null;if(d?.bytes!=null&&n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Fo(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let f=d?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await de(s.promise,d?.signal),a3(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}let h=d?.bytes??n.byteLength;if(n.byteLength<h){if(a3(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Fo(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return u.read(d)}let p=n.sublist(0,h);return n.consume(h),p},async write(d,f){if(o===!0)throw new Yf("Stream was unwrapped");r.send(d)||await Ar(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",l),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function Hr(r,e={}){let t=Xf(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ne(e.maxDataLength));let n=e?.lengthDecoder??Or,s=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new j;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ol("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new l3(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new c3(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Fo(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Fo(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new j(s(i.byteLength),i),a)},async writeV(i,a){let c=new j(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Fe(r,e){let t=Hr(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var G_=1024*1024*4,W_=1024*1024*4,ea=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new j,this.maxBufferSize=e.maxBufferSize??G_,this.maxDataLength=e.maxDataLength??W_,this.lengthDecoder=e.lengthDecoder??Or,this.encodingLength=e.encodingLength??Ne}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new v(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new ol("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Qf=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ta=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},il=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Jf(r){return r[Symbol.asyncIterator]!=null}function p9(r,e){if(r.byteLength>e)throw new ta("Message length too long")}var th=r=>{let e=Ne(r),t=Ge(e);return Xt(r,t),th.bytes=e,t};th.bytes=0;function $o(r,e){e=e??{};let t=e.lengthEncoder??th,n=e?.maxDataLength??4194304;function*s(o){p9(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Jf(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}$o.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??th,n=e?.maxDataLength??4194304;return p9(r,n),new j(t(r.byteLength),r)};var Ko;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ko||(Ko={}));var u3=r=>{let e=Or(r);return u3.bytes=Ne(e),e};u3.bytes=0;function al(r,e){let t=new j,n=Ko.LENGTH,s=-1,o=e?.lengthDecoder??u3,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ko.LENGTH)try{if(s=o(t),s<0)throw new Qf("Invalid message length");if(s>a)throw new ta("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ko.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Zf("Message length length too long");break}throw l}if(n===Ko.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ko.LENGTH}}}return Jf(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new il("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new il("Unexpected end of input")})()}al.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return al(n,{...e??{},onLength:o=>{t=o}})};var m9=Symbol.for("sindresorhus/unlimited-timeout#brand");function g9(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,s={[m9]:!0,id:void 0,cleared:!1,ref(){return n=!1,s.id?.ref?.(),s},unref(){return n=!0,s.id?.unref?.(),s}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return s;(!Number.isFinite(e)||e<0)&&(e=0);let o=performance.now()+e,i=a=>{s.cleared||(a<=2147483647?(s.id=globalThis.setTimeout(()=>{s.cleared||r(...t)},a),n&&s.id?.unref?.()):(s.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,o-c);i(l)},2147483647),n&&s.id?.unref?.()))};return i(e),s}function y9(r){!r||typeof r!="object"||!r[m9]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var X_=new WeakMap;function Q_({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(s.reason);let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(s.reason)},u=()=>{s&&s.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),X_.set(d,()=>{c(o),o=null,i()}),d}}var Z_=Q_({setTimeout:g9,clearTimeout:y9}),b9=Z_;var rr=class extends tr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var rh=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ra=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new d3}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);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(s,i.consumedPoints,this.blockDuration)),new Vf("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,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)}},d3=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,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 na(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal},u;t?.timeout!=null&&(u=ve([s.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=Yn(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,s.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var f3=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 gt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new f3({name:e,metrics:t}):n=new Map,n}var nh=class{filter;constructor(e,t){this.filter=er(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function h3(r,e=.001){return new nh(r,e)}var p3=class extends kt{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 cl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new p3({name:e,metrics:t}):n=new kt,n}var ll;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:ne(0),payloadType:ne(0),payload:ne(0),signature:ne(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(ll||(ll={}));var sh=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var fr=class r{static createFromProtobuf=e=>{let t=ll.decode(e),n=We(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=w9(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new sh("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=ll.encode({publicKey:nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:te(this.marshal(),e.marshal())}async validate(e,t){let n=w9(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},w9=(r,e,t)=>{let n=T(r),s=Xt(n.byteLength),o=Xt(e.length),i=Xt(t.length);return new j(s,n,o,e,i,t)};var E9="libp2p-peer-record",x9=Uint8Array.from([3,1]);var ul;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=ae((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:ne(0)},g=f==null?d.len:d.pos+f;for(;d.pos<g;){let y=d.uint32();y>>>3===1?p.multiaddr=d.bytes():d.skipType(y&7)}return p},function*(d,f,h,p={}){let g=f==null?d.len:d.pos+f;for(;d.pos<g;){let y=d.uint32();y>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(y&7)}})),a);function c(d){return oe(d,i.codec())}i.encode=c;function l(d,f){return se(d,i.codec(),f)}i.decode=l;function u(d,f){return ie(d,i.codec(),f)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ae((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:ne(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new pe('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(d&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},d=a==null?i.len:i.pos+a;for(;i.pos<d;){let f=i.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new pe('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(f&7);break}}}})),t);function n(i){return oe(i,r.codec())}r.encode=n;function s(i,a){return se(i,r.codec(),a)}r.decode=s;function o(i,a){return ie(i,r.codec(),a)}r.stream=o})(ul||(ul={}));function v9(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var Ht=class r{static createFromProtobuf=e=>{let t=ul.decode(e),n=ot(_e(t.peerId)),s=(t.addresses??[]).map(i=>F(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=E9;static CODEC=x9;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=ul.encode({peerId:this.peerId.toMultihash().bytes,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||!v9(this.multiaddrs,e.multiaddrs))}};function J_(r){return r[Symbol.asyncIterator]!=null}function eR(r){if(J_(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 Vo=eR;var hr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ps(r,e,t,n){let s=new hr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){g3(t,"abort",d),g3(r,e,l),g3(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};m3(t,"abort",d),m3(r,e,l),m3(r,o,u)})}function m3(r,e,t){r!=null&&(S9(r)?r.addEventListener(e,t):r.addListener(e,t))}function g3(r,e,t){r!=null&&(S9(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function S9(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var oh=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ih=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tR(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ah=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=tR(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,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 hr),this.cleanup())}async join(e={}){let t=new ih(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 de(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function y3(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var dl=class extends ue{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=y3(this.emitEmpty.bind(this),1),this.emitIdle=y3(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new oh;let n=new ah(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Ps(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ps(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ps(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=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new hr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ch="lock:worker:request-read",lh="lock:worker:abort-read-request",uh="lock:worker:release-read",dh="lock:master:grant-read",fh="lock:master:error-read",hh="lock:worker:request-write",ph="lock:worker:abort-write-request",mh="lock:worker:release-write",gh="lock:master:grant-write",yh="lock:master:error-write",bh="lock:worker:finalize",wh="mortice",A9={singleProcess:!1};var b3=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===bh&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var T9=(r=10)=>Math.random().toString().substring(2,r+2);var Eh=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(wh)}readLock(e){return this.sendRequest(ch,lh,dh,fh,uh,e)}writeLock(e){return this.sendRequest(hh,ph,gh,yh,mh,e)}finalize(){this.channel.postMessage({type:bh,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=T9();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),f.data.type===s)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var C9=r=>{if(r=Object.assign({},A9,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(wh),n=new ue;return t.addEventListener("message",b3(n,t,"requestReadLock","abortReadLockRequest",ch,lh,fh,uh,dh)),t.addEventListener("message",b3(n,t,"requestWriteLock","abortWriteLockRequest",hh,ph,yh,mh,gh)),n}return new Eh(r.name)};var Ho=new Map,fl;function I9(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function rR(r){if(fl==null&&(fl=C9(r),!I9(fl))){let e=fl;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ho.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ho.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=Ho.get(n);s?.finalize()})}return fl}async function w3(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new hr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var _9=(r,e)=>{let t=Ho.get(r);if(t!=null)return t;let n=rR(e);if(I9(n))return t=n,Ho.set(r,t),t;let s=new dl({concurrency:1}),o;return t={async readLock(i){if(o!=null)return w3(o,i);o=new dl({concurrency:e.concurrency,autoStart:!1});let a=o,c=w3(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,w3(s,i)},finalize:()=>{Ho.delete(r)},queue:s},Ho.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var nR={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function E3(r){let e=Object.assign({},nR,r);return _9(e.name,e)}var Qn;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let g={key:"",value:ne(0)},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{g.key=f.string();break}case 2:{g.value=f.bytes();break}default:{f.skipType(m&7);break}}}return g},function*(f,h,p,g={}){let y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(m&7);break}}}})),c);function l(f){return oe(f,a.codec())}a.encode=l;function u(f,h){return se(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),pl.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let g={key:""},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{g.key=f.string();break}case 2:{g.value=pl.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(m&7);break}}}return g},function*(f,h,p,g={}){let y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*pl.codec().stream(f,f.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return oe(f,a.codec())}a.encode=l;function u(f,h){return se(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),hl.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new pe('Decode error - repeated field "addresses" had too many elements');u.addresses.push(hl.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new pe('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new Ec('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new Ec('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new pe('Streaming decode error - repeated field "addresses" had too many elements');for(let p of hl.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new pe('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new pe('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new pe('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function s(a){return oe(a,r.codec())}r.encode=s;function o(a,c){return se(a,r.codec(),c)}r.decode=o;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Qn||(Qn={}));var hl;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),o.isCertified!=null&&(i.uint32(16),i.bool(o.isCertified)),o.observed!=null&&(i.uint32(24),i.uint64Number(o.observed)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ne(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}case 2:{c.isCertified=o.bool();break}case 3:{c.observed=o.uint64Number();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:o.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:o.bool()};break}case 3:{yield{field:`${a}.observed`,value:o.uint64Number()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(hl||(hl={}));var pl;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.value!=null&&o.value!==0&&(i.uint32(8),i.uint32(o.value)),o.expiry!=null&&(i.uint32(16),i.uint64(o.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={value:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.value=o.uint32();break}case 2:{c.expiry=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:o.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(pl||(pl={}));function sR(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=We(e.publicKey,t);return ur(n)}function R9(r,e,t){let n=Qn.decode(e);return sa(r,n,t)}function sa(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:sR(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:F(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function P9(r,e){return oR(r.addresses,e.addresses)&&iR(r.protocols,e.protocols)&&aR(r.publicKey,e.publicKey)&&cR(r.peerRecordEnvelope,e.peerRecordEnvelope)&&lR(r.metadata,e.metadata)&&uR(r.tags,e.tags)}function oR(r,e){return k9(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!te(t.multiaddr,n.multiaddr)))}function iR(r,e){return k9(r,e,(t,n)=>t===n)}function aR(r,e){return L9(r,e)}function cR(r,e){return L9(r,e)}function lR(r,e){return D9(r,e,(t,n)=>te(t,n))}function uR(r,e){return D9(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function L9(r,e){return r==null&&e==null?!0:r!=null&&e!=null?te(r,e):!1}function k9(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function D9(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}var x3="/peers/";function ml(r){if(!Jr(r)||r.type==null)throw new v("Invalid PeerId");let e=r.toCID().toString();return new Lt(`${x3}${e}`)}async function N9(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=F(i.multiaddr)),!hn(i.multiaddr))throw new v("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(F(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function vh(r,e,t,n){if(e==null)throw new v("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new v("publicKey does not match peer id");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new v("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=xh(f,{validate:O9})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=xh(f,{validate:M9,map:B9})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=xh([...a.entries()],{validate:O9})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of f)g==null?h.delete(p):h.set(p,g);c=xh([...h.entries()],{validate:M9,map:B9})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=nt(s.id.publicKey):e.publicKey!=null?u=nt(e.publicKey):r.publicKey!=null&&(u=nt(r.publicKey));let d={addresses:await N9(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>te(h.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function xh(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function O9(r,e){if(typeof r!="string")throw new v("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new v("Metadata value must be a Uint8Array")}function M9(r,e){if(typeof r!="string")throw new v("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new v("Tag value must be an integer");if(e.value<0||e.value>100)throw new v("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new v("Tag ttl must be an integer");if(e.ttl<0)throw new v("Tag ttl must be between greater than 0")}}function B9(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function U9(r){let e=r.toString().split("/")[2],t=ge.parse(e,br);return xt(t)}function v3(r,e,t){let n=U9(r);return R9(n,e,t)}function dR(r,e){return{prefix:x3,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(v3(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(v3(n.key,n.value,e),v3(s.key,s.value,e)))}}var Sh=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=cl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:E3({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(ml(e),t)}async load(e,t){let n=ml(e),s=await this.datastore.get(n,t),o=Qn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Ue;return sa(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(dR(e??{},this.maxAddressAge),e)){let s=U9(t);if(s.equals(this.peerId))continue;let o=Qn.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield sa(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=ml(e),s=await this.datastore.get(n,t),o=Qn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Ue;return{peerPB:o,peer:sa(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=Qn.encode(t);return await this.datastore.put(ml(e),o,s),{peer:sa(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!P9(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var S3=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 Sh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Vo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=Jr(t)?t:Jr(t?.expectedPeer)?t.expectedPeer:void 0,o=Jr(t)||t===void 0?n:t,i=await fr.openAndCertify(e,Ht.DOMAIN,o),a=xt(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=Ht.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=fr.createFromProtobuf(l.peerRecordEnvelope),d=Ht.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!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 F9(r,e={}){return new S3(r,e)}var Ah=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function fR(r){return r[Symbol.asyncIterator]!=null}function hR(r){if(fR(r))return(async()=>{for await(let e of r);})();for(let e of r);}var mn=hR;function pR(r){return r[Symbol.asyncIterator]!=null}function mR(r,e){let t=0;if(pR(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Fi(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var qo=mR;function gR(r){return r[Symbol.asyncIterator]!=null}function yR(r,e){return gR(r)?(async function*(){yield*(await Vo(r)).sort(e)})():(function*(){yield*Vo(r).sort(e)})()}var A3=yR;function bR(r){return r[Symbol.asyncIterator]!=null}function wR(r,e){return bR(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 gl=wR;var Th=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:s}of e)await this.put(n,s,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,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await mn(this.putMany(e,n)),e=[],await mn(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 s=e.prefix;n=qo(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>qo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>A3(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=qo(n,()=>s++>=o)}return e.limit!=null&&(n=gl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=qo(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>qo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>A3(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=qo(n,()=>o++>=s)}return e.limit!=null&&(n=gl(n,e.limit)),n}};var Ch=class extends Th{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ah;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Lt(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Lt(n),t?.signal?.throwIfAborted()}};var $9=864e13;var Ih=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=gt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=ee(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=zi(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?$9-Date.now():0,lastVerified:s?$9-Date.now():void 0})})}remove(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!vt(s))continue;let o=ee(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),F(n)}confirm(e,t){let n=ee(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=ee(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var _h=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=gt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:Fr(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!vt(n))continue;let s=ee(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,F(i)):e}confirm(e,t){if(!vt(e))return!1;let n=ee(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!vt(e))return!1;let n=ee(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var ER={maxObservedAddresses:10},Rh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??ER.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(it(e)||_y(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:F(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var xR={maxObservedAddresses:10},Ph=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??xR.maxObservedAddresses}get(e,t){if(it(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!vt(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!vt(e))return e.toString();let t=ee(e);return`${t.host}-${t.port}-${t.protocol}`}};var K9=6e4,V9={maxObservedAddresses:10,addressVerificationTTL:K9*10,addressVerificationRetry:K9*5},vR=r=>r;function T3(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&Ve(t).equals(e)&&(r=r.decapsulate(F(`/p2p/${e.toString()}`))),r}var Lh=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new Rh(e,t),this.dnsMappings=new Ih(e,t),this.ipMappings=new _h(e,t),this.transportAddresses=new Ph(e,t),this.announceFilter=t.announceFilter??vR,this.observedAddressFilter=er(1024),this.addressVerificationTTL=t.addressVerificationTTL??V9.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??V9.addressVerificationRetry,this._updatePeerStoreAddresses=Yn(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===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 - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>F(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>F(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>F(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=ee(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=T3(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=T3(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=T3(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=F(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(F(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${Fr(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(F(`/ip${Fr(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!vt(e))return!1;let t=ee(e);if(t.type!=="ip4"||zi(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>jn.exactMatch(o)||Uo.exactMatch(o),o=>Bo.exactMatch(o),o=>Jy.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>ee(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!jc(l)).pop();if(a==null)continue;let c=ee(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var H9;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(H9||(H9={}));var kh=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Dh=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},oa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},yl=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Nh=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Oh=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Mh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},bl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Bh=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Uh=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Fh=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},$h=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Kh=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Ls=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},zo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Vh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Hh=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var C3=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=Ui())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Uu(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")}},SR=["metrics","connectionProtector","dns"],AR=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function q9(r={}){let e=new C3(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!AR.includes(s)){let i=e.components[s];if(i==null&&!SR.includes(s))throw new kh(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function z9(r){let e={};for(let t of Object.values(r.components))for(let n of TR(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of CR(t))if(e[n]!==!0)throw new Dh(`Service "${IR(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function TR(r){return Array.isArray(r?.[ye])?r[ye]:[]}function CR(r){return Array.isArray(r?.[ir])?r[ir]:[]}function IR(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function G9(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>jn.matches(e)?!0:it(e)),r}var _R=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function RR(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=_R(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Vt(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function wl(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=RR(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}var re=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function qh(r){if(Jr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:Ve(n),e.forEach(s=>{if(!hn(s))throw new Zr("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new v("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Ve(o);if(t?.equals(i)!==!0)throw new v("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Wy.exactMatch(n)),{peerId:t,multiaddrs:e}}var PR=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function W9(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??PR;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function El(r){let e=ee(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new v(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new v(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Do(e.host,t)}function I3(r){return!mt.exactMatch(r)}function zh(r,e,t){if(r==null||e==null)return;let n=e.filter(o=>o.status==="open").sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>I3(o)))return n}var Gh=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>El(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new kt;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(vt(c.remoteAddr)){let d=ee(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await W9(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var j9="last-dial-failure",Y9="last-dial-success";var X9=100,Wh=50;function LR(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Q9(r){return r.sort((e,t)=>o9(e.multiaddr,t.multiaddr)||i9(e.multiaddr,t.multiaddr)||a9(e.multiaddr,t.multiaddr)||LR(e,t)||s9(e.multiaddr,t.multiaddr))}var jh=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},Yh=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var R3=oi(J9(),1);function P3(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var NR=100,ia=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:s}=t??{},{size:o}=this,i={priority:n,id:s,run:e};if(o===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#r();let a=P3(this.#e,i,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((o,i)=>i>=this.#t&&o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[s]=this.#e.splice(n,1);this.enqueue(s.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,s)=>s<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>NR&&this.#t>this.#e.length/2&&this.#r(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let s=this.#e[n];s.priority===e.priority&&t.push(s.run)}return t}get size(){return this.#e.length-this.#t}#r(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var vl=class extends R3.default{#e;#t;#r=0;#h;#m=!1;#w=!1;#l;#E=0;#c;#u;#a;#i=[];#o=0;#n;#C;#s=0;#g;#d;#k=1n;#y=new Map;#x=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ia,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#l=e.interval,this.#a=e.strict,this.#n=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#d=e.autoStart===!1,this.#$()}#v(e){for(;this.#o<this.#i.length;){let n=this.#i[this.#o];if(n!==void 0&&e-n>=this.#l)this.#o++;else break}(this.#o>100&&this.#o>this.#i.length/2||this.#o===this.#i.length)&&(this.#i=this.#i.slice(this.#o),this.#o=0)}#D(e){this.#a?this.#i.push(e):this.#r++}#N(){this.#a?this.#i.length>this.#o&&this.#i.pop():this.#r>0&&this.#r--}#S(){return this.#i.length-this.#o}get#O(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#r<this.#h}get#M(){return this.#s<this.#g}#B(){this.#s--,this.#s===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#P(),this.#R()}#F(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#o],s=this.#l-(e-n);return this.#I(s),!0}return!1}if(this.#c===void 0){let t=this.#E-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#I(t),!0}return!1}#I(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#A(){this.#c&&(clearInterval(this.#c),this.#c=void 0)}#_(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#n.size===0){if(this.#A(),this.emit("empty"),this.#s===0){if(this.#_(),this.#a&&this.#o>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#d){let t=Date.now(),n=!this.#F(t);if(this.#O&&this.#M){let s=this.#n.dequeue();this.#t||(this.#D(t),this.#p()),n&&this.#R(),this.emit("active"),s(),e=!0}}return e}#R(){this.#t||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#P()},this.#l),this.#E=Date.now()+this.#l)}#P(){this.#a||(this.#c!==void 0&&(this.#r===0&&this.#s===0?this.#A():this.#E=Date.now()+this.#l),this.#r=this.#e?this.#s:0),this.#T(),this.#p()}#T(){for(;this.#b(););}get concurrency(){return this.#g}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.#g=e,this.#T()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#k++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,s)=>{let o=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#s++,this.#y.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#K(),this.#y.delete(o),f}let u=e({signal:t.signal});if(t.timeout!==void 0&&(u=Vt(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#s} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){s(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(o),queueMicrotask(()=>{this.#B()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof ia){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),s(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#x.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#x.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#d?(this.#d=!1,this.#T(),this):this}pause(){this.#d=!0}clear(){for(let e of this.#x)e();this.#n=new this.#C,this.#A(),this.#L(),this.emit("empty"),this.#s===0&&(this.#_(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#f("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#f(["next","active"],()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#f("idle")}async onPendingZero(){this.#s!==0&&await this.#f("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#f("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#f("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=s=>{this.off("error",n),t(s)};this.on("error",n)})}async#f(e,t){let n=Array.isArray(e)?e:[e];return new Promise(s=>{let o=()=>{if(!(t&&!t())){for(let i of n)this.off(i,o);s()}};for(let i of n)this.on(i,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#d}#$(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#L()}))}#K(){this.#t||(this.#N(),this.#p())}#L(){let e=this.#m;if(this.#t||this.#n.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let s=Date.now();this.#v(s),t=this.#S()}else t=this.#r;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#s===this.#g&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Qh(r){let e=[pr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var L3=60;function Zh(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:pr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:pr[e.type],TTL:e.TTL??e.ttl??L3,data:e.data instanceof Uint8Array?k(e.data):e.data}))}}var OR=4;function k3(r,e={}){let t=new vl({concurrency:e.queryConcurrency??OR});return async(n,s={})=>{let o=s?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Qh(s.types).forEach(c=>{i.append("type",pr[c])}),s.onProgress?.(new re("dns:query",n)),o?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(o?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Zh(await c.json());return s.onProgress?.(new re("dns:response",l)),l},{signal:s.signal});if(a==null)throw new Error("No DNS response received");return a}}function eb(){return[k3("https://cloudflare-dns.com/dns-query"),k3("https://dns.google/resolve")]}var nb=oi(rb(),1);var D3=class{lru;constructor(e){this.lru=(0,nb.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return Zh({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:pr[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??L3)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function sb(r){return new D3(r)}var MR=1e3,BR=()=>Math.random()>.5?-1:1,Jh=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=sb(e.cacheSize??MR),this.logger=e.logger,this.sorter=e.sorter??BR,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=eb())}async query(e,t={}){let n=Qh(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new re("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});if(l.Answer.length===0)throw new Yh("Query result had no answers");for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new re("dns:error",l))}}throw new jh(a,`DNS lookup of ${e} ${n} failed`)}};var pr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(pr||(pr={}));function ob(r={}){return new Jh(r)}var N3=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=this.getDNS(t),o;try{o=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[pr.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(u=>u.name==="EmptyDNSAnswerError"))return[];throw c}let i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(F(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=ob()),this.dns)}},Sl=new N3;async function O3(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Hh("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await O3(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var aa={maxParallelDials:Wh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Sl}},e1=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??aa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??aa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??aa.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??aa.addressDialTimeout,this.connections=t.connections??new kt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??aa.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new rh({concurrency:t.maxParallelDials??aa.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==jt.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=qh(e);if(n!=null&&t.force!==!0){let i=zh(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new re("dial-queue:already-connected",i)),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new re("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new cs("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new re("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new re("dial-queue:start-dial"));let a=ve([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??$3,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(o.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new re("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new cs("Peer had more than maxPeerAddrsToDial");a++;let p=ve([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[Y9]:T(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),o.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[j9]:T(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new as(g.message);l.push(g)}finally{p.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(d=>({multiaddr:F(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new cs("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new bl("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);s.push(...d.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:f})=>f.toString())),s.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let o=(await Promise.all(s.map(async d=>{let f=await O3(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;o=o.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let i=o.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of i){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new Fh(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?Q9(l):l.sort(this.addressSorter);if(u.length===0)throw new bl(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!mt.matches(s.multiaddr))!=null:!0}catch{}return!1}};var UR=Object.prototype.toString,FR=r=>UR.call(r)==="[object Error]",$R=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function K3(r){if(!(r&&FR(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:$R.has(t)}function KR(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function t1(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function V3(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var H3=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function VR(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function r1(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function HR(r,e){r<=0||await new Promise((t,n)=>{let s=()=>{clearTimeout(o),e.signal?.removeEventListener("abort",s),n(e.signal.reason)},o=setTimeout(()=>{e.signal?.removeEventListener("abort",s),t()},r);e.unref&&o.unref?.(),e.signal?.addEventListener("abort",s,{once:!0})})}async function qR({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof H3)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=VR(t,s);if(r1(n,a)<=0){let m=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await s.onFailedAttempt(m),o}let u=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),d=await s.shouldConsumeRetry(u),f=d&&i>0?c:0,h=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:f});if(await s.onFailedAttempt(h),r1(n,a)<=0||r1(n,a)<=0||i<=0||o instanceof TypeError&&!K3(o)||!await s.shouldRetry(h))throw o;let g=r1(n,a);if(g<=0)throw o;if(!d)return s.signal?.throwIfAborted(),!1;let y=Math.min(f,g);return s.signal?.throwIfAborted(),await HR(y,s),s.signal?.throwIfAborted(),!0}async function q3(r,e={}){if(e={...e},KR(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,V3("onFailedAttempt",e.onFailedAttempt),V3("shouldRetry",e.shouldRetry),V3("shouldConsumeRetry",e.shouldConsumeRetry),t1("factor",e.factor,{min:0,allowInfinity:!1}),t1("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),t1("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),t1("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await qR({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var n1=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new rr({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);ib(t)&&(this.queue.has(e)||this.queue.add(async n=>{await q3(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(so)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>ib(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function ib(r){for(let e of r.tags.keys())if(e.startsWith(so))return!0;return!1}var $3=50,z3={maxConnections:X9,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},s1=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??z3.maxConnections,this.maxConnections<1)throw new v("Connection Manager maxConnections must be greater than 0");this.connections=new kt,this.started=!1,this.peerId=e.peerId,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.allow=(t.allow??[]).map(n=>El(F(n))),this.deny=(t.deny??[]).map(n=>El(F(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??z3.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ra({points:t.inboundConnectionThreshold??z3.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Gh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>F(n))}),this.dialQueue=new e1(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Wh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Sl},connections:this.connections}),this.reconnectQueue=new n1({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;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 s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??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 s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kr(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await en(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([wl(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new v("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),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,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}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.started)throw new Pr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new re("connection:open",e));let{peerId:n,multiaddrs:s}=qh(e);if(this.peerId.equals(n))throw new ui("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=zh(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new re("dial-queue:already-connected")),t.onProgress?.(new re("connection:opened",c)),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??$3});if(o.status!=="open")throw new Zs("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new Zr("Duplicate multiaddr connection")),c;return a||i.push(o),t.onProgress?.(new re("connection:opened",o)),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([wl(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(vt(e.remoteAddr)){let o=ee(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(vt(e.remoteAddr)){let o=ee(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(vt(e.remoteAddr)){let s=ee(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!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=>F(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var WR=1e4,jR="1.0.0",YR="ping",XR="ipfs",ab=32,QR=!0,o1=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??XR}/${YR}/${jR}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??WR,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??QR,this.timeout=new Vr({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[ye]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s;try{s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let o=Xf(s);t=Date.now(),await Promise.all([o.write(crypto.getRandomValues(new Uint8Array(ab)),{signal:n}),o.read({bytes:ab,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(o){if(s?.abort(o),o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var i1=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:k(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:k(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");let n=this,s=new dr;for await(let o of Xn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Pr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Pr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var a1=globalThis.CustomEvent??Event;async function*Zn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=Xe(),a=Xe(),c=!1,l,u=!1,d=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let g of r){if(o.length===t&&(i=Xe(),await i.promise),u||d)break;let y={done:!1};o.push(y),g().then(m=>{y.done=!0,y.ok=!0,y.value=m,s.dispatchEvent(new a1("task-complete"))},m=>{y.done=!0,y.err=m,s.dispatchEvent(new a1("task-complete"))})}c=!0,s.dispatchEvent(new a1("task-complete"))}catch(g){l=g,s.dispatchEvent(new a1("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let g=o[0];if(o.shift(),g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}function*p(){for(;f();)for(let g=0;g<o.length;g++)if(o[g].done){let y=o[g];if(o.splice(g,1),g--,y.ok)yield y.value;else throw u=!0,i.resolve(),y.err;i.resolve()}}try{for(;;){if(f()||(a=Xe(),await a.promise),l!=null||(n?yield*h():yield*p(),l!=null))throw l;if(c&&o.length===0)break}}finally{d=!0,i.resolve()}}var c1=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??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:k(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new yl("No peer routers available");if(e.toString()===this.peerId.toString())throw new Nh("Should not try to find self");let n=this,s=Xn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new Ue}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new yl("No peer routers available");let n=this,s=er(1024);for await(let o of Zn((async function*(){let i=Xn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).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 - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var l1=class extends ue{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=ve([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Xe(),yield(await wl(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=ve([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=crypto.getRandomValues(new Uint8Array(32)),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await de(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var G3=32,W3=64,u1=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=gt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Oh(`No handler registered for protocol ${e}`);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)&&n?.force!==!0)throw new Mh(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:G3,maxOutboundStreams:W3,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new v("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.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))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};var d1=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=gt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=gt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Wa.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new v("Transport must have a valid tag");if(this.transports.has(t))throw new v(`There is already a transport with the tag ${t}`);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 s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Vh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new re("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Pr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new Bh)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Zm.matches(c)?t.ipv4.attempts++:Jm.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Zm.matches(c)&&t.ipv4.success++,Jm.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,d),t.errors.set(c.toString(),d),d}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Wa.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Uh(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
17
|
+
${e}[Error list was empty]`,t.trim()}return ly(r,e)}Jt.formatters.e=r=>r==null?"undefined":dy(r);function bI(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Ui(r){return{forComponent(e){return fy(e,r)}}}function fy(r,e){let t=bI(`${r}:trace`);return Jt.enabled(`${r}:trace`)&&Jt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Jt(`${r}:trace`,e)),Object.assign(Jt(r,e),{error:Jt(`${r}:error`,e),trace:t,newScope:n=>fy(`${r}:${n}`,e)})}function uy(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}async function ym(r,e={}){let t=e.selfKey??"self",n=bf(e)({datastore:r,logger:Ui()}),s;return await r.has(new Lt(`/pkcs8/${t}`))?s=await n.exportKey(t):(s=await vd(e.keyType??"Ed25519"),await n.importKey(t,s)),s}var hy=Symbol.for("nodejs.util.inspect.custom"),wI=114,$c=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bu]=!0;toString(){return this.string==null&&(this.string=Ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(wI,this.multihash)}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 this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[hy](){return`PeerId(${this.toString()})`}},Kc=class extends $c{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Vc=class extends $c{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Hc=class extends $c{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},EI=2336,qc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ar.digest(T(this.url))}[hy](){return`PeerId(${this.url})`}[Bu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(EI,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=k(e)),e.toString()===this.toString())}};var xI=114,py=2336;function Ve(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=_e(Ie.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return xt(ge.parse(r));if(e==null)throw new v('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=_e(e.decode(r))}return ot(t)}function ur(r){if(r.type==="Ed25519")return new Vc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Hc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Kc({multihash:r.toCID().multihash,publicKey:r});throw new Lr}function my(r){return ur(r.publicKey)}function ot(r){if(SI(r))return new Kc({multihash:r});if(vI(r))try{let e=e7(r);if(e.type==="Ed25519")return new Vc({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Hc({multihash:r,publicKey:e})}catch{let t=k(r.digest);return new qc(new URL(t))}throw new Lu("Supplied PeerID Multihash is invalid")}function xt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==xI&&r.code!==py)throw new Pu("Supplied PeerID CID is invalid");if(r.code===py){let e=k(r.multihash.digest);return new qc(new URL(e))}return ot(r.multihash)}function vI(r){return r.code===ar.code}function SI(r){return r.code===yt.code}function AI(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Fi=AI;function TI(r){return r[Symbol.asyncIterator]!=null}function gy(r){return r?.then!=null}function CI(r,e){let t=0;if(TI(r))return(async function*(){for await(let c of r){let l=e(c,t++);gy(l)&&await l,yield c}})();let n=Fi(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i?.then=="function")return(async function*(){await i,yield s;for(let c of n){let l=e(c,t++);gy(l)&&await l,yield c}})();let a=e;return(function*(){yield s;for(let c of n)a(c,t++),yield c})()}var bm=CI;async function yy(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new v("Private network is enforced, but no protector was provided");return r}function _o(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function xf(r){let e=_e(Ie.decode(`z${r}`));return ot(e)}var kt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return _o(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return _o(this.map.values(),e=>e.key)}values(){return _o(this.map.values(),e=>e.value)}get size(){return this.map.size}};var dr=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 _o(this.set.entries(),e=>{let t=xf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return _o(this.set.values(),e=>xf(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}};function wm(){return new dr}var Em={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},by={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},wy=new globalThis.TextEncoder;function II(r,e){let t=Em[e],n=by[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function _I(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Em[e],s=by[e],o=r;for(;o.length>0;){let i=wy.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function xm(r,{size:e=32,utf8Buffer:t}={}){if(!Em[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return _I(r,e,t);r=wy.encode(r)}return II(r,e)}var zc={hash:r=>Number(xm(r,{size:32})),hashV:(r,e)=>RI(zc.hash(r,e))};function RI(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var vm=64,Ur=class{fp;h;seed;constructor(e,t,n,s=2){if(s>vm)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ne(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function Ro(r,e){return Math.floor(Math.random()*(e-r))+r}var Po=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");let t=Ro(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ur))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var PI=500,Gc=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??zc,this.seed=e.seed??Ro(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Po(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Po(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Ro(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Po(this.bucketSize));for(let a=0;a<PI;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Po(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new Ur(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},LI={1:.5,2:.84,4:.95,8:.98};function kI(r=.001){return r>.002?2:r>1e-5?4:8}function Ey(r,e=.001){let t=kI(e),n=LI[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),vm);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var vf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??zc,this.seed=e.seed??Ro(0,Math.pow(2,10)),this.filterSeries=[new Gc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Gc({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function er(r,e=.001,t){return new vf({...Ey(r,e),...t??{}})}function Sm(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function ee(r){let e=Sm(r);if(e==null)throw new v(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Sf=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var xy=45,DI=15,$i=new Sf;function Af(r){if(!(r.length>DI))return $i.new(r).parseWith(()=>$i.readIPv4Addr())}function Tf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>xy))return $i.new(r).parseWith(()=>$i.readIPv6Addr())}function Ki(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>xy)return;let t=$i.new(r).parseWith(()=>$i.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function vy(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Sy(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Am(r){switch(r.length){case Lo:return r.join(".");case ko:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Ay(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Ty(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Lo=4,ko=16,nH=parseInt("0xFFFF",16),NI=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Wc(r,e){e.length===ko&&r.length===Lo&&vy(e,0,11)&&(e=e.slice(12)),e.length===Lo&&r.length===ko&&Sy(r,NI,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Cy(r,e){if(typeof e=="string"&&(e=Ki(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Tm(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Lo,s=Af(e);if(s==null&&(n=ko,s=Tf(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Cm(o,8*n);return{network:Wc(s,i),mask:i}}function Cm(r,e){if(e!==8*Lo&&e!==8*ko)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var Do=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Tm(e));else{let n=Ki(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=Ki(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=Cm(s,8*n.length);this.network=Wc(n,this.mask)}}contains(e){return Cy({network:this.network,mask:this.mask},e)}toString(){let e=Ay(this.mask),t=e!==-1?String(e):Ty(this.mask);return Am(this.network)+"/"+t}};function Iy(r,e){return new Do(r).contains(e)}function Cf(r){try{let e=ee(r);return e.type==="ip6"?Iy("2000::/3",e.host):!1}catch{return!1}}function _y(r){try{let e=ee(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Ry(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let s=n.split(".");return s.length===4&&s[0]==="127"&&s.every(o=>/^\d{1,3}$/.test(o))}function jc(r){try{let e=ee(r);switch(e.type){case"ip4":case"ip6":return Ry(e.host);default:return!1}}catch{return!1}}function vt(r){return Sm(r)!==null}function Fr(r){return!!Af(r)}function If(r){return!!Tf(r)}var Dy=oi(ky(),1),KI=["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"],VI=KI.map(r=>new Dy.Netmask(r));function Dm(r){for(let e of VI)if(e.contains(r))return!0;return!1}function HI(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function qI(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Dm(s)}function zI(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function GI(r){let e=r.split(":"),t=e[e.length-1];return Dm(t)}function WI(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function zi(r){if(Fr(r))return Dm(r);if(HI(r))return qI(r);if(zI(r))return GI(r);if(If(r))return WI(r)}function it(r){try{let e=ee(r);switch(e.type){case"ip4":case"ip6":return zi(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function qn(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Sr(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=Ge(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return $u(t)}var St=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},zn=class extends Error{static name="ValidationError";name="ValidationError"},Rf=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Pf=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Om(r){return e=>k(e,r)}function Mm(r){return e=>T(e,r)}function Gi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Oo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}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!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oo(n);return et([t,s],t.length+s.length)}function Oy(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=br.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 s=Oo(n);return et([t,s],t.length+s.length)}function Bm(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=k(e,"base32"),s=Gi(t);return`${n}:${s}`}var Um=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new St("Invalid byte value in IP address");e[n]=s}),e},My=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Fr(t[n]),i;o&&(i=Um(t[n]),t[n]=k(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,k(i.subarray(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 o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new St("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},By=function(r){if(r.byteLength!==4)throw new St("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Uy=function(r){if(r.byteLength!==16)throw new St("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${t}"`)}};function Fy(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${r}"`)}}var Nm=Object.values(co).map(r=>r.decoder),jI=(function(){let r=Nm[0].or(Nm[1]);return Nm.slice(2).forEach(e=>r=r.or(e)),r})();function $y(r){return jI.decode(r)}function Ky(r){return e=>r.encoder.encode(e)}function YI(r){if(parseInt(r).toString()!==r)throw new zn("Value must be an integer")}function XI(r){if(r<0)throw new zn("Value must be a positive integer, or zero")}function QI(r){return e=>{if(e>r)throw new zn(`Value must be smaller than or equal to ${r}`)}}function ZI(...r){return e=>{for(let t of r)t(e)}}var Yc=ZI(YI,XI,QI(65535));var pt=-1,Fm=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Pf(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Wn=new Fm,f_=[{code:4,name:"ip4",size:32,valueToBytes:Um,bytesToValue:By,validate:r=>{if(!Fr(r))throw new zn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:273,name:"udp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:33,name:"dccp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:41,name:"ip6",size:128,valueToBytes:My,bytesToValue:Uy,stringToValue:Fy,validate:r=>{if(!If(r))throw new zn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pt},{code:43,name:"ipcidr",size:8,bytesToValue:Om("base10"),valueToBytes:Mm("base10")},{code:53,name:"dns",size:pt},{code:54,name:"dns4",size:pt},{code:55,name:"dns6",size:pt},{code:56,name:"dnsaddr",size:pt},{code:132,name:"sctp",size:16,valueToBytes:Oo,bytesToValue:Gi,validate:Yc},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pt,bytesToValue:Om("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Mm("base58btc")(r):ge.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bm,valueToBytes:Ny},{code:445,name:"onion3",size:296,bytesToValue:Bm,valueToBytes:Oy},{code:446,name:"garlic64",size:pt},{code:447,name:"garlic32",size:pt},{code:448,name:"tls"},{code:449,name:"sni",size:pt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pt,bytesToValue:Ky(Za),valueToBytes:$y},{code:480,name:"http"},{code:481,name:"http-path",size:pt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pt}];f_.forEach(r=>{Wn.addProtocol(r)});function Vy(r){let e=[],t=0;for(;t<r.length;){let n=Or(r,t),s=Wn.getProtocol(n),o=Ne(n),i=h_(s,r,t+o),a=0;i>0&&s.size===pt&&(a=Ne(i));let c=o+a+i,l={code:n,name:s.name,bytes:he(r.subarray(t,t+c))};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??k(d)}e.push(l),t+=c}return e}function Hy(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Wn.getProtocol(n.code),o=Ne(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,s.size===pt&&(c=Ne(a)));let l=new Uint8Array(o+c+a),u=0;Li(n.code,l,u),u+=o,i!=null&&(s.size===pt&&(Li(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return et(t,e)}function qy(r){if(r.charAt(0)!=="/")throw new St('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Wn.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new St(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new St(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new St("Incomplete multiaddr");return e}function zy(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Wn.getProtocol(e.code);if(t==null)throw new St(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function h_(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Or(e,t)}var p_=Symbol.for("nodejs.util.inspect.custom"),jm=Symbol.for("@multiformats/multiaddr");function m_(r){if(r==null&&(r="/"),hn(r))return r.getComponents();if(r instanceof Uint8Array)return Vy(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qy(r);if(Array.isArray(r))return r;throw new St("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Of=class r{[jm]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=m_(e),t.validate!==!1&&g_(this)}get bytes(){return this.#r==null&&(this.#r=Hy(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=zy(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Rf(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return te(this.bytes,e.bytes)}[p_](){return`Multiaddr(${this.toString()})`}};function g_(r){r.getComponents().forEach(e=>{let t=Wn.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function hn(r){return!!r?.[jm]}function F(r){return new Of(r)}var Le=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),J=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Gy=r=>({match:e=>r.match(e)===!1?e:!1}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Dt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),xe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ke(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var y_=J(421),Wy=ke(y_),Bf=J(54),Uf=J(55),Ff=J(56),Xm=J(53),qq=ke(Bf,be(J(421))),zq=ke(Uf,be(J(421))),Gq=ke(Ff,be(J(421))),jy=ke(Dt(Xm,Ff,Bf,Uf),be(J(421))),Yy=xe(J(4),be(J(43))),Xy=xe(be(J(42)),J(41),be(J(43))),Qm=Dt(Yy,Xy),Xi=Dt(Qm,Xm,Bf,Uf,Ff),Qy=ke(Dt(Qm,xe(Dt(Xm,Ff,Bf,Uf),be(J(421))))),Zm=ke(Yy),Jm=ke(Xy),Zy=ke(Qm),e3=xe(Xi,J(6)),tl=xe(Xi,J(273)),Bo=ke(xe(e3,be(J(421)))),Wq=ke(tl),t3=xe(tl,Le(460),be(J(421))),$f=xe(tl,Le(461),be(J(421))),b_=Dt(t3,$f),jq=ke(t3),Jy=ke($f),Ym=Dt(Xi,e3,tl,t3,$f),e9=Dt(xe(Ym,Le(477),be(J(421)))),jn=ke(e9),t9=Dt(xe(Ym,Le(478),be(J(421))),xe(Ym,Le(448),be(J(449)),Le(477),be(J(421)))),Uo=ke(t9),r9=xe(tl,Le(280),be(J(466)),be(J(466)),be(J(421))),rl=ke(r9),n9=xe($f,Le(465),be(J(466)),be(J(466)),be(J(421))),r3=ke(n9),Mf=Dt(e9,t9,xe(e3,be(J(421))),xe(b_,be(J(421))),xe(Xi,be(J(421))),r9,n9,J(421)),Qi=ke(Mf),w_=xe(be(Mf),Le(290),Gy(Le(281)),be(J(421))),mt=ke(w_),E_=Dt(xe(Mf,Le(290),Le(281),be(J(421))),xe(Mf,Le(281),be(J(421))),xe(Le(281),be(J(421)))),nl=ke(E_),x_=xe(Xi,Dt(xe(J(6,"80")),xe(J(6),Le(480)),Le(480)),be(J(481)),be(J(421))),Yq=ke(x_),v_=xe(Xi,Dt(xe(J(6,"443")),xe(J(6,"443"),Le(480)),xe(J(6),Le(443)),xe(J(6),Le(448),Le(480)),xe(Le(448),Le(480)),Le(448),Le(443)),be(J(481)),be(J(421))),Xq=ke(v_),S_=Dt(xe(J(777),be(J(421)))),Qq=ke(S_),A_=Dt(xe(J(400),be(J(421)))),Zq=ke(A_);function s9(r,e){let t=Bo.exactMatch(r),n=Bo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let s=Uo.exactMatch(r),o=Uo.exactMatch(e);if(s&&!o)return-1;if(!s&&o)return 1;let i=jn.exactMatch(r),a=jn.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nl.exactMatch(r),l=nl.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=rl.exactMatch(r),d=rl.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=r3.exactMatch(r),h=r3.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function o9(r,e){let t=jc(r),n=jc(e);return t&&!n?1:!t&&n?-1:0}function i9(r,e){let t=it(r),n=it(e);return t&&!n?1:!t&&n?-1:0}function a9(r,e){let t=mt.exactMatch(r),n=mt.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Xe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Kf=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},Zi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Kf(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 Kf(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 n3=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(r={}){return T_(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 T_(r,e){e=e??{};let t=e.onEnd,n=new Zi,s,o,i,a=Xe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(w){m(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Xe()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new Zi,o!=null?o({error:y}):(n.push({error:y}),s)),d=y=>{if(i)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Zi,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,w;m!=null&&(b=new Promise((x,S)=>{w=()=>{S(new n3)},m.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&m!=null&&m?.removeEventListener("abort",w)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},s}var s3=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},c9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Vt(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(c9(i)),r.then(d,f);return}if(i&&(c=()=>{f(c9(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new s3;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?f(s):(h.message=s??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var C_=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function I_(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=C_(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Vt(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Ar(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=I_(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Yn(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Vf=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Hf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Fo=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},qf=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},zf=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function __(r){return r.reason}function de(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??__;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;return Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}var Gf=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Xe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function R_(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var l9=new WeakMap,Wf=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=R_(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 jt),this.cleanup())}async join(e){let t=new Gf(e);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 de(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=l9.get(t);if(n==null&&(n=new WeakSet,l9.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new jt),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var tr=class extends ue{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Yn(this.emitEmpty.bind(this),1),this.emitIdle=Yn(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Hf;let n=new Wf(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new jt)}),this.clear()}async onEmpty(e){this.size!==0&&await Ar(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ar(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ar(this,"idle",e)}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=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var P_=Math.pow(2,20)*4,pn=class extends ue{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??P_,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new j,this.writeBuffer=new j,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new zf)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),de(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Kt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Qr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new Ou(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Qr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new Mu(new li))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new ls))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new j(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Nu(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Js(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Js(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Is=class extends pn{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function jf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var _s=class extends ue{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await de(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Rr;let t=this.onCreateStream({...this.streamOptions,...e});return jf(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new qf(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Rs=class extends pn{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ar(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Ar(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};function ve(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var Ji=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var L_=1.2,k_=2,D_=5e3,N_=6e4,O_=5e3,Vr=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??O_;this.success=new Ji(t),this.failure=new Ji(t),this.next=new Ji(t),this.failureMultiplier=e.failureMultiplier??k_,this.timeoutMultiplier=e.timeoutMultiplier??L_,this.minTimeout=e.minTimeout??D_,this.maxTimeout=e.maxTimeout??N_,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=ve([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var o3=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Xe(),this.haveNext=Xe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Xe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),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 this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Xe(),await de(this.readNext.promise,t?.signal,t)}};function u9(){return new o3}function d9(r){return r[Symbol.asyncIterator]!=null}async function M_(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:s,done:o}=await n.next();if(o===!0)break;await e.push(s,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*B_(r){let e=new AbortController,t=u9(),n=r.map(s=>d9(s)?s[Symbol.asyncIterator]():s[Symbol.iterator]());M_(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let s of n)try{Promise.resolve(s.return?.()).catch(()=>{})}catch{}}}function*U_(r){for(let e of r)yield*e}function F_(...r){let e=[];for(let t of r)d9(t)||e.push(t);return e.length===r.length?U_(e):B_(r)}var Xn=F_;function sl(r,...e){if(r==null)throw new Error("Empty pipeline");if(i3(r)){let n=r;r=()=>n.source}else if(h9(r)||f9(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&i3(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)i3(t[n])&&(t[n]=K_(t[n]));return $_(...t)}var $_=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},f9=r=>r?.[Symbol.asyncIterator]!=null,h9=r=>r?.[Symbol.iterator]!=null,i3=r=>r==null?!1:r.sink!=null&&r.source!=null,K_=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(f9(o))s=async function*(){yield*o,n.end()};else if(h9(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Xn(n,s())}return r.source};var V_=4194304,Yf=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ol=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},c3=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},l3=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function H_(r){return typeof r?.closeRead=="function"}function q_(r){return typeof r?.close=="function"}function a3(r){return H_(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:q_(r)?r.status!=="open":!1}function z_(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Xf(r,e){let t=e?.maxBufferSize??V_,n=new j,s,o=!1,i;if(!z_(r))throw new v("Argument should be a Stream or a Multiaddr");let a=d=>{if(i==null){if(n.append(d.data),n.byteLength>t){let f=n.byteLength;n.consume(f);let h=new Js(`Read buffer overflow - ${f} > ${t}`);i=h,s?.reject(h),queueMicrotask(()=>{r.abort(h)});return}s?.resolve()}};r.addEventListener("message",a);let c=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};r.addEventListener("close",c);let l=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",l);let u={readBuffer:n,async read(d){if(o===!0)throw new Yf("Stream was unwrapped");if(i!=null)throw i;if(a3(r)){if(n.byteLength===0&&d?.bytes==null)return null;if(d?.bytes!=null&&n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Fo(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let f=d?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await de(s.promise,d?.signal),a3(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}let h=d?.bytes??n.byteLength;if(n.byteLength<h){if(a3(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Fo(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return u.read(d)}let p=n.sublist(0,h);return n.consume(h),p},async write(d,f){if(o===!0)throw new Yf("Stream was unwrapped");r.send(d)||await Ar(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",l),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function Hr(r,e={}){let t=Xf(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ne(e.maxDataLength));let n=e?.lengthDecoder??Or,s=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new j;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ol("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new l3(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new c3(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Fo(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Fo(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new j(s(i.byteLength),i),a)},async writeV(i,a){let c=new j(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Fe(r,e){let t=Hr(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var G_=1024*1024*4,W_=1024*1024*4,ea=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new j,this.maxBufferSize=e.maxBufferSize??G_,this.maxDataLength=e.maxDataLength??W_,this.lengthDecoder=e.lengthDecoder??Or,this.encodingLength=e.encodingLength??Ne}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new v(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new ol("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Qf=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ta=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},il=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Jf(r){return r[Symbol.asyncIterator]!=null}function p9(r,e){if(r.byteLength>e)throw new ta("Message length too long")}var th=r=>{let e=Ne(r),t=Ge(e);return Xt(r,t),th.bytes=e,t};th.bytes=0;function $o(r,e){e=e??{};let t=e.lengthEncoder??th,n=e?.maxDataLength??4194304;function*s(o){p9(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Jf(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}$o.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??th,n=e?.maxDataLength??4194304;return p9(r,n),new j(t(r.byteLength),r)};var Ko;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ko||(Ko={}));var u3=r=>{let e=Or(r);return u3.bytes=Ne(e),e};u3.bytes=0;function al(r,e){let t=new j,n=Ko.LENGTH,s=-1,o=e?.lengthDecoder??u3,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ko.LENGTH)try{if(s=o(t),s<0)throw new Qf("Invalid message length");if(s>a)throw new ta("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ko.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Zf("Message length length too long");break}throw l}if(n===Ko.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ko.LENGTH}}}return Jf(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new il("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new il("Unexpected end of input")})()}al.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return al(n,{...e??{},onLength:o=>{t=o}})};var m9=Symbol.for("sindresorhus/unlimited-timeout#brand");function g9(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,s={[m9]:!0,id:void 0,cleared:!1,ref(){return n=!1,s.id?.ref?.(),s},unref(){return n=!0,s.id?.unref?.(),s}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return s;(!Number.isFinite(e)||e<0)&&(e=0);let o=performance.now()+e,i=a=>{s.cleared||(a<=2147483647?(s.id=globalThis.setTimeout(()=>{s.cleared||r(...t)},a),n&&s.id?.unref?.()):(s.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,o-c);i(l)},2147483647),n&&s.id?.unref?.()))};return i(e),s}function y9(r){!r||typeof r!="object"||!r[m9]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var X_=new WeakMap;function Q_({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(s.reason);let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(s.reason)},u=()=>{s&&s.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),X_.set(d,()=>{c(o),o=null,i()}),d}}var Z_=Q_({setTimeout:g9,clearTimeout:y9}),b9=Z_;var rr=class extends tr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var rh=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ra=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new d3}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);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(s,i.consumedPoints,this.blockDuration)),new Vf("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,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)}},d3=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,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 na(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal},u;t?.timeout!=null&&(u=ve([s.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=Yn(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,s.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var f3=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 gt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new f3({name:e,metrics:t}):n=new Map,n}var nh=class{filter;constructor(e,t){this.filter=er(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function h3(r,e=.001){return new nh(r,e)}var p3=class extends kt{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 cl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new p3({name:e,metrics:t}):n=new kt,n}var ll;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:ne(0),payloadType:ne(0),payload:ne(0),signature:ne(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(ll||(ll={}));var sh=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var fr=class r{static createFromProtobuf=e=>{let t=ll.decode(e),n=We(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=w9(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new sh("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=ll.encode({publicKey:nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:te(this.marshal(),e.marshal())}async validate(e,t){let n=w9(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},w9=(r,e,t)=>{let n=T(r),s=Xt(n.byteLength),o=Xt(e.length),i=Xt(t.length);return new j(s,n,o,e,i,t)};var E9="libp2p-peer-record",x9=Uint8Array.from([3,1]);var ul;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=ae((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:ne(0)},g=f==null?d.len:d.pos+f;for(;d.pos<g;){let y=d.uint32();y>>>3===1?p.multiaddr=d.bytes():d.skipType(y&7)}return p},function*(d,f,h,p={}){let g=f==null?d.len:d.pos+f;for(;d.pos<g;){let y=d.uint32();y>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(y&7)}})),a);function c(d){return oe(d,i.codec())}i.encode=c;function l(d,f){return se(d,i.codec(),f)}i.decode=l;function u(d,f){return ie(d,i.codec(),f)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ae((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:ne(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new pe('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(d&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},d=a==null?i.len:i.pos+a;for(;i.pos<d;){let f=i.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new pe('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(f&7);break}}}})),t);function n(i){return oe(i,r.codec())}r.encode=n;function s(i,a){return se(i,r.codec(),a)}r.decode=s;function o(i,a){return ie(i,r.codec(),a)}r.stream=o})(ul||(ul={}));function v9(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var Ht=class r{static createFromProtobuf=e=>{let t=ul.decode(e),n=ot(_e(t.peerId)),s=(t.addresses??[]).map(i=>F(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=E9;static CODEC=x9;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=ul.encode({peerId:this.peerId.toMultihash().bytes,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||!v9(this.multiaddrs,e.multiaddrs))}};function J_(r){return r[Symbol.asyncIterator]!=null}function eR(r){if(J_(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 Vo=eR;var hr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ps(r,e,t,n){let s=new hr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){g3(t,"abort",d),g3(r,e,l),g3(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};m3(t,"abort",d),m3(r,e,l),m3(r,o,u)})}function m3(r,e,t){r!=null&&(S9(r)?r.addEventListener(e,t):r.addListener(e,t))}function g3(r,e,t){r!=null&&(S9(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function S9(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var oh=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ih=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tR(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ah=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=tR(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,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 hr),this.cleanup())}async join(e={}){let t=new ih(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 de(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function y3(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var dl=class extends ue{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=y3(this.emitEmpty.bind(this),1),this.emitIdle=y3(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new oh;let n=new ah(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Ps(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ps(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ps(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=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new hr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ch="lock:worker:request-read",lh="lock:worker:abort-read-request",uh="lock:worker:release-read",dh="lock:master:grant-read",fh="lock:master:error-read",hh="lock:worker:request-write",ph="lock:worker:abort-write-request",mh="lock:worker:release-write",gh="lock:master:grant-write",yh="lock:master:error-write",bh="lock:worker:finalize",wh="mortice",A9={singleProcess:!1};var b3=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===bh&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var T9=(r=10)=>Math.random().toString().substring(2,r+2);var Eh=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(wh)}readLock(e){return this.sendRequest(ch,lh,dh,fh,uh,e)}writeLock(e){return this.sendRequest(hh,ph,gh,yh,mh,e)}finalize(){this.channel.postMessage({type:bh,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=T9();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),f.data.type===s)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var C9=r=>{if(r=Object.assign({},A9,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(wh),n=new ue;return t.addEventListener("message",b3(n,t,"requestReadLock","abortReadLockRequest",ch,lh,fh,uh,dh)),t.addEventListener("message",b3(n,t,"requestWriteLock","abortWriteLockRequest",hh,ph,yh,mh,gh)),n}return new Eh(r.name)};var Ho=new Map,fl;function I9(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function rR(r){if(fl==null&&(fl=C9(r),!I9(fl))){let e=fl;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ho.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ho.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=Ho.get(n);s?.finalize()})}return fl}async function w3(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new hr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var _9=(r,e)=>{let t=Ho.get(r);if(t!=null)return t;let n=rR(e);if(I9(n))return t=n,Ho.set(r,t),t;let s=new dl({concurrency:1}),o;return t={async readLock(i){if(o!=null)return w3(o,i);o=new dl({concurrency:e.concurrency,autoStart:!1});let a=o,c=w3(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,w3(s,i)},finalize:()=>{Ho.delete(r)},queue:s},Ho.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var nR={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function E3(r){let e=Object.assign({},nR,r);return _9(e.name,e)}var Qn;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let g={key:"",value:ne(0)},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{g.key=f.string();break}case 2:{g.value=f.bytes();break}default:{f.skipType(m&7);break}}}return g},function*(f,h,p,g={}){let y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(m&7);break}}}})),c);function l(f){return oe(f,a.codec())}a.encode=l;function u(f,h){return se(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),pl.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let g={key:""},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{g.key=f.string();break}case 2:{g.value=pl.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(m&7);break}}}return g},function*(f,h,p,g={}){let y=h==null?f.len:f.pos+h;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*pl.codec().stream(f,f.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return oe(f,a.codec())}a.encode=l;function u(f,h){return se(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),hl.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new pe('Decode error - repeated field "addresses" had too many elements');u.addresses.push(hl.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new pe('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new Ec('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new Ec('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new pe('Streaming decode error - repeated field "addresses" had too many elements');for(let p of hl.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new pe('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new pe('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new pe('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function s(a){return oe(a,r.codec())}r.encode=s;function o(a,c){return se(a,r.codec(),c)}r.decode=o;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Qn||(Qn={}));var hl;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),o.isCertified!=null&&(i.uint32(16),i.bool(o.isCertified)),o.observed!=null&&(i.uint32(24),i.uint64Number(o.observed)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ne(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}case 2:{c.isCertified=o.bool();break}case 3:{c.observed=o.uint64Number();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:o.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:o.bool()};break}case 3:{yield{field:`${a}.observed`,value:o.uint64Number()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(hl||(hl={}));var pl;(function(r){let e;r.codec=()=>(e==null&&(e=ae((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.value!=null&&o.value!==0&&(i.uint32(8),i.uint32(o.value)),o.expiry!=null&&(i.uint32(16),i.uint64(o.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={value:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.value=o.uint32();break}case 2:{c.expiry=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:o.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return oe(o,r.codec())}r.encode=t;function n(o,i){return se(o,r.codec(),i)}r.decode=n;function s(o,i){return ie(o,r.codec(),i)}r.stream=s})(pl||(pl={}));function sR(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=We(e.publicKey,t);return ur(n)}function R9(r,e,t){let n=Qn.decode(e);return sa(r,n,t)}function sa(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:sR(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:F(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function P9(r,e){return oR(r.addresses,e.addresses)&&iR(r.protocols,e.protocols)&&aR(r.publicKey,e.publicKey)&&cR(r.peerRecordEnvelope,e.peerRecordEnvelope)&&lR(r.metadata,e.metadata)&&uR(r.tags,e.tags)}function oR(r,e){return k9(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!te(t.multiaddr,n.multiaddr)))}function iR(r,e){return k9(r,e,(t,n)=>t===n)}function aR(r,e){return L9(r,e)}function cR(r,e){return L9(r,e)}function lR(r,e){return D9(r,e,(t,n)=>te(t,n))}function uR(r,e){return D9(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function L9(r,e){return r==null&&e==null?!0:r!=null&&e!=null?te(r,e):!1}function k9(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function D9(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}var x3="/peers/";function ml(r){if(!Jr(r)||r.type==null)throw new v("Invalid PeerId");let e=r.toCID().toString();return new Lt(`${x3}${e}`)}async function N9(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=F(i.multiaddr)),!hn(i.multiaddr))throw new v("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(F(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function vh(r,e,t,n){if(e==null)throw new v("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new v("publicKey does not match peer id");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new v("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=xh(f,{validate:O9})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=xh(f,{validate:M9,map:B9})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=xh([...a.entries()],{validate:O9})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of f)g==null?h.delete(p):h.set(p,g);c=xh([...h.entries()],{validate:M9,map:B9})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=nt(s.id.publicKey):e.publicKey!=null?u=nt(e.publicKey):r.publicKey!=null&&(u=nt(r.publicKey));let d={addresses:await N9(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>te(h.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function xh(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function O9(r,e){if(typeof r!="string")throw new v("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new v("Metadata value must be a Uint8Array")}function M9(r,e){if(typeof r!="string")throw new v("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new v("Tag value must be an integer");if(e.value<0||e.value>100)throw new v("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new v("Tag ttl must be an integer");if(e.ttl<0)throw new v("Tag ttl must be between greater than 0")}}function B9(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function U9(r){let e=r.toString().split("/")[2],t=ge.parse(e,br);return xt(t)}function v3(r,e,t){let n=U9(r);return R9(n,e,t)}function dR(r,e){return{prefix:x3,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(v3(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(v3(n.key,n.value,e),v3(s.key,s.value,e)))}}var Sh=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=cl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:E3({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(ml(e),t)}async load(e,t){let n=ml(e),s=await this.datastore.get(n,t),o=Qn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Ue;return sa(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await vh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(dR(e??{},this.maxAddressAge),e)){let s=U9(t);if(s.equals(this.peerId))continue;let o=Qn.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield sa(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=ml(e),s=await this.datastore.get(n,t),o=Qn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Ue;return{peerPB:o,peer:sa(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=Qn.encode(t);return await this.datastore.put(ml(e),o,s),{peer:sa(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!P9(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var S3=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 Sh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Vo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=Jr(t)?t:Jr(t?.expectedPeer)?t.expectedPeer:void 0,o=Jr(t)||t===void 0?n:t,i=await fr.openAndCertify(e,Ht.DOMAIN,o),a=xt(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=Ht.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=fr.createFromProtobuf(l.peerRecordEnvelope),d=Ht.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!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 F9(r,e={}){return new S3(r,e)}var Ah=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function fR(r){return r[Symbol.asyncIterator]!=null}function hR(r){if(fR(r))return(async()=>{for await(let e of r);})();for(let e of r);}var mn=hR;function pR(r){return r[Symbol.asyncIterator]!=null}function mR(r,e){let t=0;if(pR(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Fi(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var qo=mR;function gR(r){return r[Symbol.asyncIterator]!=null}function yR(r,e){return gR(r)?(async function*(){yield*(await Vo(r)).sort(e)})():(function*(){yield*Vo(r).sort(e)})()}var A3=yR;function bR(r){return r[Symbol.asyncIterator]!=null}function wR(r,e){return bR(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 gl=wR;var Th=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:s}of e)await this.put(n,s,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,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await mn(this.putMany(e,n)),e=[],await mn(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 s=e.prefix;n=qo(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>qo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>A3(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=qo(n,()=>s++>=o)}return e.limit!=null&&(n=gl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=qo(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>qo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>A3(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=qo(n,()=>o++>=s)}return e.limit!=null&&(n=gl(n,e.limit)),n}};var Ch=class extends Th{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ah;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Lt(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Lt(n),t?.signal?.throwIfAborted()}};var $9=864e13;var Ih=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=gt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=ee(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=zi(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?$9-Date.now():0,lastVerified:s?$9-Date.now():void 0})})}remove(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!vt(s))continue;let o=ee(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),F(n)}confirm(e,t){let n=ee(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=ee(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var _h=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=gt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:Fr(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=ee(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!vt(n))continue;let s=ee(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,F(i)):e}confirm(e,t){if(!vt(e))return!1;let n=ee(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!vt(e))return!1;let n=ee(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var ER={maxObservedAddresses:10},Rh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??ER.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(it(e)||_y(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:F(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var xR={maxObservedAddresses:10},Ph=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??xR.maxObservedAddresses}get(e,t){if(it(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!vt(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!vt(e))return e.toString();let t=ee(e);return`${t.host}-${t.port}-${t.protocol}`}};var K9=6e4,V9={maxObservedAddresses:10,addressVerificationTTL:K9*10,addressVerificationRetry:K9*5},vR=r=>r;function T3(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&Ve(t).equals(e)&&(r=r.decapsulate(F(`/p2p/${e.toString()}`))),r}var Lh=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new Rh(e,t),this.dnsMappings=new Ih(e,t),this.ipMappings=new _h(e,t),this.transportAddresses=new Ph(e,t),this.announceFilter=t.announceFilter??vR,this.observedAddressFilter=er(1024),this.addressVerificationTTL=t.addressVerificationTTL??V9.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??V9.addressVerificationRetry,this._updatePeerStoreAddresses=Yn(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===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 - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>F(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>F(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>F(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=ee(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=T3(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=T3(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=T3(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=F(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(F(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${Fr(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(F(`/ip${Fr(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!vt(e))return!1;let t=ee(e);if(t.type!=="ip4"||zi(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>jn.exactMatch(o)||Uo.exactMatch(o),o=>Bo.exactMatch(o),o=>Jy.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>ee(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!jc(l)).pop();if(a==null)continue;let c=ee(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var H9;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(H9||(H9={}));var kh=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Dh=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},oa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},yl=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Nh=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Oh=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Mh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},bl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Bh=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Uh=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Fh=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},$h=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Kh=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Ls=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},zo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Vh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Hh=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var C3=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=Ui())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Uu(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")}},SR=["metrics","connectionProtector","dns"],AR=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function q9(r={}){let e=new C3(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!AR.includes(s)){let i=e.components[s];if(i==null&&!SR.includes(s))throw new kh(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function z9(r){let e={};for(let t of Object.values(r.components))for(let n of TR(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of CR(t))if(e[n]!==!0)throw new Dh(`Service "${IR(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function TR(r){return Array.isArray(r?.[ye])?r[ye]:[]}function CR(r){return Array.isArray(r?.[ir])?r[ir]:[]}function IR(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function G9(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>jn.matches(e)?!0:it(e)),r}var _R=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function RR(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=_R(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Vt(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function wl(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=RR(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}var re=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function qh(r){if(Jr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:Ve(n),e.forEach(s=>{if(!hn(s))throw new Zr("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new v("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Ve(o);if(t?.equals(i)!==!0)throw new v("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Wy.exactMatch(n)),{peerId:t,multiaddrs:e}}var PR=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function W9(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??PR;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function El(r){let e=ee(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new v(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new v(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Do(e.host,t)}function I3(r){return!mt.exactMatch(r)}function zh(r,e,t){if(r==null||e==null)return;let n=e.filter(o=>o.status==="open").sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>I3(o)))return n}var Gh=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>El(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new kt;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(vt(c.remoteAddr)){let d=ee(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await W9(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var j9="last-dial-failure",Y9="last-dial-success";var X9=100,Wh=50;function LR(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Q9(r){return r.sort((e,t)=>o9(e.multiaddr,t.multiaddr)||i9(e.multiaddr,t.multiaddr)||a9(e.multiaddr,t.multiaddr)||LR(e,t)||s9(e.multiaddr,t.multiaddr))}var jh=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},Yh=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var R3=oi(J9(),1);function P3(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var NR=100,ia=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:s}=t??{},{size:o}=this,i={priority:n,id:s,run:e};if(o===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#r();let a=P3(this.#e,i,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((o,i)=>i>=this.#t&&o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[s]=this.#e.splice(n,1);this.enqueue(s.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,s)=>s<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>NR&&this.#t>this.#e.length/2&&this.#r(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let s=this.#e[n];s.priority===e.priority&&t.push(s.run)}return t}get size(){return this.#e.length-this.#t}#r(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var vl=class extends R3.default{#e;#t;#r=0;#h;#m=!1;#w=!1;#l;#E=0;#c;#u;#a;#i=[];#o=0;#n;#C;#s=0;#g;#d;#k=1n;#y=new Map;#x=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ia,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#l=e.interval,this.#a=e.strict,this.#n=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#d=e.autoStart===!1,this.#$()}#v(e){for(;this.#o<this.#i.length;){let n=this.#i[this.#o];if(n!==void 0&&e-n>=this.#l)this.#o++;else break}(this.#o>100&&this.#o>this.#i.length/2||this.#o===this.#i.length)&&(this.#i=this.#i.slice(this.#o),this.#o=0)}#D(e){this.#a?this.#i.push(e):this.#r++}#N(){this.#a?this.#i.length>this.#o&&this.#i.pop():this.#r>0&&this.#r--}#S(){return this.#i.length-this.#o}get#O(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#r<this.#h}get#M(){return this.#s<this.#g}#B(){this.#s--,this.#s===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#P(),this.#R()}#F(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#o],s=this.#l-(e-n);return this.#I(s),!0}return!1}if(this.#c===void 0){let t=this.#E-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#I(t),!0}return!1}#I(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#A(){this.#c&&(clearInterval(this.#c),this.#c=void 0)}#_(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#n.size===0){if(this.#A(),this.emit("empty"),this.#s===0){if(this.#_(),this.#a&&this.#o>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#d){let t=Date.now(),n=!this.#F(t);if(this.#O&&this.#M){let s=this.#n.dequeue();this.#t||(this.#D(t),this.#p()),n&&this.#R(),this.emit("active"),s(),e=!0}}return e}#R(){this.#t||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#P()},this.#l),this.#E=Date.now()+this.#l)}#P(){this.#a||(this.#c!==void 0&&(this.#r===0&&this.#s===0?this.#A():this.#E=Date.now()+this.#l),this.#r=this.#e?this.#s:0),this.#T(),this.#p()}#T(){for(;this.#b(););}get concurrency(){return this.#g}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.#g=e,this.#T()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#k++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,s)=>{let o=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#s++,this.#y.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#K(),this.#y.delete(o),f}let u=e({signal:t.signal});if(t.timeout!==void 0&&(u=Vt(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#s} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){s(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(o),queueMicrotask(()=>{this.#B()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof ia){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),s(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#x.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#x.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#d?(this.#d=!1,this.#T(),this):this}pause(){this.#d=!0}clear(){for(let e of this.#x)e();this.#n=new this.#C,this.#A(),this.#L(),this.emit("empty"),this.#s===0&&(this.#_(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#f("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#f(["next","active"],()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#f("idle")}async onPendingZero(){this.#s!==0&&await this.#f("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#f("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#f("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=s=>{this.off("error",n),t(s)};this.on("error",n)})}async#f(e,t){let n=Array.isArray(e)?e:[e];return new Promise(s=>{let o=()=>{if(!(t&&!t())){for(let i of n)this.off(i,o);s()}};for(let i of n)this.on(i,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#d}#$(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#L()}))}#K(){this.#t||(this.#N(),this.#p())}#L(){let e=this.#m;if(this.#t||this.#n.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let s=Date.now();this.#v(s),t=this.#S()}else t=this.#r;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#s===this.#g&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Qh(r){let e=[pr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var L3=60;function Zh(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:pr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:pr[e.type],TTL:e.TTL??e.ttl??L3,data:e.data instanceof Uint8Array?k(e.data):e.data}))}}var OR=4;function k3(r,e={}){let t=new vl({concurrency:e.queryConcurrency??OR});return async(n,s={})=>{let o=s?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Qh(s.types).forEach(c=>{i.append("type",pr[c])}),s.onProgress?.(new re("dns:query",n)),o?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(o?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Zh(await c.json());return s.onProgress?.(new re("dns:response",l)),l},{signal:s.signal});if(a==null)throw new Error("No DNS response received");return a}}function eb(){return[k3("https://cloudflare-dns.com/dns-query"),k3("https://dns.google/resolve")]}var nb=oi(rb(),1);var D3=class{lru;constructor(e){this.lru=(0,nb.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return Zh({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:pr[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??L3)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function sb(r){return new D3(r)}var MR=1e3,BR=()=>Math.random()>.5?-1:1,Jh=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=sb(e.cacheSize??MR),this.logger=e.logger,this.sorter=e.sorter??BR,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=eb())}async query(e,t={}){let n=Qh(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new re("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});if(l.Answer.length===0)throw new Yh("Query result had no answers");for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new re("dns:error",l))}}throw new jh(a,`DNS lookup of ${e} ${n} failed`)}};var pr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(pr||(pr={}));function ob(r={}){return new Jh(r)}var N3=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=this.getDNS(t),o;try{o=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[pr.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(u=>u.name==="EmptyDNSAnswerError"))return[];throw c}let i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(F(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=ob()),this.dns)}},Sl=new N3;async function O3(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Hh("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await O3(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var aa={maxParallelDials:Wh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Sl}},e1=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??aa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??aa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??aa.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??aa.addressDialTimeout,this.connections=t.connections??new kt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??aa.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new rh({concurrency:t.maxParallelDials??aa.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==jt.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=qh(e);if(n!=null&&t.force!==!0){let i=zh(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new re("dial-queue:already-connected",i)),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new re("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new cs("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new re("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new re("dial-queue:start-dial"));let a=ve([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??$3,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(o.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new re("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new cs("Peer had more than maxPeerAddrsToDial");a++;let p=ve([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[Y9]:T(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),o.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[j9]:T(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new as(g.message);l.push(g)}finally{p.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(d=>({multiaddr:F(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new cs("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new bl("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);s.push(...d.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:f})=>f.toString())),s.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let o=(await Promise.all(s.map(async d=>{let f=await O3(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;o=o.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let i=o.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of i){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new Fh(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?Q9(l):l.sort(this.addressSorter);if(u.length===0)throw new bl(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!mt.matches(s.multiaddr))!=null:!0}catch{}return!1}};var UR=Object.prototype.toString,FR=r=>UR.call(r)==="[object Error]",$R=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function K3(r){if(!(r&&FR(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:$R.has(t)}function KR(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function t1(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function V3(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var H3=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function VR(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function r1(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function HR(r,e){r<=0||await new Promise((t,n)=>{let s=()=>{clearTimeout(o),e.signal?.removeEventListener("abort",s),n(e.signal.reason)},o=setTimeout(()=>{e.signal?.removeEventListener("abort",s),t()},r);e.unref&&o.unref?.(),e.signal?.addEventListener("abort",s,{once:!0})})}async function qR({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof H3)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=VR(t,s);if(r1(n,a)<=0){let m=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await s.onFailedAttempt(m),o}let u=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),d=await s.shouldConsumeRetry(u),f=d&&i>0?c:0,h=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:f});if(await s.onFailedAttempt(h),r1(n,a)<=0||r1(n,a)<=0||i<=0||o instanceof TypeError&&!K3(o)||!await s.shouldRetry(h))throw o;let g=r1(n,a);if(g<=0)throw o;if(!d)return s.signal?.throwIfAborted(),!1;let y=Math.min(f,g);return s.signal?.throwIfAborted(),await HR(y,s),s.signal?.throwIfAborted(),!0}async function q3(r,e={}){if(e={...e},KR(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,V3("onFailedAttempt",e.onFailedAttempt),V3("shouldRetry",e.shouldRetry),V3("shouldConsumeRetry",e.shouldConsumeRetry),t1("factor",e.factor,{min:0,allowInfinity:!1}),t1("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),t1("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),t1("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await qR({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var n1=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new rr({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);ib(t)&&(this.queue.has(e)||this.queue.add(async n=>{await q3(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(so)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>ib(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function ib(r){for(let e of r.tags.keys())if(e.startsWith(so))return!0;return!1}var $3=50,z3={maxConnections:X9,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},s1=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??z3.maxConnections,this.maxConnections<1)throw new v("Connection Manager maxConnections must be greater than 0");this.connections=new kt,this.started=!1,this.peerId=e.peerId,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.allow=(t.allow??[]).map(n=>El(F(n))),this.deny=(t.deny??[]).map(n=>El(F(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??z3.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ra({points:t.inboundConnectionThreshold??z3.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Gh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>F(n))}),this.dialQueue=new e1(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Wh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Sl},connections:this.connections}),this.reconnectQueue=new n1({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;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 s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??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 s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kr(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await en(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([wl(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new v("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),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,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}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.started)throw new Pr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new re("connection:open",e));let{peerId:n,multiaddrs:s}=qh(e);if(this.peerId.equals(n))throw new ui("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=zh(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new re("dial-queue:already-connected")),t.onProgress?.(new re("connection:opened",c)),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??$3});if(o.status!=="open")throw new Zs("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new Zr("Duplicate multiaddr connection")),c;return a||i.push(o),t.onProgress?.(new re("connection:opened",o)),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([wl(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(vt(e.remoteAddr)){let o=ee(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(vt(e.remoteAddr)){let o=ee(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(vt(e.remoteAddr)){let s=ee(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!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=>F(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var WR=1e4,jR="1.0.0",YR="ping",XR="ipfs",ab=32,QR=!0,o1=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??XR}/${YR}/${jR}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??WR,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??QR,this.timeout=new Vr({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[ye]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s;try{s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let o=Xf(s);t=Date.now(),await Promise.all([o.write(crypto.getRandomValues(new Uint8Array(ab)),{signal:n}),o.read({bytes:ab,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(o){if(s?.abort(o),o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var i1=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:k(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:k(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");let n=this,s=new dr;for await(let o of Xn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new oa("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Pr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Pr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var a1=globalThis.CustomEvent??Event;async function*Zn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=Xe(),a=Xe(),c=!1,l,u=!1,d=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let g of r){if(o.length===t&&(i=Xe(),await i.promise),u||d)break;let y={done:!1};o.push(y),g().then(m=>{y.done=!0,y.ok=!0,y.value=m,s.dispatchEvent(new a1("task-complete"))},m=>{y.done=!0,y.err=m,s.dispatchEvent(new a1("task-complete"))})}c=!0,s.dispatchEvent(new a1("task-complete"))}catch(g){l=g,s.dispatchEvent(new a1("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let g=o[0];if(o.shift(),g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}function*p(){for(;f();)for(let g=0;g<o.length;g++)if(o[g].done){let y=o[g];if(o.splice(g,1),g--,y.ok)yield y.value;else throw u=!0,i.resolve(),y.err;i.resolve()}}try{for(;;){if(f()||(a=Xe(),await a.promise),l!=null||(n?yield*h():yield*p(),l!=null))throw l;if(c&&o.length===0)break}}finally{d=!0,i.resolve()}}var c1=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??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:k(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new yl("No peer routers available");if(e.toString()===this.peerId.toString())throw new Nh("Should not try to find self");let n=this,s=Xn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new Ue}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new yl("No peer routers available");let n=this,s=er(1024);for await(let o of Zn((async function*(){let i=Xn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).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 - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var l1=class extends ue{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=ve([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Xe(),yield(await wl(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=ve([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=crypto.getRandomValues(new Uint8Array(32)),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await de(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var G3=32,W3=64,u1=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=gt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Oh(`No handler registered for protocol ${e}`);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)&&n?.force!==!0)throw new Mh(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:G3,maxOutboundStreams:W3,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new v("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.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))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};var d1=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=gt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=gt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Wa.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new v("Transport must have a valid tag");if(this.transports.has(t))throw new v(`There is already a transport with the tag ${t}`);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 s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Vh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new re("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Pr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new Bh)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Zm.matches(c)?t.ipv4.attempts++:Jm.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Zm.matches(c)&&t.ipv4.success++,Jm.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,d),t.errors.set(c.toString(),d),d}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Wa.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Uh(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
18
18
|
${[...t.errors.entries()].map(([o,i])=>`
|
|
19
19
|
${o}: ${`${ZR(i)}`.split(`
|
|
20
20
|
`).join(`
|