libp2p 3.2.2 → 3.2.3-10b2bdf50
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 +8 -8
- package/dist/index.min.js.map +3 -3
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +10 -10
- package/src/version.ts +1 -1
- package/dist/typedoc-urls.json +0 -24
package/dist/index.min.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var Em=Object.create;var Qo=Object.defineProperty;var vm=Object.getOwnPropertyDescriptor;var Sm=Object.getOwnPropertyNames;var _m=Object.getPrototypeOf,Am=Object.prototype.hasOwnProperty;var On=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Be=(r,e)=>{for(var t in e)Qo(r,t,{get:e[t],enumerable:!0})},Ef=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sm(e))!Am.call(r,o)&&o!==t&&Qo(r,o,{get:()=>e[o],enumerable:!(n=vm(e,o))||n.enumerable});return r};var Ua=(r,e,t)=>(t=r!=null?Em(_m(r)):{},Ef(e||!r||!r.__esModule?Qo(t,"default",{value:r,enumerable:!0}):t,r)),Im=r=>Ef(Qo({},"__esModule",{value:!0}),r);var Bl=On(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.Netmask4Impl=void 0;un.ip2long=ln;un.long2ip=gt;function gt(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var ky=48,Ry=97,Oy=65;function Ny(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-ky)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Ry)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Oy)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function ln(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,o]=Ny(r);r=r.substring(o),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 Ml=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ln(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;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=(ln(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=gt(this.netLong),this.mask=gt(this.maskLong),this.hostmask=gt(~this.maskLong),this.first=this.bitmask<=30?gt(this.netLong+1):this.base,this.last=this.bitmask<=30?gt(this.netLong+this.size-2):gt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?gt(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):(ln(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(gt(this.netLong+this.size*e),this.mask)}forEach(e){let t=ln(this.first),n=ln(this.last),o=0;for(;t<=n;)e(gt(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};un.Netmask4Impl=Ml});var Zh=On(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.Netmask6Impl=void 0;fn.ip6bigint=Kl;fn.bigint2ip6=xr;var Fy=Bl(),Ul=(1n<<128n)-1n;function Kl(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),o=(0,Fy.ip2long)(n),s=r.substring(0,t+1)+"0:0";return Yh(s)&~0xffffffffn|BigInt(o)}return Yh(r)}function Yh(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.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 o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function xr(r){if(r<0n||r>Ul)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,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),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 ql=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):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=Ul>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Kl(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xr(this.netBigint),this.mask=xr(this.maskBigint),this.hostmask=xr(~this.maskBigint&Ul),this.first=this.base,this.last=xr(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):(Kl(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(xr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(xr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};fn.Netmask6Impl=ql});var Xh=On(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.long2ip=Zt.ip2long=Zt.Netmask=void 0;var Zs=Bl();Object.defineProperty(Zt,"ip2long",{enumerable:!0,get:function(){return Zs.ip2long}});Object.defineProperty(Zt,"long2ip",{enumerable:!0,get:function(){return Zs.long2ip}});var My=Zh(),$l=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 My.Netmask6Impl(e,t):this._impl=new Zs.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 Zs.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()}};Zt.Netmask=$l});var sm=On((V4,Yu)=>{"use strict";var Cw=Object.prototype.hasOwnProperty,Fe="~";function Go(){}Object.create&&(Go.prototype=Object.create(null),new Go().__proto__||(Fe=!1));function Tw(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function om(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Tw(t,n||r,o),i=Fe?Fe+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function xa(r,e){--r._eventsCount===0?r._events=new Go:delete r._events[e]}function Le(){this._events=new Go,this._eventsCount=0}Le.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Cw.call(t,n)&&e.push(Fe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Le.prototype.listeners=function(e){var t=Fe?Fe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Le.prototype.listenerCount=function(e){var t=Fe?Fe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Le.prototype.emit=function(e,t,n,o,s,i){var a=Fe?Fe+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;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,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Le.prototype.on=function(e,t,n){return om(this,e,t,n,!1)};Le.prototype.once=function(e,t,n){return om(this,e,t,n,!0)};Le.prototype.removeListener=function(e,t,n,o){var s=Fe?Fe+e:e;if(!this._events[s])return this;if(!t)return xa(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&xa(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:xa(this,s)}return this};Le.prototype.removeAllListeners=function(e){var t;return e?(t=Fe?Fe+e:e,this._events[t]&&xa(this,t)):(this._events=new Go,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=Fe;Le.EventEmitter=Le;typeof Yu<"u"&&(Yu.exports=Le)});var cm=On((dL,am)=>{am.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ex={};Be(ex,{createLibp2p:()=>Xw,dnsaddrResolver:()=>kr,isLibp2p:()=>Jw});var vf=Symbol.for("@libp2p/connection");var Ka=Symbol.for("@libp2p/content-routing");var Ze=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var P=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Nn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var er=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var tr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Nr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ot=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Jo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},es=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ts=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},rs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ns=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},wt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Fr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Fn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},os=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},ss=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Nt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var is=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var qa=Symbol.for("@libp2p/peer-discovery");var as=Symbol.for("@libp2p/peer-id");function Ft(r){return!!r?.[as]}var $a=Symbol.for("@libp2p/peer-routing");var za="keep-alive";function cs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Sf(...r){let e=[];for(let t of r)cs(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 _f(...r){let e=[];for(let t of r)cs(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 Mn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Mn||(Mn={}));function Cm(r){return typeof r?.handleEvent=="function"}function Tm(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Pe=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 o=Tm(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Cm(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Bn=Symbol.for("@libp2p/service-capabilities"),Va=Symbol.for("@libp2p/service-dependencies");var Ya={};Be(Ya,{base58btc:()=>te,base58flickr:()=>Nm});var Bx=new Uint8Array(0);function Af(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 xt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function If(r){return new TextEncoder().encode(r)}function Cf(r){return new TextDecoder().decode(r)}function Lm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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 g=0,p=0,y=0,v=m.length;y!==v&&m[y]===0;)y++,g++;for(var S=(v-y)*u+1>>>0,k=new Uint8Array(S);y!==v;){for(var L=m[y],U=0,R=S-1;(L!==0||U<p)&&R!==-1;R--,U++)L+=256*k[R]>>>0,k[R]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");p=U,y++}for(var I=S-p;I!==S&&k[I]===0;)I++;for(var K=c.repeat(g);I<S;++I)K+=r.charAt(k[I]);return K}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var g=0;if(m[g]!==" "){for(var p=0,y=0;m[g]===c;)p++,g++;for(var v=(m.length-g)*l+1>>>0,S=new Uint8Array(v);m[g];){var k=t[m.charCodeAt(g)];if(k===255)return;for(var L=0,U=v-1;(k!==0||L<y)&&U!==-1;U--,L++)k+=a*S[U]>>>0,S[U]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");y=L,g++}if(m[g]!==" "){for(var R=v-y;R!==v&&S[R]===0;)R++;for(var I=new Uint8Array(p+(v-R)),K=p;R!==v;)I[K++]=S[R++];return I}}}function h(m){var g=d(m);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Pm=Lm,Dm=Pm,Lf=Dm;var Ha=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")}},Wa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Pf(this,e)}},Ga=class{decoders;constructor(e){this.decoders=e}or(e){return Pf(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 Pf(r,e){return new Ga({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ja=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ha(e,t,n),this.decoder=new Wa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Mr({name:r,prefix:e,encode:t,decode:n}){return new ja(r,e,t,n)}function Mt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Lf(t,r);return Mr({prefix:e,name:r,encode:n,decode:s=>xt(o(s))})}function km(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++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,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Rm(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Om(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ie({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Om(n);return Mr({prefix:e,name:r,encode(s){return Rm(s,n,t)},decode(s){return km(s,o,t,r)}})}var te=Mt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nm=Mt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Za={};Be(Za,{base32:()=>We,base32hex:()=>Um,base32hexpad:()=>qm,base32hexpadupper:()=>$m,base32hexupper:()=>Km,base32pad:()=>Mm,base32padupper:()=>Bm,base32upper:()=>Fm,base32z:()=>zm});var We=ie({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fm=ie({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Mm=ie({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Bm=ie({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Um=ie({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Km=ie({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qm=ie({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$m=ie({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zm=ie({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xa={};Be(Xa,{base36:()=>Un,base36upper:()=>Vm});var Un=Mt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vm=Mt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hm=Rf,Df=128,Wm=127,Gm=~Wm,jm=Math.pow(2,31);function Rf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jm;)e[t++]=r&255|Df,r/=128;for(;r&Gm;)e[t++]=r&255|Df,r>>>=7;return e[t]=r|0,Rf.bytes=t-n+1,e}var Ym=Qa,Zm=128,kf=127;function Qa(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&kf)<<o:(i&kf)*Math.pow(2,o),o+=7}while(i>=Zm);return Qa.bytes=s-n,t}var Xm=Math.pow(2,7),Qm=Math.pow(2,14),Jm=Math.pow(2,21),eg=Math.pow(2,28),tg=Math.pow(2,35),rg=Math.pow(2,42),ng=Math.pow(2,49),og=Math.pow(2,56),sg=Math.pow(2,63),ig=function(r){return r<Xm?1:r<Qm?2:r<Jm?3:r<eg?4:r<tg?5:r<rg?6:r<ng?7:r<og?8:r<sg?9:10},ag={encode:Hm,decode:Ym,encodingLength:ig},cg=ag,Kn=cg;function qn(r,e=0){return[Kn.decode(r,e),Kn.decode.bytes]}function Br(r,e,t=0){return Kn.encode(r,e,t),e}function Ur(r){return Kn.encodingLength(r)}function ut(r,e){let t=e.byteLength,n=Ur(r),o=n+Ur(t),s=new Uint8Array(o+t);return Br(r,s,0),Br(t,s,n),s.set(e,o),new Kr(r,t,e,s)}function Et(r){let e=xt(r),[t,n]=qn(e),[o,s]=qn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Kr(t,o,i,e)}function Of(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Af(r.bytes,t.bytes)}}var Kr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Nf(r,e){let{bytes:t,version:n}=r;return n===0?ug(t,Ja(r),e??te.encoder):fg(t,Ja(r),e??We.encoder)}var Ff=new WeakMap;function Ja(r){let e=Ff.get(r);if(e==null){let t=new Map;return Ff.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==$n)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dg)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&&Of(e.multihash,n.multihash)}toString(e){return Nf(this,e)}toJSON(){return{"/":Nf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Mf(n,o,s.bytes))}else if(t[hg]===!0){let{version:n,multihash:o,code:s}=t,i=Et(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==$n)throw new Error(`Version 0 CID must use dag-pb (code: ${$n}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Mf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,$n,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=xt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Kr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=qn(e.subarray(t));return t+=d,f},o=n(),s=$n;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=lg(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ja(s).set(n,e),s}};function lg(r,e){switch(r[0]){case"Q":{let t=e??te;return[te.prefix,t.decode(`${te.prefix}${r}`)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Un.prefix:{let t=e??Un;return[Un.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 ug(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function fg(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var $n=112,dg=18;function Mf(r,e,t){let n=Ur(r),o=n+Ur(e),s=new Uint8Array(o+t.byteLength);return Br(r,s,0),Br(e,s,n),s.set(t,o),s}var hg=Symbol.for("@ipld/js-cid/CID");var ec={};Be(ec,{identity:()=>Xe});var Bf=0,pg="identity",Uf=xt;function mg(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(Bf,Uf(r))}var Xe={code:Bf,name:pg,encode:Uf,digest:mg};function Q(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}async function Kf(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 qf(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function $f(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}function ae(r=0){return new Uint8Array(r)}function _e(r=0){return new Uint8Array(r)}function Qe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=_e(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Vf=Symbol.for("@achingbrain/uint8arraylist");function zf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function us(r){return!!r?.[Vf]}var J=class r{bufs;length;[Vf]=!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(us(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(us(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=zf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=zf(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(us(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Qe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Qe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(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(!us(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}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=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var tc={};Be(tc,{base10:()=>gg});var gg=Mt({prefix:"9",name:"base10",alphabet:"0123456789"});var rc={};Be(rc,{base16:()=>yg,base16upper:()=>bg});var yg=ie({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bg=ie({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var nc={};Be(nc,{base2:()=>wg});var wg=ie({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oc={};Be(oc,{base256emoji:()=>_g});var Hf=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}"),xg=Hf.reduce((r,e,t)=>(r[t]=e,r),[]),Eg=Hf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function vg(r){return r.reduce((e,t)=>(e+=xg[t],e),"")}function Sg(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Eg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var _g=Mr({prefix:"\u{1F680}",name:"base256emoji",encode:vg,decode:Sg});var ac={};Be(ac,{base64:()=>sc,base64pad:()=>Ag,base64url:()=>ic,base64urlpad:()=>Ig});var sc=ie({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ag=ie({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ic=ie({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ig=ie({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cc={};Be(cc,{base8:()=>Cg});var Cg=ie({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lc={};Be(lc,{identity:()=>Tg});var Tg=Mr({prefix:"\0",name:"identity",encode:r=>Cf(r),decode:r=>If(r)});var vE=new TextEncoder,SE=new TextDecoder;var dc={};Be(dc,{sha256:()=>qr,sha512:()=>kg});var Dg=20;function fc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new uc(r,e,t,n,o)}var uc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Dg,this.maxDigestLength=s}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?Wf(n,this.code,t?.truncate):n.then(o=>Wf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Wf(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 jf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var qr=fc({name:"sha2-256",code:18,encode:jf("SHA-256")}),kg=fc({name:"sha2-512",code:19,encode:jf("SHA-512")});var zn={...lc,...nc,...cc,...tc,...rc,...Za,...Xa,...Ya,...ac,...oc},NE={...dc,...ec};function Zf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Yf=Zf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),hc=Zf("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=_e(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Rg={utf8:Yf,"utf-8":Yf,hex:zn.base16,latin1:hc,ascii:hc,binary:hc,...zn},fs=Rg;function D(r,e="utf8"){let t=fs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function B(r,e="utf8"){let t=fs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Og=parseInt("11111",2),pc=parseInt("10000000",2),Ng=parseInt("01111111",2),Xf={0:Vn,1:Vn,2:Fg,3:Ug,4:Kg,5:Bg,6:Mg,16:Vn,22:Vn,48:Vn};function vt(r,e={offset:0}){let t=r[e.offset]&Og;if(e.offset++,Xf[t]!=null)return Xf[t](r,e);throw new Error("No decoder for tag "+t)}function Hn(r,e){let t=0;if((r[e.offset]&pc)===pc){let n=r[e.offset]&Ng,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Vn(r,e){Hn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=vt(r,e);if(n===null)break;t.push(n)}return t}function Fg(r,e){let t=Hn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Mg(r,e){let t=Hn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Bg(r,e){return e.offset++,null}function Ug(r,e){let t=Hn(r,e),n=r[e.offset];e.offset++;let o=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 o}function Kg(r,e){let t=Hn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function qg(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 ds(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=qg(r.byteLength);return new J(Uint8Array.from([e.byteLength|pc]),e)}function De(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]),ds(e),e)}function Wn(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),ds(t),t)}function Qf(r){return new J(Uint8Array.from([4]),ds(r),r)}function Je(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),ds(t),t)}var $g=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),zg=Uint8Array.from([6,5,43,129,4,0,34]),Vg=Uint8Array.from([6,5,43,129,4,0,35]),Hg={ext:!0,kty:"EC",crv:"P-256"},Wg={ext:!0,kty:"EC",crv:"P-384"},Gg={ext:!0,kty:"EC",crv:"P-521"},mc=32,gc=48,yc=66;function bc(r){let e=vt(r);return Jf(e)}function Jf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===mc*2+1)return n=B(e.subarray(t,t+mc),"base64url"),o=B(e.subarray(t+mc),"base64url"),new rr({...Hg,key_ops:["verify"],x:n,y:o});if(e.byteLength===gc*2+1)return n=B(e.subarray(t,t+gc),"base64url"),o=B(e.subarray(t+gc),"base64url"),new rr({...Wg,key_ops:["verify"],x:n,y:o});if(e.byteLength===yc*2+1)return n=B(e.subarray(t,t+yc),"base64url"),o=B(e.subarray(t+yc),"base64url"),new rr({...Gg,key_ops:["verify"],x:n,y:o});throw new P(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ed(r){return Je([De(Uint8Array.from([1])),Qf(D(r.d??"","base64url")),Je([rd(r.crv)],160),Je([Wn(new J(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function td(r){return Je([De(Uint8Array.from([1])),Je([rd(r.crv)],160),Je([Wn(new J(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function rd(r){if(r==="P-256")return $g;if(r==="P-384")return zg;if(r==="P-521")return Vg;throw new P(`Invalid curve ${r}`)}async function nd(r="P-256"){let e=await Kf(r);return new hs(e.privateKey)}var rr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=td(this.jwk)),this._raw}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return $f(this.jwk,t,e,n)}},hs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new rr({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=ed(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async sign(e,t){return qf(this.jwk,e,t)}};function wc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ut(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function qe(r,e,t=""){let n=wc(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function ps(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ut(r.outputLen),Ut(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function $r(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ms(r,e){qe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function _t(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function gs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function et(r,e){return r<<32-e|r>>>e}var sd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ys(r){if(qe(r),sd)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=jg[r[t]];return e}var St={_0:48,_9:57,A:65,F:70,a:97,f:102};function od(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function Gn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(sd)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}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 o=0,s=0;o<t;o++,s+=2){let i=od(r.charCodeAt(s)),a=od(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function xc(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];qe(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ec(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function bs(r=32){Ut(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 vc=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function id(r,e,t){return r&e^~r&t}function ad(r,e,t){return r&e^r&t^e&t}var jn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=gs(this.buffer)}update(e){$r(this),qe(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$r(this),ms(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,_t(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},At=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ws=BigInt(4294967295),cd=BigInt(32);function Yg(r,e=!1){return e?{h:Number(r&ws),l:Number(r>>cd&ws)}:{h:Number(r>>cd&ws)|0,l:Number(r&ws)|0}}function ld(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Yg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Sc=(r,e,t)=>r>>>t,_c=(r,e,t)=>r<<32-t|e>>>t,nr=(r,e,t)=>r>>>t|e<<32-t,or=(r,e,t)=>r<<32-t|e>>>t,Yn=(r,e,t)=>r<<64-t|e>>>t-32,Zn=(r,e,t)=>r>>>t-32|e<<64-t;function ft(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var ud=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),fd=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,dd=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),hd=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,pd=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),md=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Xg=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]),Kt=new Uint32Array(64),Ac=class extends jn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Kt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Kt[f-15],h=Kt[f-2],m=et(d,7)^et(d,18)^d>>>3,g=et(h,17)^et(h,19)^h>>>10;Kt[f]=g+Kt[f-7]+m+Kt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=et(a,6)^et(a,11)^et(a,25),h=u+d+id(a,c,l)+Xg[f]+Kt[f]|0,g=(et(n,2)^et(n,13)^et(n,22))+ad(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){_t(Kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_t(this.buffer)}},Ic=class extends Ac{A=At[0]|0;B=At[1]|0;C=At[2]|0;D=At[3]|0;E=At[4]|0;F=At[5]|0;G=At[6]|0;H=At[7]|0;constructor(){super(32)}};var gd=ld(["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))),Qg=gd[0],Jg=gd[1],qt=new Uint32Array(80),$t=new Uint32Array(80),Cc=class extends jn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:g,Hl:p}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,p]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,p){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=p|0}process(e,t){for(let S=0;S<16;S++,t+=4)qt[S]=e.getUint32(t),$t[S]=e.getUint32(t+=4);for(let S=16;S<80;S++){let k=qt[S-15]|0,L=$t[S-15]|0,U=nr(k,L,1)^nr(k,L,8)^Sc(k,L,7),R=or(k,L,1)^or(k,L,8)^_c(k,L,7),I=qt[S-2]|0,K=$t[S-2]|0,Y=nr(I,K,19)^Yn(I,K,61)^Sc(I,K,6),q=or(I,K,19)^Zn(I,K,61)^_c(I,K,6),b=dd(R,q,$t[S-7],$t[S-16]),w=hd(b,U,Y,qt[S-7],qt[S-16]);qt[S]=w|0,$t[S]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:g,Gl:p,Hh:y,Hl:v}=this;for(let S=0;S<80;S++){let k=nr(f,d,14)^nr(f,d,18)^Yn(f,d,41),L=or(f,d,14)^or(f,d,18)^Zn(f,d,41),U=f&h^~f&g,R=d&m^~d&p,I=pd(v,L,R,Jg[S],$t[S]),K=md(I,y,k,U,Qg[S],qt[S]),Y=I|0,q=nr(n,o,28)^Yn(n,o,34)^Yn(n,o,39),b=or(n,o,28)^Zn(n,o,34)^Zn(n,o,39),w=n&s^n&a^s&a,_=o&i^o&c^i&c;y=g|0,v=p|0,g=h|0,p=m|0,h=f|0,m=d|0,{h:f,l:d}=ft(l|0,u|0,K|0,Y|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=ud(Y,b,_);n=fd(E,K,q,w),o=E|0}({h:n,l:o}=ft(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ft(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ft(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ft(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ft(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=ft(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:p}=ft(this.Gh|0,this.Gl|0,g|0,p|0),{h:y,l:v}=ft(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,l,u,f,d,h,m,g,p,y,v)}roundClean(){_t(qt,$t)}destroy(){this.destroyed=!0,_t(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Tc=class extends Cc{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var zr=Ec(()=>new Ic,vc(1));var xs=Ec(()=>new Tc,vc(3));var W=(r,e,t)=>qe(r,e,t),Pc=Ut,Vr=ys,he=(...r)=>xc(...r),Hr=r=>Gn(r),sr=wc,Xn=r=>bs(r),vs=BigInt(0),Lc=BigInt(1);function tt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Ss(r){if(typeof r=="bigint"){if(!Es(r))throw new RangeError("positive bigint expected, got "+r)}else Pc(r);return r}function rt(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 Qn(r){let e=Ss(r).toString(16);return e.length&1?"0"+e:e}function yd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?vs:BigInt("0x"+r)}function ir(r){return yd(ys(r))}function dt(r){return yd(ys(Jn(qe(r)).reverse()))}function _s(r,e){if(Ut(e),e===0)throw new RangeError("zero length");r=Ss(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Gn(t.padStart(e*2,"0"))}function Dc(r,e){return _s(r,e).reverse()}function bd(r,e){if(r=W(r),e=W(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Jn(r){return Uint8Array.from(W(r))}function As(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Es=r=>typeof r=="bigint"&&vs<=r;function e0(r,e,t){return Es(r)&&Es(e)&&Es(t)&&e<=r&&r<t}function Wr(r,e,t,n){if(!e0(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Gr(r){if(r<vs)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>vs;r>>=Lc,e+=1);return e}var eo=r=>(Lc<<BigInt(r))-Lc;function wd(r,e,t){if(Ut(r,"hashLen"),Ut(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...p)=>t(l,he(c,...p)),h=(p=o)=>{l=d(s,p),c=d(),p.length!==0&&(l=d(i,p),c=d())},m=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,y=[];for(;p<e;){c=d();let v=c.slice();y.push(v),p+=c.length}return he(...y)};return(p,y)=>{f(),h(p);let v;for(;(v=y(m()))===void 0;)h();return f(),v}}function nt(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var kc=()=>{throw new Error("not implemented")};var Ee=BigInt(0),ce=BigInt(1),ar=BigInt(2),Sd=BigInt(3),_d=BigInt(4),Ad=BigInt(5),t0=BigInt(7),Id=BigInt(8),r0=BigInt(9),Cd=BigInt(16);function fe(r,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Ee?t:e+t}function oe(r,e,t){if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Ee;)n*=n,n%=t;return n}function xd(r,e){if(r===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let t=fe(r,e),n=e,o=Ee,s=ce,i=ce,a=Ee;for(;t!==Ee;){let l=n/t,u=n-t*l,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==ce)throw new Error("invert: does not exist");return fe(o,e)}function Rc(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Td(r,e){let t=r,n=(t.ORDER+ce)/_d,o=t.pow(e,n);return Rc(t,o,e),o}function n0(r,e){let t=r,n=(t.ORDER-Ad)/Id,o=t.mul(e,ar),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,ar),s),c=t.mul(i,t.sub(a,t.ONE));return Rc(t,c,e),c}function o0(r){let e=jr(r),t=Ld(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+t0)/Cd;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),d=l.mul(u,o),h=l.mul(u,s),m=l.eql(l.sqr(f),c),g=l.eql(l.sqr(d),c);u=l.cmov(u,f,m),f=l.cmov(h,d,g);let p=l.eql(l.sqr(f),c),y=l.cmov(u,f,p);return Rc(l,y,c),y})}function Ld(r){if(r<Sd)throw new Error("sqrt is not defined for small field");let e=r-ce,t=0;for(;e%ar===Ee;)e/=ar,t++;let n=ar,o=jr(r);for(;Ed(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Td;let s=o.pow(n,e),i=(e+ce)/ar;return function(c,l){let u=c;if(u.is0(l))return l;if(Ed(u,l)!==1)throw new Error("Cannot find square root");let f=t,d=u.mul(u.ONE,s),h=u.pow(l,e),m=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let g=1,p=u.sqr(h);for(;!u.eql(p,u.ONE);)if(g++,p=u.sqr(p),g===f)throw new Error("Cannot find square root");let y=ce<<BigInt(f-g-1),v=u.pow(d,y);f=g,d=u.sqr(v),h=u.mul(h,d),m=u.mul(m,v)}return m}}function s0(r){return r%_d===Sd?Td:r%Id===Ad?n0:r%Cd===r0?o0(r):Ld(r)}var It=(r,e)=>(fe(r,e)&ce)===ce,i0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=i0.reduce((n,o)=>(n[o]="function",n),e);if(nt(r,t),rt(r.BYTES,"BYTES"),rt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ce)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function a0(r,e,t){let n=r;if(t<Ee)throw new Error("invalid exponent, negatives unsupported");if(t===Ee)return n.ONE;if(t===ce)return e;let o=n.ONE,s=e;for(;t>Ee;)t&ce&&(o=n.mul(o,s)),s=n.sqr(s),t>>=ce;return o}function to(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function Ed(r,e){let t=r,n=(t.ORDER-ce)/ar,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function c0(r,e){if(e!==void 0&&Pc(e),r<=Ee)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=Gr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var vd=new WeakMap,Is=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=ce;_lengths;_mod;constructor(e,t={}){if(e<=ce)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:o,nByteLength:s}=c0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ce)===ce}neg(e){return fe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return fe(e*e,this.ORDER)}add(e,t){return fe(e+t,this.ORDER)}sub(e,t){return fe(e-t,this.ORDER)}mul(e,t){return fe(e*t,this.ORDER)}pow(e,t){return a0(this,e,t)}div(e,t){return fe(e*xd(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 xd(e,this.ORDER)}sqrt(e){let t=vd.get(this);return t||vd.set(this,t=s0(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Dc(e,this.BYTES):_s(e,this.BYTES)}fromBytes(e,t=!1){W(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?dt(e):ir(e);if(a&&(c=fe(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return to(this,e)}cmov(e,t,n){return tt(n,"condition"),n?t:e}};Object.freeze(Is.prototype);function jr(r,e={}){return new Is(r,e)}function Pd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ce)throw new Error("field order must be greater than 1");let e=Gr(r-ce);return Math.ceil(e/8)}function Nc(r){let e=Pd(r);return e+Math.ceil(e/2)}function Fc(r,e,t=!1){W(r);let n=r.length,o=Pd(e),s=Math.max(Nc(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?dt(r):ir(r),a=fe(i,e-ce)+ce;return t?Dc(a,o):_s(a,o)}var Yr=BigInt(0),cr=BigInt(1);function ro(r,e){let t=e.negate();return r?t:e}function lr(r,e){let t=to(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Od(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Mc(r,e){Od(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=eo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Dd(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=cr);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var Bc=new WeakMap,Nd=new WeakMap;function Uc(r){return Nd.get(r)||1}function kd(r){if(r!==Yr)throw new Error("invalid wNAF")}var Zr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Yr;)t&cr&&(n=n.add(o)),o=o.double(),t>>=cr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Mc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Mc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=Dd(n,a,i);n=c,u?s=s.add(ro(d,t[h])):o=o.add(ro(f,t[l]))}return kd(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Mc(e,this.bits);for(let i=0;i<s.windows&&n!==Yr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Dd(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return kd(n),o}getPrecomputes(e,t,n){let o=Bc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Bc.set(t,o))),o}cached(e,t,n){let o=Uc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Uc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Od(t,this.bits),Nd.set(e,t),Bc.delete(e)}hasCache(e){return Uc(e)!==1}};function Fd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Yr||n>Yr;)t&cr&&(s=s.add(o)),n&cr&&(i=i.add(o)),o=o.double(),t>>=cr,n>>=cr;return{p1:s,p2:i}}function Rd(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oc(e),e}else return jr(r,{isLE:t})}function Cs(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Yr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Rd(e.p,t.Fp,n),s=Rd(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function Ts(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var zt=BigInt(0),ge=BigInt(1),Kc=BigInt(2),l0=BigInt(8);function u0(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Md(r,e={}){let t=e,n=Cs("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;nt(t,{},{uvRatio:"function"});let c=Kc<<BigInt(s.BYTES*8)-ge,l=g=>o.create(g),u=t.uvRatio===void 0?(g,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,p))}}catch{return{isValid:!1,value:zt}}}:t.uvRatio;if(!u0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,p,y=!1){let v=y?ge:zt;return Wr("coordinate "+g,p,v,c),p}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ge,l(i.Gx*i.Gy));static ZERO=new h(zt,ge,ge,zt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,y,v,S){this.X=f("x",p),this.Y=f("y",y),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof h)throw new Error("extended point not allowed");let{x:y,y:v}=p||{};return f("x",y),f("y",v),new h(y,v,ge,l(y*v))}static fromBytes(p,y=!1){let v=o.BYTES,{a:S,d:k}=i;p=Jn(W(p,v,"point")),tt(y,"zip215");let L=Jn(p),U=p[v-1];L[v-1]=U&-129;let R=dt(L),I=y?c:o.ORDER;Wr("point.y",R,zt,I);let K=l(R*R),Y=l(K-ge),q=l(k*K-S),{isValid:b,value:w}=u(Y,q);if(!b)throw new Error("bad point: invalid y coordinate");let _=(w&ge)===ge,E=(U&128)!==0;if(!y&&w===zt&&E)throw new Error("bad point: x=0 and x_0=1");return E!==_&&(w=l(-w)),h.fromAffine({x:w,y:R})}static fromHex(p,y=!1){return h.fromBytes(Hr(p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return m.createCache(this,p),y||this.multiply(Kc),this}assertValidity(){let p=this,{a:y,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:k,Z:L,T:U}=p,R=l(S*S),I=l(k*k),K=l(L*L),Y=l(K*K),q=l(R*y),b=l(K*l(q+I)),w=l(Y+l(v*l(R*I)));if(b!==w)throw new Error("bad point: equation left != right (1)");let _=l(S*k),E=l(L*U);if(_!==E)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:y,Y:v,Z:S}=this,{X:k,Y:L,Z:U}=p,R=l(y*U),I=l(k*S),K=l(v*U),Y=l(L*S);return R===I&&K===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:p}=i,{X:y,Y:v,Z:S}=this,k=l(y*y),L=l(v*v),U=l(Kc*l(S*S)),R=l(p*k),I=y+v,K=l(l(I*I)-k-L),Y=R+L,q=Y-U,b=R-L,w=l(K*q),_=l(Y*b),E=l(K*b),x=l(q*Y);return new h(w,_,x,E)}add(p){d(p);let{a:y,d:v}=i,{X:S,Y:k,Z:L,T:U}=this,{X:R,Y:I,Z:K,T:Y}=p,q=l(S*R),b=l(k*I),w=l(U*v*Y),_=l(L*K),E=l((S+k)*(R+I)-q-b),x=_-w,A=_+w,T=l(b-y*q),C=l(E*x),O=l(A*T),F=l(E*T),H=l(x*A);return new h(C,O,H,F)}subtract(p){return d(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=m.cached(this,p,S=>lr(h,S));return lr(h,[y,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===zt?h.ZERO:this.is0()||p===ge?this:m.unsafe(this,p,y=>lr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(p){let y=this,v=p,{X:S,Y:k,Z:L}=y,U=y.is0();v==null&&(v=U?l0:o.inv(L));let R=l(S*v),I=l(k*v),K=o.mul(L,v);if(U)return{x:zt,y:ge};if(K!==ge)throw new Error("invZ was invalid");return{x:R,y:I}}clearCofactor(){return a===ge?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=p&ge?128:0,v}toHex(){return Vr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Zr(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Ls=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){kc()}static fromHex(e){kc()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Vr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Bd(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;nt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(rt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Xn:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,w,_)=>{if(tt(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function m(b){return c.create(dt(b))}function g(b){let w=R.secretKey;W(b,R.secretKey,"secretKey");let _=W(n(b),2*w,"hashedSecretKey"),E=d(_.slice(0,w)),x=_.slice(w,2*w),A=m(E);return{head:E,prefix:x,scalar:A}}function p(b){let{head:w,prefix:_,scalar:E}=g(b),x=i.multiply(E),A=x.toBytes();return{head:w,prefix:_,scalar:E,point:x,pointBytes:A}}function y(b){return p(b).pointBytes}function v(b=Uint8Array.of(),...w){let _=he(...w);return m(n(h(_,W(b,void 0,"context"),!!s)))}function S(b,w,_={}){b=W(b,void 0,"message"),s&&(b=s(b));let{prefix:E,scalar:x,pointBytes:A}=p(w),T=v(_.context,E,b),C=i.multiply(T).toBytes(),O=v(_.context,C,A,b),F=c.create(T+O*x);if(!c.isValid(F))throw new Error("sign failed: invalid s");let H=he(C,c.toBytes(F));return W(H,R.signature,"result")}let k={zip215:o.zip215};function L(b,w,_,E=k){let{context:x}=E,A=E.zip215===void 0?!!k.zip215:E.zip215,T=R.signature;b=W(b,T,"signature"),w=W(w,void 0,"message"),_=W(_,R.publicKey,"publicKey"),A!==void 0&&tt(A,"zip215"),s&&(w=s(w));let C=T/2,O=b.subarray(0,C),F=dt(b.subarray(C,T)),H,j,$;try{H=r.fromBytes(_,A),j=r.fromBytes(O,A),$=i.multiplyUnsafe(F)}catch{return!1}if(!A&&H.isSmallOrder())return!1;let de=v(x,O,_,w);return j.add(H.multiplyUnsafe(de)).subtract($).clearCofactor().is0()}let U=a.BYTES,R={secretKey:U,publicKey:U,signature:2*U,seed:U};function I(b){return b=b===void 0?f(R.seed):b,W(b,R.seed,"seed")}function K(b){return sr(b)&&b.length===R.secretKey}function Y(b,w){try{return!!r.fromBytes(b,w===void 0?k.zip215:w)}catch{return!1}}let q={getExtendedPublicKey:p,randomSecretKey:I,isValidSecretKey:K,isValidPublicKey:Y,toMontgomery(b){let{y:w}=r.fromBytes(b),_=R.publicKey,E=_===32;if(!E&&_!==57)throw new Error("only defined for 25519 and 448");let x=E?a.div(ge+w,ge-w):a.div(w-ge,w+ge);return a.toBytes(x)},toMontgomerySecret(b){let w=R.secretKey;W(b,w);let _=n(b.subarray(0,w));return d(_).subarray(0,w)}};return Object.freeze(R),Object.freeze(q),Object.freeze({keygen:Ts(I,y),getPublicKey:y,sign:S,verify:L,utils:q,Point:r,lengths:R})}function no(r,e){if(rt(r),rt(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function f0(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function d0(r){if(!sr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?As(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function qc(r,e,t,n){W(r),rt(t),e=d0(e),e.length>255&&(e=n(he(As("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=he(e,no(e.length,1)),c=new Uint8Array(s),l=no(t,2),u=new Array(i),f=n(he(c,r,l,no(0,1),a));u[0]=n(he(f,no(1,1),a));for(let h=1;h<i;h++){let m=[f0(f,u[h-1]),no(h+1,1),a];u[h]=n(he(...m))}return he(...u).slice(0,t)}var Ud="HashToScalar-";var h0=BigInt(0),Ct=BigInt(1),Kd=BigInt(2);var p0=BigInt(5),m0=BigInt(8),Xr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Hc={p:Xr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:m0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function g0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Xr,a=r*r%s*r%s,c=oe(a,Kd,s)*a%s,l=oe(c,Ct,s)*r%s,u=oe(l,p0,s)*l%s,f=oe(u,e,s)*u%s,d=oe(f,t,s)*f%s,h=oe(d,n,s)*d%s,m=oe(h,o,s)*h%s,g=oe(m,o,s)*h%s,p=oe(g,e,s)*u%s;return{pow_p_5_8:oe(p,Kd,s)*r%s,b2:a}}function y0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var $c=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Wc(r,e){let t=Xr,n=fe(e*e*e,t),o=fe(n*n*e,t),s=g0(r*o).pow_p_5_8,i=fe(r*n*s,t),a=fe(e*i*i,t),c=i,l=fe(i*$c,t),u=a===r,f=a===fe(-r,t),d=a===fe(-r*$c,t);return u&&(i=c),(f||d)&&(i=l),It(i,t)&&(i=fe(-i,t)),{isValid:u||f,value:i}}var Ht=Md(Hc,{uvRatio:Wc}),Vt=Ht.Fp,zd=Ht.Fn;function b0(r){return Bd(Ht,xs,Object.assign({adjustScalarBytes:y0,zip215:!0},r))}var oo=b0({});var zc=$c,w0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),E0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),v0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),qd=r=>Wc(Ct,r),S0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Vc=r=>Vt.create(dt(r)&S0);function $d(r){let{d:e}=Hc,t=Xr,n=y=>Vt.create(y),o=n(zc*r*r),s=n((o+Ct)*E0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Wc(s,a),u=n(l*r);It(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Ct)*v0-a),d=l*l,h=n((l+l)*a),m=n(f*w0),g=n(Ct-d),p=n(Ct+d);return new Ht(n(h*p),n(g*m),n(m*p),n(h*g))}var Wt=class r extends Ls{static BASE=new r(Ht.BASE);static ZERO=new r(Ht.ZERO);static Fp=Vt;static Fn=zd;constructor(e){super(e)}static fromAffine(e){return new r(Ht.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){qe(e,32);let{a:t,d:n}=Hc,o=Xr,s=k=>Vt.create(k),i=Vc(e);if(!bd(Vt.toBytes(i),e)||It(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Ct+t*a),l=s(Ct-t*a),u=s(c*c),f=s(l*l),d=s(t*n*u-f),{isValid:h,value:m}=qd(s(d*f)),g=s(m*l),p=s(m*g*d),y=s((i+i)*g);It(y,o)&&(y=s(-y));let v=s(c*p),S=s(y*v);if(!h||It(S,o)||v===h0)throw new Error("invalid ristretto255 encoding 2");return new r(new Ht(y,v,Ct,S))}static fromHex(e){return r.fromBytes(Gn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=Xr,i=p=>Vt.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=qd(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),m;if(It(o*h,s)){let p=i(t*zc),y=i(e*zc);e=p,t=y,m=i(f*x0)}else m=d;It(e*h,s)&&(t=i(-t));let g=i((n-t)*m);return It(g,s)&&(g=i(-g)),Vt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>Vt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Wt.BASE);Object.freeze(Wt.ZERO);Object.freeze(Wt.prototype);Object.freeze(Wt);var _0=Object.freeze({Point:Wt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=qc(r,t,64,xs);return _0.deriveToCurve(n)},hashToScalar(r,e={DST:Ud}){let t=qc(r,e.DST,64,xs);return zd.create(dt(t))},deriveToCurve(r){qe(r,64);let e=Vc(r.subarray(0,32)),t=$d(e),n=Vc(r.subarray(32,64)),o=$d(n);return new Wt(t.add(o))}});var so=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},io=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ps=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Vd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ps("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 Ue=Vd;var Ds=32,ao=64,Gc=32;var Qr,Hd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Wd(){let r=oo.utils.randomSecretKey(),e=oo.getPublicKey(r);return{privateKey:L0(r,e),publicKey:e}}async function A0(r,e){let t;r.length===ao?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:B(r.subarray(32),"base64url"),d:B(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ue.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ue.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function I0(r,e){let t=r.subarray(0,Gc);return oo.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Gd(r,e){return Qr==null&&(Qr=await Hd),Qr?A0(r,e):I0(r,e)}async function C0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function T0(r,e,t){return oo.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function jd(r,e,t){return Qr==null&&(Qr=await Hd),Qr?C0(r,e,t):T0(r,e,t)}function L0(r,e){let t=new Uint8Array(ao);for(let n=0;n<Gc;n++)t[n]=r[n],t[Gc+n]=e[n];return t}function Jr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var co=class{type="Ed25519";raw;constructor(e){this.raw=Rs(e,Ds)}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=jd(this.raw,t,e);return Jr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},ks=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Rs(e,ao),this.publicKey=new co(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Gd(this.raw,e);return Jr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function jc(r){return r=Rs(r,Ds),new co(r)}async function Zd(){let{privateKey:r,publicKey:e}=Wd();return new ks(r,e)}function Rs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new P(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var P0=Math.pow(2,7),D0=Math.pow(2,14),k0=Math.pow(2,21),Yc=Math.pow(2,28),Zc=Math.pow(2,35),Xc=Math.pow(2,42),Qc=Math.pow(2,49),Z=128,Ae=127;function ye(r){if(r<P0)return 1;if(r<D0)return 2;if(r<k0)return 3;if(r<Yc)return 4;if(r<Zc)return 5;if(r<Xc)return 6;if(r<Qc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function en(r,e,t=0){switch(ye(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function R0(r,e,t=0){switch(ye(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Jc(r,e){let t=r[e],n=0;if(n+=t&Ae,t<Z||(t=r[e+1],n+=(t&Ae)<<7,t<Z)||(t=r[e+2],n+=(t&Ae)<<14,t<Z)||(t=r[e+3],n+=(t&Ae)<<21,t<Z)||(t=r[e+4],n+=(t&Ae)*Yc,t<Z)||(t=r[e+5],n+=(t&Ae)*Zc,t<Z)||(t=r[e+6],n+=(t&Ae)*Xc,t<Z)||(t=r[e+7],n+=(t&Ae)*Qc,t<Z))return n;throw new RangeError("Could not decode varint")}function O0(r,e){let t=r.get(e),n=0;if(n+=t&Ae,t<Z||(t=r.get(e+1),n+=(t&Ae)<<7,t<Z)||(t=r.get(e+2),n+=(t&Ae)<<14,t<Z)||(t=r.get(e+3),n+=(t&Ae)<<21,t<Z)||(t=r.get(e+4),n+=(t&Ae)*Yc,t<Z)||(t=r.get(e+5),n+=(t&Ae)*Zc,t<Z)||(t=r.get(e+6),n+=(t&Ae)*Xc,t<Z)||(t=r.get(e+7),n+=(t&Ae)*Qc,t<Z))return n;throw new RangeError("Could not decode varint")}function Gt(r,e,t=0){return e==null&&(e=_e(ye(r))),e instanceof Uint8Array?en(r,e,t):R0(r,e,t)}function ur(r,e=0){return r instanceof Uint8Array?Jc(r,e):O0(r,e)}var el=new Float32Array([-0]),jt=new Uint8Array(el.buffer);function Xd(r,e,t){el[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3]}function Qd(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],el[0]}var tl=new Float64Array([-0]),Ie=new Uint8Array(tl.buffer);function Jd(r,e,t){tl[0]=r,e[t]=Ie[0],e[t+1]=Ie[1],e[t+2]=Ie[2],e[t+3]=Ie[3],e[t+4]=Ie[4],e[t+5]=Ie[5],e[t+6]=Ie[6],e[t+7]=Ie[7]}function eh(r,e){return Ie[0]=r[e],Ie[1]=r[e+1],Ie[2]=r[e+2],Ie[3]=r[e+3],Ie[4]=r[e+4],Ie[5]=r[e+5],Ie[6]=r[e+6],Ie[7]=r[e+7],tl[0]}var N0=BigInt(Number.MAX_SAFE_INTEGER),F0=BigInt(Number.MIN_SAFE_INTEGER),$e=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return fr;if(e<N0&&e>F0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>th&&(o=0n,++n>th&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return fr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):fr}},fr=new $e(0,0);fr.toBigInt=function(){return 0n};fr.zzEncode=fr.zzDecode=function(){return this};fr.length=function(){return 1};var th=4294967296n;function rh(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 nh(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function rl(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Os(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var nl=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return Os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return Os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=Qd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=eh(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return nh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==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 $e(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=Os(this.buf,this.pos+=4),t=Os(this.buf,this.pos+=4);return new $e(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Jc(this.buf,this.pos);return this.pos+=ye(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 uo(r){return new nl(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=uo(r);return e.decode(n,void 0,t)}function ol(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return _e(i);o+i>e&&(n=_e(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var dr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function sl(){}var al=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},M0=ol();function B0(r){return globalThis.Buffer!=null?_e(r):M0(r)}var ho=class{len;head;tail;states;constructor(){this.len=0,this.head=new dr(sl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new dr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new cl((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(Ns,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(Ns,t.length(),t)}uint64Number(e){return this._push(en,ye(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=$e.fromBigInt(e).zzEncode();return this._push(Ns,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(Ns,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(il,1,e?1:0)}fixed32(e){return this._push(fo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(fo,4,t.lo)._push(fo,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(fo,4,t.lo)._push(fo,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(Xd,4,e)}double(e){return this._push(Jd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(il,1,0):this.uint32(t)._push(K0,t,e)}string(e){let t=rh(e);return t!==0?this.uint32(t)._push(rl,t,e):this._push(il,1,0)}fork(){return this.states=new al(this),this.head=this.tail=new dr(sl,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 dr(sl,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=B0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function il(r,e,t){e[t]=r&255}function U0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var cl=class extends dr{next;constructor(e,t){super(U0,e,t),this.next=void 0}};function Ns(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 fo(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 K0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ho.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(q0,e,r),this},ho.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push($0,e,r),this});function q0(r,e,t){e.set(r,t)}function $0(r,e,t){r.length<40?rl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function ll(){return new ho}function Re(r,e){let t=ll();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Oe(r,e,t){let n=uo(r);yield*e.stream(n,void 0,"$",t)}var Fs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ms(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function ul(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ms("enum",Fs.VARINT,t,n,o)}function Ne(r,e,t){return Ms("message",Fs.LENGTH_DELIMITED,r,e,t)}var je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},po=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var se;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(se||(se={}));var fl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(fl||(fl={}));(function(r){r.codec=()=>ul(fl)})(se||(se={}));var ht;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(ht||(ht={}));var dl;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(dl||(dl={}));function tn(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return bs(r)}var go={};Be(go,{MAX_RSA_KEY_SIZE:()=>hl,generateRSAKeyPair:()=>vl,jwkToJWKKeyPair:()=>lh,jwkToPkcs1:()=>W0,jwkToPkix:()=>yl,jwkToRSAPrivateKey:()=>El,pkcs1MessageToJwk:()=>ml,pkcs1MessageToRSAPrivateKey:()=>bl,pkcs1ToJwk:()=>H0,pkcs1ToRSAPrivateKey:()=>ch,pkixMessageToJwk:()=>gl,pkixMessageToRSAPublicKey:()=>xl,pkixToJwk:()=>G0,pkixToRSAPublicKey:()=>wl});var rn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=go.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return ah(this.jwk,t,e,n)}},mo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=go.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return ih(this.jwk,e,t)}};var hl=8192,pl=18,z0=1062,V0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function H0(r){let e=vt(r);return ml(e)}function ml(r){return{n:B(r[1],"base64url"),e:B(r[2],"base64url"),d:B(r[3],"base64url"),p:B(r[4],"base64url"),q:B(r[5],"base64url"),dp:B(r[6],"base64url"),dq:B(r[7],"base64url"),qi:B(r[8],"base64url"),kty:"RSA"}}function W0(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 P("JWK was missing components");return Je([De(Uint8Array.from([0])),De(D(r.n,"base64url")),De(D(r.e,"base64url")),De(D(r.d,"base64url")),De(D(r.p,"base64url")),De(D(r.q,"base64url")),De(D(r.dp,"base64url")),De(D(r.dq,"base64url")),De(D(r.qi,"base64url"))]).subarray()}function G0(r){let e=vt(r,{offset:0});return gl(e)}function gl(r){let e=vt(r[1],{offset:0});return{kty:"RSA",n:B(e[0],"base64url"),e:B(e[1],"base64url")}}function yl(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");return Je([V0,Wn(Je([De(D(r.n,"base64url")),De(D(r.e,"base64url"))]))]).subarray()}function ch(r){let e=vt(r);return bl(e)}function bl(r){let e=ml(r);return El(e)}function wl(r,e){if(r.byteLength>=z0)throw new Or("Key size is too large");let t=vt(r,{offset:0});return xl(t,r,e)}function xl(r,e,t){let n=gl(r);if(t==null){let o=zr(ht.encode({Type:se.RSA,Data:e}));t=ut(pl,o)}return new rn(n,t)}function El(r){if(fh(r)>hl)throw new P("Key size is too large");let e=lh(r),t=zr(ht.encode({Type:se.RSA,Data:yl(e.publicKey)})),n=ut(pl,t);return new mo(e.privateKey,new rn(e.publicKey,n))}async function vl(r){if(r>hl)throw new P("Key size is too large");let e=await uh(r),t=zr(ht.encode({Type:se.RSA,Data:yl(e.publicKey)})),n=ut(pl,t);return new mo(e.privateKey,new rn(e.publicKey,n))}function lh(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function uh(r,e){let t=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await j0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function ih(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function ah(r,e,t,n){let o=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function j0(r,e){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function fh(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return D(r.n,"base64url").length*8}var Bs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ps(e),qe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),_t(o)}update(e){return $r(this),this.iHash.update(e),this}digestInto(e){$r(this),ms(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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},dh=(()=>{let r=((e,t,n)=>new Bs(e,t).update(n).digest());return r.create=(e,t)=>new Bs(e,t),r})();var hh=(r,e)=>(r+(r>=0?e:-e)/ph)/e;function Y0(r,e,t){Wr("scalar",r,pt,t);let[[n,o],[s,i]]=e,a=hh(i*r,t),c=hh(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<pt,d=u<pt;f&&(l=-l),d&&(u=-u);let h=eo(Math.ceil(Gr(t)/2))+Yt;if(l<pt||l>=h||u<pt||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:d,k2:u}}function _l(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Sl(r,e){nt(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return tt(t.lowS,"lowS"),tt(t.prehash,"prehash"),t.format!==void 0&&_l(t.format),t}var Al=class extends Error{constructor(e=""){super(e)}},st={Err:Al,_tlv:{encode:(r,e)=>{let{Err:t}=st;if(rt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Qn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Qn(o.length/2|128):"";return Qn(r)+s+o+e},decode(r,e){let{Err:t}=st;e=W(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let 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}=st;if(Ss(r),r<pt)throw new e("integer: negative integers are not allowed");let t=Qn(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}=st;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 ir(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=st,o=W(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=st,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(st._tlv);Object.freeze(st._int);Object.freeze(st);var pt=BigInt(0),Yt=BigInt(1),ph=BigInt(2),Us=BigInt(3),Z0=BigInt(4);function mh(r,e={}){let t=Cs("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;nt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=yh(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(q,b,w){if(l&&b.is0())return Uint8Array.of(0);let{x:_,y:E}=b.toAffine(),x=n.toBytes(_);if(tt(w,"isCompressed"),w){f();let A=!n.isOdd(E);return he(gh(A),x)}else return he(Uint8Array.of(4),x,n.toBytes(E))}function h(q){W(q,void 0,"Point");let{publicKey:b,publicKeyUncompressed:w}=u,_=q.length,E=q[0],x=q.subarray(1);if(l&&_===1&&E===0)return{x:n.ZERO,y:n.ZERO};if(_===b&&(E===2||E===3)){let A=n.fromBytes(x);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let T=p(A),C;try{C=n.sqrt(T)}catch(H){let j=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}f();let O=n.isOdd(C);return(E&1)===1!==O&&(C=n.neg(C)),{x:A,y:C}}else if(_===w&&E===4){let A=n.BYTES,T=n.fromBytes(x.subarray(0,A)),C=n.fromBytes(x.subarray(A,A*2));if(!y(T,C))throw new Error("bad point: is not on curve");return{x:T,y:C}}else throw new Error(`bad point: got length ${_}, expected compressed=${b} or uncompressed=${w}`)}let m=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function p(q){let b=n.sqr(q),w=n.mul(b,q);return n.add(n.add(w,n.mul(q,s.a)),s.b)}function y(q,b){let w=n.sqr(b),_=p(q);return n.eql(w,_)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,Us),Z0),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function k(q,b,w=!1){if(!n.isValid(b)||w&&n.is0(b))throw new Error(`bad point coordinate ${q}`);return b}function L(q){if(!(q instanceof I))throw new Error("Weierstrass Point expected")}function U(q){if(!c||!c.basises)throw new Error("no endo");return Y0(q,c.basises,o.ORDER)}function R(q,b,w,_,E){return w=new I(n.mul(w.X,q),w.Y,w.Z),b=ro(_,b),w=ro(E,w),b.add(w)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,w,_){this.X=k("x",b),this.Y=k("y",w,!0),this.Z=k("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:w,y:_}=b||{};if(!b||!n.isValid(w)||!n.isValid(_))throw new Error("invalid affine point");if(b instanceof I)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(_)?I.ZERO:new I(w,_,n.ONE)}static fromBytes(b){let w=I.fromAffine(g(W(b,void 0,"point")));return w.assertValidity(),w}static fromHex(b){return I.fromBytes(Hr(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,w=!0){return Y.createCache(this,b),w||this.multiply(Us),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:w,y:_}=b.toAffine();if(!n.isValid(w)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!y(w,_))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){L(b);let{X:w,Y:_,Z:E}=this,{X:x,Y:A,Z:T}=b,C=n.eql(n.mul(w,T),n.mul(x,E)),O=n.eql(n.mul(_,T),n.mul(A,E));return C&&O}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:w}=s,_=n.mul(w,Us),{X:E,Y:x,Z:A}=this,T=n.ZERO,C=n.ZERO,O=n.ZERO,F=n.mul(E,E),H=n.mul(x,x),j=n.mul(A,A),$=n.mul(E,x);return $=n.add($,$),O=n.mul(E,A),O=n.add(O,O),T=n.mul(b,O),C=n.mul(_,j),C=n.add(T,C),T=n.sub(H,C),C=n.add(H,C),C=n.mul(T,C),T=n.mul($,T),O=n.mul(_,O),j=n.mul(b,j),$=n.sub(F,j),$=n.mul(b,$),$=n.add($,O),O=n.add(F,F),F=n.add(O,F),F=n.add(F,j),F=n.mul(F,$),C=n.add(C,F),j=n.mul(x,A),j=n.add(j,j),F=n.mul(j,$),T=n.sub(T,F),O=n.mul(j,H),O=n.add(O,O),O=n.add(O,O),new I(T,C,O)}add(b){L(b);let{X:w,Y:_,Z:E}=this,{X:x,Y:A,Z:T}=b,C=n.ZERO,O=n.ZERO,F=n.ZERO,H=s.a,j=n.mul(s.b,Us),$=n.mul(w,x),de=n.mul(_,A),pe=n.mul(E,T),me=n.add(w,_),le=n.add(x,A);me=n.mul(me,le),le=n.add($,de),me=n.sub(me,le),le=n.add(w,E);let Me=n.add(x,T);return le=n.mul(le,Me),Me=n.add($,pe),le=n.sub(le,Me),Me=n.add(_,E),C=n.add(A,T),Me=n.mul(Me,C),C=n.add(de,pe),Me=n.sub(Me,C),F=n.mul(H,le),C=n.mul(j,pe),F=n.add(C,F),C=n.sub(de,F),F=n.add(de,F),O=n.mul(C,F),de=n.add($,$),de=n.add(de,$),pe=n.mul(H,pe),le=n.mul(j,le),de=n.add(de,pe),pe=n.sub($,pe),pe=n.mul(H,pe),le=n.add(le,pe),$=n.mul(de,le),O=n.add(O,$),$=n.mul(Me,le),C=n.mul(me,C),C=n.sub(C,$),$=n.mul(me,de),F=n.mul(Me,F),F=n.add(F,$),new I(C,O,F)}subtract(b){return L(b),this.add(b.negate())}is0(){return this.equals(I.ZERO)}multiply(b){let{endo:w}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let _,E,x=A=>Y.cached(this,A,T=>lr(I,T));if(w){let{k1neg:A,k1:T,k2neg:C,k2:O}=U(b),{p:F,f:H}=x(T),{p:j,f:$}=x(O);E=H.add($),_=R(w.beta,F,j,A,C)}else{let{p:A,f:T}=x(b);_=A,E=T}return lr(I,[_,E])[0]}multiplyUnsafe(b){let{endo:w}=e,_=this,E=b;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===pt||_.is0())return I.ZERO;if(E===Yt)return _;if(Y.hasCache(this))return this.multiply(E);if(w){let{k1neg:x,k1:A,k2neg:T,k2:C}=U(E),{p1:O,p2:F}=Fd(I,_,A,C);return R(w.beta,O,F,x,T)}else return Y.unsafe(_,E)}toAffine(b){let w=this,_=b,{X:E,Y:x,Z:A}=w;if(n.eql(A,n.ONE))return{x:E,y:x};let T=w.is0();_==null&&(_=T?n.ONE:n.inv(A));let C=n.mul(E,_),O=n.mul(x,_),F=n.mul(A,_);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}isTorsionFree(){let{isTorsionFree:b}=e;return i===Yt?!0:b?b(I,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Yt?this:b?b(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Yt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return tt(b,"isCompressed"),this.assertValidity(),m(I,this,b)}toHex(b=!0){return Vr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let K=o.BITS,Y=new Zr(I,e.endo?Math.ceil(K/2):K);return K>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function gh(r){return Uint8Array.of(r?2:3)}function yh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function X0(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Xn:e.randomBytes,o=Object.assign(yh(r.Fp,t),{seed:Math.max(Nc(t.ORDER),16)});function s(h){try{let m=t.fromBytes(h);return t.isValidNot0(m)}catch{return!1}}function i(h,m){let{publicKey:g,publicKeyUncompressed:p}=o;try{let y=h.length;return m===!0&&y!==g||m===!1&&y!==p?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Fc(W(h,o.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(m)}function l(h){let{secretKey:m,publicKey:g,publicKeyUncompressed:p}=o,y=t._lengths;if(!sr(h))return;let v=W(h,void 0,"key").length,S=v===g||v===p,k=v===m||!!y?.includes(v);if(!(S&&k))return S}function u(h,m,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(h);return r.fromBytes(m).multiply(p).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ts(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function bh(r,e,t={}){let n=e;ps(n),nt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Xn:t.randomBytes,s=t.hmac===void 0?(E,x)=>dh(n,E,x):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:m}=X0(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*ph+Yt<i.ORDER;function y(E){let x=c>>Yt;return E>x}function v(E,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return x}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(E,x){_l(x);let A=m.signature,T=x==="compact"?A:x==="recovered"?A+1:void 0;return W(E,T)}class L{r;s;recovery;constructor(x,A,T){if(this.r=v("r",x),this.s=v("s",A),T!=null){if(S(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(x,A=g.format){k(x,A);let T;if(A==="der"){let{r:H,s:j}=st.toSig(W(x));return new L(H,j)}A==="recovered"&&(T=x[0],A="compact",x=x.subarray(1));let C=m.signature/2,O=x.subarray(0,C),F=x.subarray(C,C*2);return new L(a.fromBytes(O),a.fromBytes(F),T)}static fromHex(x,A){return this.fromBytes(Hr(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new L(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:T}=this,C=this.assertRecovery(),O=C===2||C===3?A+c:A;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(O),H=r.fromBytes(he(gh((C&1)===0),F)),j=a.inv(O),$=R(W(x,void 0,"msgHash")),de=a.create(-$*j),pe=a.create(T*j),me=r.BASE.multiplyUnsafe(de).add(H.multiplyUnsafe(pe));if(me.is0())throw new Error("invalid recovery: point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}toBytes(x=g.format){if(_l(x),x==="der")return Hr(st.hexFromSig(this));let{r:A,s:T}=this,C=a.toBytes(A),O=a.toBytes(T);return x==="recovered"?(S(),he(Uint8Array.of(this.assertRecovery()),C,O)):he(C,O)}toHex(x){return Vr(this.toBytes(x))}}Object.freeze(L.prototype),Object.freeze(L);let U=t.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let A=ir(x),T=x.length*8-l;return T>0?A>>BigInt(T):A}:t.bits2int,R=t.bits2int_modN===void 0?function(x){return a.create(U(x))}:t.bits2int_modN,I=eo(l);function K(E){return Wr("num < 2^"+l,E,pt,I),a.toBytes(E)}function Y(E,x){return W(E,void 0,"message"),x?W(n(E),void 0,"prehashed message"):E}function q(E,x,A){let{lowS:T,prehash:C,extraEntropy:O}=Sl(A,g);E=Y(E,C);let F=R(E),H=a.fromBytes(x);if(!a.isValidNot0(H))throw new Error("invalid private key");let j=[K(H),K(F)];if(O!=null&&O!==!1){let me=O===!0?o(m.secretKey):O;j.push(W(me,void 0,"extraEntropy"))}let $=he(...j),de=F;function pe(me){let le=U(me);if(!a.isValidNot0(le))return;let Me=a.inv(le),Rr=r.BASE.multiply(le).toAffine(),Rn=a.create(Rr.x);if(Rn===pt)return;let Xo=a.create(Me*a.create(de+Rn*H));if(Xo===pt)return;let wf=(Rr.x===Rn?0:2)|Number(Rr.y&Yt),xf=Xo;return T&&y(Xo)&&(xf=a.neg(Xo),wf^=1),new L(Rn,xf,p?void 0:wf)}return{seed:$,k2sig:pe}}function b(E,x,A={}){let{seed:T,k2sig:C}=q(E,x,A);return wd(n.outputLen,a.BYTES,s)(T,C).toBytes(A.format)}function w(E,x,A,T={}){let{lowS:C,prehash:O,format:F}=Sl(T,g);if(A=W(A,void 0,"publicKey"),x=Y(x,O),!sr(E)){let H=E instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+H)}k(E,F);try{let H=L.fromBytes(E,F),j=r.fromBytes(A);if(C&&H.hasHighS())return!1;let{r:$,s:de}=H,pe=R(x),me=a.inv(de),le=a.create(pe*me),Me=a.create($*me),Rr=r.BASE.multiplyUnsafe(le).add(j.multiplyUnsafe(Me));return Rr.is0()?!1:a.create(Rr.x)===$}catch{return!1}}function _(E,x,A={}){let{prehash:T}=Sl(A,g);return x=Y(x,T),L.fromBytes(E,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:m,Point:r,sign:b,verify:w,recoverPublicKey:_,Signature:L,hash:n})}var Cl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Q0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var wh=BigInt(2);function J0(r){let e=Cl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=oe(u,t,e)*u%e,d=oe(f,t,e)*u%e,h=oe(d,wh,e)*l%e,m=oe(h,o,e)*h%e,g=oe(m,s,e)*m%e,p=oe(g,a,e)*g%e,y=oe(p,c,e)*p%e,v=oe(y,a,e)*g%e,S=oe(v,t,e)*u%e,k=oe(S,i,e)*m%e,L=oe(k,n,e)*l%e,U=oe(L,wh,e);if(!Il.eql(Il.sqr(U),r))throw new Error("Cannot find square root");return U}var Il=jr(Cl.p,{sqrt:J0}),ey=mh(Cl,{Fp:Il,endo:Q0}),it=bh(ey,zr);function xh(r,e,t){let n=qr.digest(e instanceof Uint8Array?e:e.subarray());if(Jr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),it.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new so(String(o))});try{return it.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new so(String(o))}}function Eh(r,e,t,n){let o=qr.digest(t instanceof Uint8Array?t:t.subarray());if(Jr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),it.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new io(String(s))});try{return n?.signal?.throwIfAborted(),it.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new io(String(s))}}var yo=class{type="secp256k1";raw;_key;constructor(e){this._key=_h(e),this.raw=vh(this._key)}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return Eh(this._key,t,e,n)}},Ks=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Sh(e),this.publicKey=new yo(t??Ah(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return xh(this.raw,e,t)}};function Tl(r){return new yo(r)}async function Ih(){let r=ty();return new Ks(r)}function vh(r){return it.Point.fromBytes(r).toBytes()}function Sh(r){try{return it.getPublicKey(r,!0),r}catch(e){throw new Nn(String(e))}}function _h(r){try{return it.Point.fromBytes(r),r}catch(e){throw new Or(String(e))}}function Ah(r){try{return it.getPublicKey(r,!0)}catch(e){throw new Nn(String(e))}}function ty(){return it.utils.randomSecretKey()}async function Ch(r,e){if(r==="Ed25519")return Zd();if(r==="secp256k1")return Ih();if(r==="RSA")return vl(ry(e));if(r==="ECDSA")return nd(ny(e));throw new Nt}function nn(r,e){let{Type:t,Data:n}=ht.decode(r),o=n??new Uint8Array;switch(t){case se.RSA:return wl(o,e);case se.Ed25519:return jc(o);case se.secp256k1:return Tl(o);case se.ECDSA:return bc(o);default:throw new Nt}}function Th(r){let{Type:e,Data:t}=ht.decode(r.digest),n=t??new Uint8Array;switch(e){case se.Ed25519:return jc(n);case se.secp256k1:return Tl(n);case se.ECDSA:return bc(n);default:throw new Nt}}function Ge(r){return ht.encode({Type:se[r.type],Data:r.raw})}function ry(r){return r==null?2048:parseInt(r,10)}function ny(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 P("Unsupported curve, should be P-256, P-384 or P-521")}var Lh=Symbol.for("nodejs.util.inspect.custom"),oy=114,bo=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()})`}[as]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(oy,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Lh](){return`PeerId(${this.toString()})`}},wo=class extends bo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xo=class extends bo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Eo=class extends bo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},sy=2336,vo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Xe.digest(D(this.url))}[Lh](){return`PeerId(${this.url})`}[as]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(sy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=B(e)),e.toString()===this.toString())}};var iy=114,Ph=2336;function mt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Et(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return So(ue.parse(r));if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Et(e.decode(r))}return on(t)}function Ll(r){if(r.type==="Ed25519")return new xo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Eo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new wo({multihash:r.toCID().multihash,publicKey:r});throw new Nt}function Dh(r){return Ll(r.publicKey)}function on(r){if(cy(r))return new wo({multihash:r});if(ay(r))try{let e=Th(r);if(e.type==="Ed25519")return new xo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Eo({multihash:r,publicKey:e})}catch{let t=B(r.digest);return new vo(new URL(t))}throw new es("Supplied PeerID Multihash is invalid")}function So(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==iy&&r.code!==Ph)throw new Jo("Supplied PeerID CID is invalid");if(r.code===Ph){let e=B(r.multihash.digest);return new vo(new URL(e))}return on(r.multihash)}function ay(r){return r.code===Xe.code}function cy(r){return r.code===qr.code}async function kh(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new P("Private network is enforced, but no protector was provided");return r}function ly(r,e){if(typeof r=="string")return uy(r);if(typeof r=="number")return hy(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var qs=ly;function uy(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function fy(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function dy(r){let e=Math.abs(r);return e>=315576e5?hr(r,e,315576e5,"year"):e>=26298e5?hr(r,e,26298e5,"month"):e>=6048e5?hr(r,e,6048e5,"week"):e>=864e5?hr(r,e,864e5,"day"):e>=36e5?hr(r,e,36e5,"hour"):e>=6e4?hr(r,e,6e4,"minute"):e>=1e3?hr(r,e,1e3,"second"):`${r} ms`}function hy(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?dy(r):fy(r)}function hr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Pl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=qs,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u,f){let d,h=null,m,g;function p(...y){if(!p.enabled)return;let v=p,S=Number(new Date),k=S-(d||S);v.diff=k,v.prev=d,v.curr=S,d=S,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let L=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,I)=>{if(R==="%%")return"%";L++;let K=t.formatters[I];if(typeof K=="function"){let Y=y[L];R=K.call(v,Y),y.splice(L,1),L--}return R}),t.formatArgs.call(v,y),f?.onLog!=null&&f.onLog(...y),(v.log||t.log).apply(v,y)}return p.namespace=u,p.useColors=t.useColors(),p.color=t.selectColor(u),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(m!==t.namespaces&&(m=t.namespaces,g=t.enabled(u)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(p),p}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var $s=xy(),py=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function my(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function gy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+qs(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var yy=console.debug??console.log??(()=>{});function by(r){try{r?$s?.setItem("debug",r):$s?.removeItem("debug")}catch{}}function wy(){let r;try{r=$s?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function xy(){try{return localStorage}catch{}}function Ey(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Rh=Pl({formatArgs:gy,save:by,load:wy,useColors:my,setupFormatters:Ey,colors:py,storage:$s,log:yy});var Ke=Rh;Ke.formatters.b=r=>r==null?"undefined":te.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":sc.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();function Oh(r,e=""){let t=Nh(r.message),n=Nh(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var vm=Object.create;var Qo=Object.defineProperty;var Sm=Object.getOwnPropertyDescriptor;var _m=Object.getOwnPropertyNames;var Am=Object.getPrototypeOf,Im=Object.prototype.hasOwnProperty;var On=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Be=(r,e)=>{for(var t in e)Qo(r,t,{get:e[t],enumerable:!0})},vf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _m(e))!Im.call(r,o)&&o!==t&&Qo(r,o,{get:()=>e[o],enumerable:!(n=Sm(e,o))||n.enumerable});return r};var Ua=(r,e,t)=>(t=r!=null?vm(Am(r)):{},vf(e||!r||!r.__esModule?Qo(t,"default",{value:r,enumerable:!0}):t,r)),Cm=r=>vf(Qo({},"__esModule",{value:!0}),r);var Ul=On(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.Netmask4Impl=void 0;un.ip2long=ln;un.long2ip=gt;function gt(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Ry=48,Oy=97,Ny=65;function Fy(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Ry)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Oy)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Ny)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function ln(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,o]=Fy(r);r=r.substring(o),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 Bl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ln(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;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=(ln(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=gt(this.netLong),this.mask=gt(this.maskLong),this.hostmask=gt(~this.maskLong),this.first=this.bitmask<=30?gt(this.netLong+1):this.base,this.last=this.bitmask<=30?gt(this.netLong+this.size-2):gt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?gt(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):(ln(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(gt(this.netLong+this.size*e),this.mask)}forEach(e){let t=ln(this.first),n=ln(this.last),o=0;for(;t<=n;)e(gt(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};un.Netmask4Impl=Bl});var Xh=On(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.Netmask6Impl=void 0;fn.ip6bigint=ql;fn.bigint2ip6=xr;var My=Ul(),Kl=(1n<<128n)-1n;function ql(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),o=(0,My.ip2long)(n),s=r.substring(0,t+1)+"0:0";return Zh(s)&~0xffffffffn|BigInt(o)}return Zh(r)}function Zh(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.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 o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function xr(r){if(r<0n||r>Kl)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,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),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 $l=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):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=Kl>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=ql(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xr(this.netBigint),this.mask=xr(this.maskBigint),this.hostmask=xr(~this.maskBigint&Kl),this.first=this.base,this.last=xr(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):(ql(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(xr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(xr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};fn.Netmask6Impl=$l});var Qh=On(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.long2ip=Zt.ip2long=Zt.Netmask=void 0;var Zs=Ul();Object.defineProperty(Zt,"ip2long",{enumerable:!0,get:function(){return Zs.ip2long}});Object.defineProperty(Zt,"long2ip",{enumerable:!0,get:function(){return Zs.long2ip}});var By=Xh(),zl=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 By.Netmask6Impl(e,t):this._impl=new Zs.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 Zs.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()}};Zt.Netmask=zl});var im=On((H4,Zu)=>{"use strict";var Tw=Object.prototype.hasOwnProperty,Fe="~";function Go(){}Object.create&&(Go.prototype=Object.create(null),new Go().__proto__||(Fe=!1));function Lw(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function sm(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Lw(t,n||r,o),i=Fe?Fe+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function xa(r,e){--r._eventsCount===0?r._events=new Go:delete r._events[e]}function Le(){this._events=new Go,this._eventsCount=0}Le.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Tw.call(t,n)&&e.push(Fe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Le.prototype.listeners=function(e){var t=Fe?Fe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Le.prototype.listenerCount=function(e){var t=Fe?Fe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Le.prototype.emit=function(e,t,n,o,s,i){var a=Fe?Fe+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;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,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Le.prototype.on=function(e,t,n){return sm(this,e,t,n,!1)};Le.prototype.once=function(e,t,n){return sm(this,e,t,n,!0)};Le.prototype.removeListener=function(e,t,n,o){var s=Fe?Fe+e:e;if(!this._events[s])return this;if(!t)return xa(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&xa(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:xa(this,s)}return this};Le.prototype.removeAllListeners=function(e){var t;return e?(t=Fe?Fe+e:e,this._events[t]&&xa(this,t)):(this._events=new Go,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=Fe;Le.EventEmitter=Le;typeof Zu<"u"&&(Zu.exports=Le)});var lm=On((hL,cm)=>{cm.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var tx={};Be(tx,{createLibp2p:()=>Qw,dnsaddrResolver:()=>kr,isLibp2p:()=>ex});var Sf=Symbol.for("@libp2p/connection");var Ka=Symbol.for("@libp2p/content-routing");var Ze=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var P=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Nn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var er=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var tr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Nr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ot=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Jo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},es=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ts=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},rs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ns=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},wt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Fr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Fn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},os=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},ss=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Nt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var is=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var qa=Symbol.for("@libp2p/peer-discovery");var as=Symbol.for("@libp2p/peer-id");function Ft(r){return!!r?.[as]}var $a=Symbol.for("@libp2p/peer-routing");var za="keep-alive";function cs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function _f(...r){let e=[];for(let t of r)cs(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 Af(...r){let e=[];for(let t of r)cs(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 Mn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Mn||(Mn={}));function Tm(r){return typeof r?.handleEvent=="function"}function Lm(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Pe=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 o=Lm(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Tm(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Bn=Symbol.for("@libp2p/service-capabilities"),Va=Symbol.for("@libp2p/service-dependencies");var Ya={};Be(Ya,{base58btc:()=>te,base58flickr:()=>Fm});var Ux=new Uint8Array(0);function If(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 xt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Cf(r){return new TextEncoder().encode(r)}function Tf(r){return new TextDecoder().decode(r)}function Pm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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 g=0,p=0,y=0,v=m.length;y!==v&&m[y]===0;)y++,g++;for(var S=(v-y)*u+1>>>0,k=new Uint8Array(S);y!==v;){for(var L=m[y],U=0,R=S-1;(L!==0||U<p)&&R!==-1;R--,U++)L+=256*k[R]>>>0,k[R]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");p=U,y++}for(var I=S-p;I!==S&&k[I]===0;)I++;for(var K=c.repeat(g);I<S;++I)K+=r.charAt(k[I]);return K}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var g=0;if(m[g]!==" "){for(var p=0,y=0;m[g]===c;)p++,g++;for(var v=(m.length-g)*l+1>>>0,S=new Uint8Array(v);m[g];){var k=t[m.charCodeAt(g)];if(k===255)return;for(var L=0,U=v-1;(k!==0||L<y)&&U!==-1;U--,L++)k+=a*S[U]>>>0,S[U]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");y=L,g++}if(m[g]!==" "){for(var R=v-y;R!==v&&S[R]===0;)R++;for(var I=new Uint8Array(p+(v-R)),K=p;R!==v;)I[K++]=S[R++];return I}}}function h(m){var g=d(m);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Dm=Pm,km=Dm,Pf=km;var Ha=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")}},Wa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Df(this,e)}},Ga=class{decoders;constructor(e){this.decoders=e}or(e){return Df(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 Df(r,e){return new Ga({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ja=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ha(e,t,n),this.decoder=new Wa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Mr({name:r,prefix:e,encode:t,decode:n}){return new ja(r,e,t,n)}function Mt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Pf(t,r);return Mr({prefix:e,name:r,encode:n,decode:s=>xt(o(s))})}function Rm(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++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,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Om(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Nm(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ie({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Nm(n);return Mr({prefix:e,name:r,encode(s){return Om(s,n,t)},decode(s){return Rm(s,o,t,r)}})}var te=Mt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fm=Mt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Za={};Be(Za,{base32:()=>We,base32hex:()=>Km,base32hexpad:()=>$m,base32hexpadupper:()=>zm,base32hexupper:()=>qm,base32pad:()=>Bm,base32padupper:()=>Um,base32upper:()=>Mm,base32z:()=>Vm});var We=ie({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mm=ie({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bm=ie({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Um=ie({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Km=ie({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qm=ie({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$m=ie({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zm=ie({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vm=ie({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xa={};Be(Xa,{base36:()=>Un,base36upper:()=>Hm});var Un=Mt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hm=Mt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wm=Of,kf=128,Gm=127,jm=~Gm,Ym=Math.pow(2,31);function Of(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ym;)e[t++]=r&255|kf,r/=128;for(;r&jm;)e[t++]=r&255|kf,r>>>=7;return e[t]=r|0,Of.bytes=t-n+1,e}var Zm=Qa,Xm=128,Rf=127;function Qa(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Rf)<<o:(i&Rf)*Math.pow(2,o),o+=7}while(i>=Xm);return Qa.bytes=s-n,t}var Qm=Math.pow(2,7),Jm=Math.pow(2,14),eg=Math.pow(2,21),tg=Math.pow(2,28),rg=Math.pow(2,35),ng=Math.pow(2,42),og=Math.pow(2,49),sg=Math.pow(2,56),ig=Math.pow(2,63),ag=function(r){return r<Qm?1:r<Jm?2:r<eg?3:r<tg?4:r<rg?5:r<ng?6:r<og?7:r<sg?8:r<ig?9:10},cg={encode:Wm,decode:Zm,encodingLength:ag},lg=cg,Kn=lg;function qn(r,e=0){return[Kn.decode(r,e),Kn.decode.bytes]}function Br(r,e,t=0){return Kn.encode(r,e,t),e}function Ur(r){return Kn.encodingLength(r)}function ut(r,e){let t=e.byteLength,n=Ur(r),o=n+Ur(t),s=new Uint8Array(o+t);return Br(r,s,0),Br(t,s,n),s.set(e,o),new Kr(r,t,e,s)}function Et(r){let e=xt(r),[t,n]=qn(e),[o,s]=qn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Kr(t,o,i,e)}function Nf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&If(r.bytes,t.bytes)}}var Kr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Ff(r,e){let{bytes:t,version:n}=r;return n===0?fg(t,Ja(r),e??te.encoder):dg(t,Ja(r),e??We.encoder)}var Mf=new WeakMap;function Ja(r){let e=Mf.get(r);if(e==null){let t=new Map;return Mf.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==$n)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==hg)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&&Nf(e.multihash,n.multihash)}toString(e){return Ff(this,e)}toJSON(){return{"/":Ff(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Bf(n,o,s.bytes))}else if(t[pg]===!0){let{version:n,multihash:o,code:s}=t,i=Et(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==$n)throw new Error(`Version 0 CID must use dag-pb (code: ${$n}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Bf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,$n,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=xt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Kr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=qn(e.subarray(t));return t+=d,f},o=n(),s=$n;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=ug(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ja(s).set(n,e),s}};function ug(r,e){switch(r[0]){case"Q":{let t=e??te;return[te.prefix,t.decode(`${te.prefix}${r}`)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Un.prefix:{let t=e??Un;return[Un.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 fg(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function dg(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var $n=112,hg=18;function Bf(r,e,t){let n=Ur(r),o=n+Ur(e),s=new Uint8Array(o+t.byteLength);return Br(r,s,0),Br(e,s,n),s.set(t,o),s}var pg=Symbol.for("@ipld/js-cid/CID");var ec={};Be(ec,{identity:()=>Xe});var Uf=0,mg="identity",Kf=xt;function gg(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(Uf,Kf(r))}var Xe={code:Uf,name:mg,encode:Kf,digest:gg};function Q(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}async function qf(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 $f(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function zf(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}function ae(r=0){return new Uint8Array(r)}function _e(r=0){return new Uint8Array(r)}function Qe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=_e(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Hf=Symbol.for("@achingbrain/uint8arraylist");function Vf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function us(r){return!!r?.[Hf]}var J=class r{bufs;length;[Hf]=!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(us(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(us(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=Vf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Vf(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(us(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Qe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Qe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(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(!us(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}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=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var tc={};Be(tc,{base10:()=>yg});var yg=Mt({prefix:"9",name:"base10",alphabet:"0123456789"});var rc={};Be(rc,{base16:()=>bg,base16upper:()=>wg});var bg=ie({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wg=ie({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var nc={};Be(nc,{base2:()=>xg});var xg=ie({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oc={};Be(oc,{base256emoji:()=>Ag});var Wf=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}"),Eg=Wf.reduce((r,e,t)=>(r[t]=e,r),[]),vg=Wf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Sg(r){return r.reduce((e,t)=>(e+=Eg[t],e),"")}function _g(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=vg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Ag=Mr({prefix:"\u{1F680}",name:"base256emoji",encode:Sg,decode:_g});var ac={};Be(ac,{base64:()=>sc,base64pad:()=>Ig,base64url:()=>ic,base64urlpad:()=>Cg});var sc=ie({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ig=ie({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ic=ie({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cg=ie({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cc={};Be(cc,{base8:()=>Tg});var Tg=ie({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lc={};Be(lc,{identity:()=>Lg});var Lg=Mr({prefix:"\0",name:"identity",encode:r=>Tf(r),decode:r=>Cf(r)});var SE=new TextEncoder,_E=new TextDecoder;var dc={};Be(dc,{sha256:()=>qr,sha512:()=>Rg});var kg=20;function fc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new uc(r,e,t,n,o)}var uc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??kg,this.maxDigestLength=s}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?Gf(n,this.code,t?.truncate):n.then(o=>Gf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gf(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 Yf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var qr=fc({name:"sha2-256",code:18,encode:Yf("SHA-256")}),Rg=fc({name:"sha2-512",code:19,encode:Yf("SHA-512")});var zn={...lc,...nc,...cc,...tc,...rc,...Za,...Xa,...Ya,...ac,...oc},FE={...dc,...ec};function Xf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Zf=Xf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),hc=Xf("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=_e(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Og={utf8:Zf,"utf-8":Zf,hex:zn.base16,latin1:hc,ascii:hc,binary:hc,...zn},fs=Og;function D(r,e="utf8"){let t=fs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function B(r,e="utf8"){let t=fs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ng=parseInt("11111",2),pc=parseInt("10000000",2),Fg=parseInt("01111111",2),Qf={0:Vn,1:Vn,2:Mg,3:Kg,4:qg,5:Ug,6:Bg,16:Vn,22:Vn,48:Vn};function vt(r,e={offset:0}){let t=r[e.offset]&Ng;if(e.offset++,Qf[t]!=null)return Qf[t](r,e);throw new Error("No decoder for tag "+t)}function Hn(r,e){let t=0;if((r[e.offset]&pc)===pc){let n=r[e.offset]&Fg,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Vn(r,e){Hn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=vt(r,e);if(n===null)break;t.push(n)}return t}function Mg(r,e){let t=Hn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Bg(r,e){let t=Hn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ug(r,e){return e.offset++,null}function Kg(r,e){let t=Hn(r,e),n=r[e.offset];e.offset++;let o=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 o}function qg(r,e){let t=Hn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function $g(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 ds(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=$g(r.byteLength);return new J(Uint8Array.from([e.byteLength|pc]),e)}function De(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]),ds(e),e)}function Wn(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),ds(t),t)}function Jf(r){return new J(Uint8Array.from([4]),ds(r),r)}function Je(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),ds(t),t)}var zg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Vg=Uint8Array.from([6,5,43,129,4,0,34]),Hg=Uint8Array.from([6,5,43,129,4,0,35]),Wg={ext:!0,kty:"EC",crv:"P-256"},Gg={ext:!0,kty:"EC",crv:"P-384"},jg={ext:!0,kty:"EC",crv:"P-521"},mc=32,gc=48,yc=66;function bc(r){let e=vt(r);return ed(e)}function ed(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===mc*2+1)return n=B(e.subarray(t,t+mc),"base64url"),o=B(e.subarray(t+mc),"base64url"),new rr({...Wg,key_ops:["verify"],x:n,y:o});if(e.byteLength===gc*2+1)return n=B(e.subarray(t,t+gc),"base64url"),o=B(e.subarray(t+gc),"base64url"),new rr({...Gg,key_ops:["verify"],x:n,y:o});if(e.byteLength===yc*2+1)return n=B(e.subarray(t,t+yc),"base64url"),o=B(e.subarray(t+yc),"base64url"),new rr({...jg,key_ops:["verify"],x:n,y:o});throw new P(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function td(r){return Je([De(Uint8Array.from([1])),Jf(D(r.d??"","base64url")),Je([nd(r.crv)],160),Je([Wn(new J(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function rd(r){return Je([De(Uint8Array.from([1])),Je([nd(r.crv)],160),Je([Wn(new J(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function nd(r){if(r==="P-256")return zg;if(r==="P-384")return Vg;if(r==="P-521")return Hg;throw new P(`Invalid curve ${r}`)}async function od(r="P-256"){let e=await qf(r);return new hs(e.privateKey)}var rr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=rd(this.jwk)),this._raw}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return zf(this.jwk,t,e,n)}},hs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new rr({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=td(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async sign(e,t){return $f(this.jwk,e,t)}};function wc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ut(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function qe(r,e,t=""){let n=wc(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function ps(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ut(r.outputLen),Ut(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function $r(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ms(r,e){qe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function _t(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function gs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function et(r,e){return r<<32-e|r>>>e}var id=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ys(r){if(qe(r),id)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Yg[r[t]];return e}var St={_0:48,_9:57,A:65,F:70,a:97,f:102};function sd(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function Gn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(id)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}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 o=0,s=0;o<t;o++,s+=2){let i=sd(r.charCodeAt(s)),a=sd(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function xc(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];qe(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ec(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function bs(r=32){Ut(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 vc=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ad(r,e,t){return r&e^~r&t}function cd(r,e,t){return r&e^r&t^e&t}var jn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=gs(this.buffer)}update(e){$r(this),qe(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$r(this),ms(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,_t(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},At=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ws=BigInt(4294967295),ld=BigInt(32);function Zg(r,e=!1){return e?{h:Number(r&ws),l:Number(r>>ld&ws)}:{h:Number(r>>ld&ws)|0,l:Number(r&ws)|0}}function ud(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Zg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Sc=(r,e,t)=>r>>>t,_c=(r,e,t)=>r<<32-t|e>>>t,nr=(r,e,t)=>r>>>t|e<<32-t,or=(r,e,t)=>r<<32-t|e>>>t,Yn=(r,e,t)=>r<<64-t|e>>>t-32,Zn=(r,e,t)=>r>>>t-32|e<<64-t;function ft(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var fd=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),dd=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,hd=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),pd=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,md=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),gd=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Qg=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]),Kt=new Uint32Array(64),Ac=class extends jn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Kt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Kt[f-15],h=Kt[f-2],m=et(d,7)^et(d,18)^d>>>3,g=et(h,17)^et(h,19)^h>>>10;Kt[f]=g+Kt[f-7]+m+Kt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=et(a,6)^et(a,11)^et(a,25),h=u+d+ad(a,c,l)+Qg[f]+Kt[f]|0,g=(et(n,2)^et(n,13)^et(n,22))+cd(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){_t(Kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_t(this.buffer)}},Ic=class extends Ac{A=At[0]|0;B=At[1]|0;C=At[2]|0;D=At[3]|0;E=At[4]|0;F=At[5]|0;G=At[6]|0;H=At[7]|0;constructor(){super(32)}};var yd=ud(["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))),Jg=yd[0],e0=yd[1],qt=new Uint32Array(80),$t=new Uint32Array(80),Cc=class extends jn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:g,Hl:p}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,p]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,p){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=p|0}process(e,t){for(let S=0;S<16;S++,t+=4)qt[S]=e.getUint32(t),$t[S]=e.getUint32(t+=4);for(let S=16;S<80;S++){let k=qt[S-15]|0,L=$t[S-15]|0,U=nr(k,L,1)^nr(k,L,8)^Sc(k,L,7),R=or(k,L,1)^or(k,L,8)^_c(k,L,7),I=qt[S-2]|0,K=$t[S-2]|0,Y=nr(I,K,19)^Yn(I,K,61)^Sc(I,K,6),q=or(I,K,19)^Zn(I,K,61)^_c(I,K,6),b=hd(R,q,$t[S-7],$t[S-16]),w=pd(b,U,Y,qt[S-7],qt[S-16]);qt[S]=w|0,$t[S]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:g,Gl:p,Hh:y,Hl:v}=this;for(let S=0;S<80;S++){let k=nr(f,d,14)^nr(f,d,18)^Yn(f,d,41),L=or(f,d,14)^or(f,d,18)^Zn(f,d,41),U=f&h^~f&g,R=d&m^~d&p,I=md(v,L,R,e0[S],$t[S]),K=gd(I,y,k,U,Jg[S],qt[S]),Y=I|0,q=nr(n,o,28)^Yn(n,o,34)^Yn(n,o,39),b=or(n,o,28)^Zn(n,o,34)^Zn(n,o,39),w=n&s^n&a^s&a,_=o&i^o&c^i&c;y=g|0,v=p|0,g=h|0,p=m|0,h=f|0,m=d|0,{h:f,l:d}=ft(l|0,u|0,K|0,Y|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=fd(Y,b,_);n=dd(E,K,q,w),o=E|0}({h:n,l:o}=ft(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ft(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ft(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ft(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ft(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=ft(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:p}=ft(this.Gh|0,this.Gl|0,g|0,p|0),{h:y,l:v}=ft(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,l,u,f,d,h,m,g,p,y,v)}roundClean(){_t(qt,$t)}destroy(){this.destroyed=!0,_t(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Tc=class extends Cc{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var zr=Ec(()=>new Ic,vc(1));var xs=Ec(()=>new Tc,vc(3));var H=(r,e,t)=>qe(r,e,t),Pc=Ut,Vr=ys,he=(...r)=>xc(...r),Hr=r=>Gn(r),sr=wc,Xn=r=>bs(r),vs=BigInt(0),Lc=BigInt(1);function tt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Ss(r){if(typeof r=="bigint"){if(!Es(r))throw new RangeError("positive bigint expected, got "+r)}else Pc(r);return r}function rt(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 Qn(r){let e=Ss(r).toString(16);return e.length&1?"0"+e:e}function bd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?vs:BigInt("0x"+r)}function ir(r){return bd(ys(r))}function dt(r){return bd(ys(Jn(qe(r)).reverse()))}function _s(r,e){if(Ut(e),e===0)throw new RangeError("zero length");r=Ss(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Gn(t.padStart(e*2,"0"))}function Dc(r,e){return _s(r,e).reverse()}function wd(r,e){if(r=H(r),e=H(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Jn(r){return Uint8Array.from(H(r))}function As(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Es=r=>typeof r=="bigint"&&vs<=r;function t0(r,e,t){return Es(r)&&Es(e)&&Es(t)&&e<=r&&r<t}function Wr(r,e,t,n){if(!t0(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Gr(r){if(r<vs)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>vs;r>>=Lc,e+=1);return e}var eo=r=>(Lc<<BigInt(r))-Lc;function xd(r,e,t){if(Ut(r,"hashLen"),Ut(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...p)=>t(l,he(c,...p)),h=(p=o)=>{l=d(s,p),c=d(),p.length!==0&&(l=d(i,p),c=d())},m=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,y=[];for(;p<e;){c=d();let v=c.slice();y.push(v),p+=c.length}return he(...y)};return(p,y)=>{f(),h(p);let v;for(;(v=y(m()))===void 0;)h();return f(),v}}function nt(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var kc=()=>{throw new Error("not implemented")};var Ee=BigInt(0),ce=BigInt(1),ar=BigInt(2),_d=BigInt(3),Ad=BigInt(4),Id=BigInt(5),r0=BigInt(7),Cd=BigInt(8),n0=BigInt(9),Td=BigInt(16);function fe(r,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Ee?t:e+t}function oe(r,e,t){if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Ee;)n*=n,n%=t;return n}function Ed(r,e){if(r===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let t=fe(r,e),n=e,o=Ee,s=ce,i=ce,a=Ee;for(;t!==Ee;){let l=n/t,u=n-t*l,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==ce)throw new Error("invert: does not exist");return fe(o,e)}function Rc(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Ld(r,e){let t=r,n=(t.ORDER+ce)/Ad,o=t.pow(e,n);return Rc(t,o,e),o}function o0(r,e){let t=r,n=(t.ORDER-Id)/Cd,o=t.mul(e,ar),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,ar),s),c=t.mul(i,t.sub(a,t.ONE));return Rc(t,c,e),c}function s0(r){let e=jr(r),t=Pd(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+r0)/Td;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),d=l.mul(u,o),h=l.mul(u,s),m=l.eql(l.sqr(f),c),g=l.eql(l.sqr(d),c);u=l.cmov(u,f,m),f=l.cmov(h,d,g);let p=l.eql(l.sqr(f),c),y=l.cmov(u,f,p);return Rc(l,y,c),y})}function Pd(r){if(r<_d)throw new Error("sqrt is not defined for small field");let e=r-ce,t=0;for(;e%ar===Ee;)e/=ar,t++;let n=ar,o=jr(r);for(;vd(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ld;let s=o.pow(n,e),i=(e+ce)/ar;return function(c,l){let u=c;if(u.is0(l))return l;if(vd(u,l)!==1)throw new Error("Cannot find square root");let f=t,d=u.mul(u.ONE,s),h=u.pow(l,e),m=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let g=1,p=u.sqr(h);for(;!u.eql(p,u.ONE);)if(g++,p=u.sqr(p),g===f)throw new Error("Cannot find square root");let y=ce<<BigInt(f-g-1),v=u.pow(d,y);f=g,d=u.sqr(v),h=u.mul(h,d),m=u.mul(m,v)}return m}}function i0(r){return r%Ad===_d?Ld:r%Cd===Id?o0:r%Td===n0?s0(r):Pd(r)}var It=(r,e)=>(fe(r,e)&ce)===ce,a0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=a0.reduce((n,o)=>(n[o]="function",n),e);if(nt(r,t),rt(r.BYTES,"BYTES"),rt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ce)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function c0(r,e,t){let n=r;if(t<Ee)throw new Error("invalid exponent, negatives unsupported");if(t===Ee)return n.ONE;if(t===ce)return e;let o=n.ONE,s=e;for(;t>Ee;)t&ce&&(o=n.mul(o,s)),s=n.sqr(s),t>>=ce;return o}function to(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function vd(r,e){let t=r,n=(t.ORDER-ce)/ar,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function l0(r,e){if(e!==void 0&&Pc(e),r<=Ee)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=Gr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Sd=new WeakMap,Is=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=ce;_lengths;_mod;constructor(e,t={}){if(e<=ce)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:o,nByteLength:s}=l0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ce)===ce}neg(e){return fe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return fe(e*e,this.ORDER)}add(e,t){return fe(e+t,this.ORDER)}sub(e,t){return fe(e-t,this.ORDER)}mul(e,t){return fe(e*t,this.ORDER)}pow(e,t){return c0(this,e,t)}div(e,t){return fe(e*Ed(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 Ed(e,this.ORDER)}sqrt(e){let t=Sd.get(this);return t||Sd.set(this,t=i0(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Dc(e,this.BYTES):_s(e,this.BYTES)}fromBytes(e,t=!1){H(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?dt(e):ir(e);if(a&&(c=fe(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return to(this,e)}cmov(e,t,n){return tt(n,"condition"),n?t:e}};Object.freeze(Is.prototype);function jr(r,e={}){return new Is(r,e)}function Dd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ce)throw new Error("field order must be greater than 1");let e=Gr(r-ce);return Math.ceil(e/8)}function Nc(r){let e=Dd(r);return e+Math.ceil(e/2)}function Fc(r,e,t=!1){H(r);let n=r.length,o=Dd(e),s=Math.max(Nc(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?dt(r):ir(r),a=fe(i,e-ce)+ce;return t?Dc(a,o):_s(a,o)}var Yr=BigInt(0),cr=BigInt(1);function ro(r,e){let t=e.negate();return r?t:e}function lr(r,e){let t=to(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Nd(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Mc(r,e){Nd(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=eo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function kd(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=cr);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var Bc=new WeakMap,Fd=new WeakMap;function Uc(r){return Fd.get(r)||1}function Rd(r){if(r!==Yr)throw new Error("invalid wNAF")}var Zr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Yr;)t&cr&&(n=n.add(o)),o=o.double(),t>>=cr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Mc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Mc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=kd(n,a,i);n=c,u?s=s.add(ro(d,t[h])):o=o.add(ro(f,t[l]))}return Rd(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Mc(e,this.bits);for(let i=0;i<s.windows&&n!==Yr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=kd(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return Rd(n),o}getPrecomputes(e,t,n){let o=Bc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Bc.set(t,o))),o}cached(e,t,n){let o=Uc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Uc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Nd(t,this.bits),Fd.set(e,t),Bc.delete(e)}hasCache(e){return Uc(e)!==1}};function Md(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Yr||n>Yr;)t&cr&&(s=s.add(o)),n&cr&&(i=i.add(o)),o=o.double(),t>>=cr,n>>=cr;return{p1:s,p2:i}}function Od(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oc(e),e}else return jr(r,{isLE:t})}function Cs(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Yr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Od(e.p,t.Fp,n),s=Od(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function Ts(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var zt=BigInt(0),ge=BigInt(1),Kc=BigInt(2),u0=BigInt(8);function f0(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Bd(r,e={}){let t=e,n=Cs("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;nt(t,{},{uvRatio:"function"});let c=Kc<<BigInt(s.BYTES*8)-ge,l=g=>o.create(g),u=t.uvRatio===void 0?(g,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,p))}}catch{return{isValid:!1,value:zt}}}:t.uvRatio;if(!f0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,p,y=!1){let v=y?ge:zt;return Wr("coordinate "+g,p,v,c),p}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ge,l(i.Gx*i.Gy));static ZERO=new h(zt,ge,ge,zt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,y,v,S){this.X=f("x",p),this.Y=f("y",y),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof h)throw new Error("extended point not allowed");let{x:y,y:v}=p||{};return f("x",y),f("y",v),new h(y,v,ge,l(y*v))}static fromBytes(p,y=!1){let v=o.BYTES,{a:S,d:k}=i;p=Jn(H(p,v,"point")),tt(y,"zip215");let L=Jn(p),U=p[v-1];L[v-1]=U&-129;let R=dt(L),I=y?c:o.ORDER;Wr("point.y",R,zt,I);let K=l(R*R),Y=l(K-ge),q=l(k*K-S),{isValid:b,value:w}=u(Y,q);if(!b)throw new Error("bad point: invalid y coordinate");let _=(w&ge)===ge,E=(U&128)!==0;if(!y&&w===zt&&E)throw new Error("bad point: x=0 and x_0=1");return E!==_&&(w=l(-w)),h.fromAffine({x:w,y:R})}static fromHex(p,y=!1){return h.fromBytes(Hr(p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return m.createCache(this,p),y||this.multiply(Kc),this}assertValidity(){let p=this,{a:y,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:k,Z:L,T:U}=p,R=l(S*S),I=l(k*k),K=l(L*L),Y=l(K*K),q=l(R*y),b=l(K*l(q+I)),w=l(Y+l(v*l(R*I)));if(b!==w)throw new Error("bad point: equation left != right (1)");let _=l(S*k),E=l(L*U);if(_!==E)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:y,Y:v,Z:S}=this,{X:k,Y:L,Z:U}=p,R=l(y*U),I=l(k*S),K=l(v*U),Y=l(L*S);return R===I&&K===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:p}=i,{X:y,Y:v,Z:S}=this,k=l(y*y),L=l(v*v),U=l(Kc*l(S*S)),R=l(p*k),I=y+v,K=l(l(I*I)-k-L),Y=R+L,q=Y-U,b=R-L,w=l(K*q),_=l(Y*b),E=l(K*b),x=l(q*Y);return new h(w,_,x,E)}add(p){d(p);let{a:y,d:v}=i,{X:S,Y:k,Z:L,T:U}=this,{X:R,Y:I,Z:K,T:Y}=p,q=l(S*R),b=l(k*I),w=l(U*v*Y),_=l(L*K),E=l((S+k)*(R+I)-q-b),x=_-w,A=_+w,T=l(b-y*q),C=l(E*x),O=l(A*T),F=l(E*T),V=l(x*A);return new h(C,O,V,F)}subtract(p){return d(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=m.cached(this,p,S=>lr(h,S));return lr(h,[y,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===zt?h.ZERO:this.is0()||p===ge?this:m.unsafe(this,p,y=>lr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(p){let y=this,v=p,{X:S,Y:k,Z:L}=y,U=y.is0();v==null&&(v=U?u0:o.inv(L));let R=l(S*v),I=l(k*v),K=o.mul(L,v);if(U)return{x:zt,y:ge};if(K!==ge)throw new Error("invZ was invalid");return{x:R,y:I}}clearCofactor(){return a===ge?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=p&ge?128:0,v}toHex(){return Vr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Zr(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Ls=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){kc()}static fromHex(e){kc()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Vr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Ud(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;nt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(rt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Xn:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,w,_)=>{if(tt(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function m(b){return c.create(dt(b))}function g(b){let w=R.secretKey;H(b,R.secretKey,"secretKey");let _=H(n(b),2*w,"hashedSecretKey"),E=d(_.slice(0,w)),x=_.slice(w,2*w),A=m(E);return{head:E,prefix:x,scalar:A}}function p(b){let{head:w,prefix:_,scalar:E}=g(b),x=i.multiply(E),A=x.toBytes();return{head:w,prefix:_,scalar:E,point:x,pointBytes:A}}function y(b){return p(b).pointBytes}function v(b=Uint8Array.of(),...w){let _=he(...w);return m(n(h(_,H(b,void 0,"context"),!!s)))}function S(b,w,_={}){b=H(b,void 0,"message"),s&&(b=s(b));let{prefix:E,scalar:x,pointBytes:A}=p(w),T=v(_.context,E,b),C=i.multiply(T).toBytes(),O=v(_.context,C,A,b),F=c.create(T+O*x);if(!c.isValid(F))throw new Error("sign failed: invalid s");let V=he(C,c.toBytes(F));return H(V,R.signature,"result")}let k={zip215:o.zip215};function L(b,w,_,E=k){let{context:x}=E,A=E.zip215===void 0?!!k.zip215:E.zip215,T=R.signature;b=H(b,T,"signature"),w=H(w,void 0,"message"),_=H(_,R.publicKey,"publicKey"),A!==void 0&&tt(A,"zip215"),s&&(w=s(w));let C=T/2,O=b.subarray(0,C),F=dt(b.subarray(C,T)),V,j,$;try{V=r.fromBytes(_,A),j=r.fromBytes(O,A),$=i.multiplyUnsafe(F)}catch{return!1}if(!A&&V.isSmallOrder())return!1;let de=v(x,O,_,w);return j.add(V.multiplyUnsafe(de)).subtract($).clearCofactor().is0()}let U=a.BYTES,R={secretKey:U,publicKey:U,signature:2*U,seed:U};function I(b){return b=b===void 0?f(R.seed):b,H(b,R.seed,"seed")}function K(b){return sr(b)&&b.length===R.secretKey}function Y(b,w){try{return!!r.fromBytes(b,w===void 0?k.zip215:w)}catch{return!1}}let q={getExtendedPublicKey:p,randomSecretKey:I,isValidSecretKey:K,isValidPublicKey:Y,toMontgomery(b){let{y:w}=r.fromBytes(b),_=R.publicKey,E=_===32;if(!E&&_!==57)throw new Error("only defined for 25519 and 448");let x=E?a.div(ge+w,ge-w):a.div(w-ge,w+ge);return a.toBytes(x)},toMontgomerySecret(b){let w=R.secretKey;H(b,w);let _=n(b.subarray(0,w));return d(_).subarray(0,w)}};return Object.freeze(R),Object.freeze(q),Object.freeze({keygen:Ts(I,y),getPublicKey:y,sign:S,verify:L,utils:q,Point:r,lengths:R})}function no(r,e){if(rt(r),rt(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function d0(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function h0(r){if(!sr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?As(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function qc(r,e,t,n){H(r),rt(t),e=h0(e),e.length>255&&(e=n(he(As("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=he(e,no(e.length,1)),c=new Uint8Array(s),l=no(t,2),u=new Array(i),f=n(he(c,r,l,no(0,1),a));u[0]=n(he(f,no(1,1),a));for(let h=1;h<i;h++){let m=[d0(f,u[h-1]),no(h+1,1),a];u[h]=n(he(...m))}return he(...u).slice(0,t)}var Kd="HashToScalar-";var p0=BigInt(0),Ct=BigInt(1),qd=BigInt(2);var m0=BigInt(5),g0=BigInt(8),Xr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Hc={p:Xr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:g0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function y0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Xr,a=r*r%s*r%s,c=oe(a,qd,s)*a%s,l=oe(c,Ct,s)*r%s,u=oe(l,m0,s)*l%s,f=oe(u,e,s)*u%s,d=oe(f,t,s)*f%s,h=oe(d,n,s)*d%s,m=oe(h,o,s)*h%s,g=oe(m,o,s)*h%s,p=oe(g,e,s)*u%s;return{pow_p_5_8:oe(p,qd,s)*r%s,b2:a}}function b0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var $c=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Wc(r,e){let t=Xr,n=fe(e*e*e,t),o=fe(n*n*e,t),s=y0(r*o).pow_p_5_8,i=fe(r*n*s,t),a=fe(e*i*i,t),c=i,l=fe(i*$c,t),u=a===r,f=a===fe(-r,t),d=a===fe(-r*$c,t);return u&&(i=c),(f||d)&&(i=l),It(i,t)&&(i=fe(-i,t)),{isValid:u||f,value:i}}var Ht=Bd(Hc,{uvRatio:Wc}),Vt=Ht.Fp,Vd=Ht.Fn;function w0(r){return Ud(Ht,xs,Object.assign({adjustScalarBytes:b0,zip215:!0},r))}var oo=w0({});var zc=$c,x0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),E0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),v0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),S0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),$d=r=>Wc(Ct,r),_0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Vc=r=>Vt.create(dt(r)&_0);function zd(r){let{d:e}=Hc,t=Xr,n=y=>Vt.create(y),o=n(zc*r*r),s=n((o+Ct)*v0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Wc(s,a),u=n(l*r);It(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Ct)*S0-a),d=l*l,h=n((l+l)*a),m=n(f*x0),g=n(Ct-d),p=n(Ct+d);return new Ht(n(h*p),n(g*m),n(m*p),n(h*g))}var Wt=class r extends Ls{static BASE=new r(Ht.BASE);static ZERO=new r(Ht.ZERO);static Fp=Vt;static Fn=Vd;constructor(e){super(e)}static fromAffine(e){return new r(Ht.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){qe(e,32);let{a:t,d:n}=Hc,o=Xr,s=k=>Vt.create(k),i=Vc(e);if(!wd(Vt.toBytes(i),e)||It(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Ct+t*a),l=s(Ct-t*a),u=s(c*c),f=s(l*l),d=s(t*n*u-f),{isValid:h,value:m}=$d(s(d*f)),g=s(m*l),p=s(m*g*d),y=s((i+i)*g);It(y,o)&&(y=s(-y));let v=s(c*p),S=s(y*v);if(!h||It(S,o)||v===p0)throw new Error("invalid ristretto255 encoding 2");return new r(new Ht(y,v,Ct,S))}static fromHex(e){return r.fromBytes(Gn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=Xr,i=p=>Vt.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=$d(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),m;if(It(o*h,s)){let p=i(t*zc),y=i(e*zc);e=p,t=y,m=i(f*E0)}else m=d;It(e*h,s)&&(t=i(-t));let g=i((n-t)*m);return It(g,s)&&(g=i(-g)),Vt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>Vt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Wt.BASE);Object.freeze(Wt.ZERO);Object.freeze(Wt.prototype);Object.freeze(Wt);var A0=Object.freeze({Point:Wt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=qc(r,t,64,xs);return A0.deriveToCurve(n)},hashToScalar(r,e={DST:Kd}){let t=qc(r,e.DST,64,xs);return Vd.create(dt(t))},deriveToCurve(r){qe(r,64);let e=Vc(r.subarray(0,32)),t=zd(e),n=Vc(r.subarray(32,64)),o=zd(n);return new Wt(t.add(o))}});var so=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},io=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ps=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Hd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ps("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 Ue=Hd;var Ds=32,ao=64,Gc=32;var Qr,Wd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Gd(){let r=oo.utils.randomSecretKey(),e=oo.getPublicKey(r);return{privateKey:P0(r,e),publicKey:e}}async function I0(r,e){let t;r.length===ao?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:B(r.subarray(32),"base64url"),d:B(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ue.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ue.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function C0(r,e){let t=r.subarray(0,Gc);return oo.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function jd(r,e){return Qr==null&&(Qr=await Wd),Qr?I0(r,e):C0(r,e)}async function T0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function L0(r,e,t){return oo.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Yd(r,e,t){return Qr==null&&(Qr=await Wd),Qr?T0(r,e,t):L0(r,e,t)}function P0(r,e){let t=new Uint8Array(ao);for(let n=0;n<Gc;n++)t[n]=r[n],t[Gc+n]=e[n];return t}function Jr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var co=class{type="Ed25519";raw;constructor(e){this.raw=Rs(e,Ds)}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Yd(this.raw,t,e);return Jr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},ks=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Rs(e,ao),this.publicKey=new co(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=jd(this.raw,e);return Jr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function jc(r){return r=Rs(r,Ds),new co(r)}async function Xd(){let{privateKey:r,publicKey:e}=Gd();return new ks(r,e)}function Rs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new P(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var D0=Math.pow(2,7),k0=Math.pow(2,14),R0=Math.pow(2,21),Yc=Math.pow(2,28),Zc=Math.pow(2,35),Xc=Math.pow(2,42),Qc=Math.pow(2,49),Z=128,Ae=127;function ye(r){if(r<D0)return 1;if(r<k0)return 2;if(r<R0)return 3;if(r<Yc)return 4;if(r<Zc)return 5;if(r<Xc)return 6;if(r<Qc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function en(r,e,t=0){switch(ye(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function O0(r,e,t=0){switch(ye(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Jc(r,e){let t=r[e],n=0;if(n+=t&Ae,t<Z||(t=r[e+1],n+=(t&Ae)<<7,t<Z)||(t=r[e+2],n+=(t&Ae)<<14,t<Z)||(t=r[e+3],n+=(t&Ae)<<21,t<Z)||(t=r[e+4],n+=(t&Ae)*Yc,t<Z)||(t=r[e+5],n+=(t&Ae)*Zc,t<Z)||(t=r[e+6],n+=(t&Ae)*Xc,t<Z)||(t=r[e+7],n+=(t&Ae)*Qc,t<Z))return n;throw new RangeError("Could not decode varint")}function N0(r,e){let t=r.get(e),n=0;if(n+=t&Ae,t<Z||(t=r.get(e+1),n+=(t&Ae)<<7,t<Z)||(t=r.get(e+2),n+=(t&Ae)<<14,t<Z)||(t=r.get(e+3),n+=(t&Ae)<<21,t<Z)||(t=r.get(e+4),n+=(t&Ae)*Yc,t<Z)||(t=r.get(e+5),n+=(t&Ae)*Zc,t<Z)||(t=r.get(e+6),n+=(t&Ae)*Xc,t<Z)||(t=r.get(e+7),n+=(t&Ae)*Qc,t<Z))return n;throw new RangeError("Could not decode varint")}function Gt(r,e,t=0){return e==null&&(e=_e(ye(r))),e instanceof Uint8Array?en(r,e,t):O0(r,e,t)}function ur(r,e=0){return r instanceof Uint8Array?Jc(r,e):N0(r,e)}var el=new Float32Array([-0]),jt=new Uint8Array(el.buffer);function Qd(r,e,t){el[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3]}function Jd(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],el[0]}var tl=new Float64Array([-0]),Ie=new Uint8Array(tl.buffer);function eh(r,e,t){tl[0]=r,e[t]=Ie[0],e[t+1]=Ie[1],e[t+2]=Ie[2],e[t+3]=Ie[3],e[t+4]=Ie[4],e[t+5]=Ie[5],e[t+6]=Ie[6],e[t+7]=Ie[7]}function th(r,e){return Ie[0]=r[e],Ie[1]=r[e+1],Ie[2]=r[e+2],Ie[3]=r[e+3],Ie[4]=r[e+4],Ie[5]=r[e+5],Ie[6]=r[e+6],Ie[7]=r[e+7],tl[0]}var F0=BigInt(Number.MAX_SAFE_INTEGER),M0=BigInt(Number.MIN_SAFE_INTEGER),$e=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return fr;if(e<F0&&e>M0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>rh&&(o=0n,++n>rh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return fr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):fr}},fr=new $e(0,0);fr.toBigInt=function(){return 0n};fr.zzEncode=fr.zzDecode=function(){return this};fr.length=function(){return 1};var rh=4294967296n;function nh(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 oh(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function rl(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Os(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var nl=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return Os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return Os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=Jd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=th(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return oh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==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 $e(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=Os(this.buf,this.pos+=4),t=Os(this.buf,this.pos+=4);return new $e(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Jc(this.buf,this.pos);return this.pos+=ye(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 uo(r){return new nl(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=uo(r);return e.decode(n,void 0,t)}function ol(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return _e(i);o+i>e&&(n=_e(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var dr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function sl(){}var al=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},B0=ol();function U0(r){return globalThis.Buffer!=null?_e(r):B0(r)}var ho=class{len;head;tail;states;constructor(){this.len=0,this.head=new dr(sl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new dr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new cl((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(Ns,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(Ns,t.length(),t)}uint64Number(e){return this._push(en,ye(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=$e.fromBigInt(e).zzEncode();return this._push(Ns,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(Ns,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(il,1,e?1:0)}fixed32(e){return this._push(fo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(fo,4,t.lo)._push(fo,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(fo,4,t.lo)._push(fo,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(Qd,4,e)}double(e){return this._push(eh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(il,1,0):this.uint32(t)._push(q0,t,e)}string(e){let t=nh(e);return t!==0?this.uint32(t)._push(rl,t,e):this._push(il,1,0)}fork(){return this.states=new al(this),this.head=this.tail=new dr(sl,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 dr(sl,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=U0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function il(r,e,t){e[t]=r&255}function K0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var cl=class extends dr{next;constructor(e,t){super(K0,e,t),this.next=void 0}};function Ns(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 fo(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 q0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ho.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push($0,e,r),this},ho.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(z0,e,r),this});function $0(r,e,t){e.set(r,t)}function z0(r,e,t){r.length<40?rl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function ll(){return new ho}function Re(r,e){let t=ll();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Oe(r,e,t){let n=uo(r);yield*e.stream(n,void 0,"$",t)}var Fs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ms(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function ul(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ms("enum",Fs.VARINT,t,n,o)}function Ne(r,e,t){return Ms("message",Fs.LENGTH_DELIMITED,r,e,t)}var je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},po=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var se;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(se||(se={}));var fl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(fl||(fl={}));(function(r){r.codec=()=>ul(fl)})(se||(se={}));var ht;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(ht||(ht={}));var dl;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(dl||(dl={}));function tn(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return bs(r)}var go={};Be(go,{MAX_RSA_KEY_SIZE:()=>hl,generateRSAKeyPair:()=>vl,jwkToJWKKeyPair:()=>uh,jwkToPkcs1:()=>G0,jwkToPkix:()=>yl,jwkToRSAPrivateKey:()=>El,pkcs1MessageToJwk:()=>ml,pkcs1MessageToRSAPrivateKey:()=>bl,pkcs1ToJwk:()=>W0,pkcs1ToRSAPrivateKey:()=>lh,pkixMessageToJwk:()=>gl,pkixMessageToRSAPublicKey:()=>xl,pkixToJwk:()=>j0,pkixToRSAPublicKey:()=>wl});var rn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=go.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return ch(this.jwk,t,e,n)}},mo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=go.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return ah(this.jwk,e,t)}};var hl=8192,pl=18,V0=1062,H0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function W0(r){let e=vt(r);return ml(e)}function ml(r){return{n:B(r[1],"base64url"),e:B(r[2],"base64url"),d:B(r[3],"base64url"),p:B(r[4],"base64url"),q:B(r[5],"base64url"),dp:B(r[6],"base64url"),dq:B(r[7],"base64url"),qi:B(r[8],"base64url"),kty:"RSA"}}function G0(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 P("JWK was missing components");return Je([De(Uint8Array.from([0])),De(D(r.n,"base64url")),De(D(r.e,"base64url")),De(D(r.d,"base64url")),De(D(r.p,"base64url")),De(D(r.q,"base64url")),De(D(r.dp,"base64url")),De(D(r.dq,"base64url")),De(D(r.qi,"base64url"))]).subarray()}function j0(r){let e=vt(r,{offset:0});return gl(e)}function gl(r){let e=vt(r[1],{offset:0});return{kty:"RSA",n:B(e[0],"base64url"),e:B(e[1],"base64url")}}function yl(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");return Je([H0,Wn(Je([De(D(r.n,"base64url")),De(D(r.e,"base64url"))]))]).subarray()}function lh(r){let e=vt(r);return bl(e)}function bl(r){let e=ml(r);return El(e)}function wl(r,e){if(r.byteLength>=V0)throw new Or("Key size is too large");let t=vt(r,{offset:0});return xl(t,r,e)}function xl(r,e,t){let n=gl(r);if(t==null){let o=zr(ht.encode({Type:se.RSA,Data:e}));t=ut(pl,o)}return new rn(n,t)}function El(r){if(dh(r)>hl)throw new P("Key size is too large");let e=uh(r),t=zr(ht.encode({Type:se.RSA,Data:yl(e.publicKey)})),n=ut(pl,t);return new mo(e.privateKey,new rn(e.publicKey,n))}async function vl(r){if(r>hl)throw new P("Key size is too large");let e=await fh(r),t=zr(ht.encode({Type:se.RSA,Data:yl(e.publicKey)})),n=ut(pl,t);return new mo(e.privateKey,new rn(e.publicKey,n))}function uh(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function fh(r,e){let t=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Y0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function ah(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function ch(r,e,t,n){let o=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Y0(r,e){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function dh(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return D(r.n,"base64url").length*8}var Bs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ps(e),qe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),_t(o)}update(e){return $r(this),this.iHash.update(e),this}digestInto(e){$r(this),ms(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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},hh=(()=>{let r=((e,t,n)=>new Bs(e,t).update(n).digest());return r.create=(e,t)=>new Bs(e,t),r})();var ph=(r,e)=>(r+(r>=0?e:-e)/mh)/e;function Z0(r,e,t){Wr("scalar",r,pt,t);let[[n,o],[s,i]]=e,a=ph(i*r,t),c=ph(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<pt,d=u<pt;f&&(l=-l),d&&(u=-u);let h=eo(Math.ceil(Gr(t)/2))+Yt;if(l<pt||l>=h||u<pt||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:d,k2:u}}function _l(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Sl(r,e){nt(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return tt(t.lowS,"lowS"),tt(t.prehash,"prehash"),t.format!==void 0&&_l(t.format),t}var Al=class extends Error{constructor(e=""){super(e)}},st={Err:Al,_tlv:{encode:(r,e)=>{let{Err:t}=st;if(rt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Qn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Qn(o.length/2|128):"";return Qn(r)+s+o+e},decode(r,e){let{Err:t}=st;e=H(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let 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}=st;if(Ss(r),r<pt)throw new e("integer: negative integers are not allowed");let t=Qn(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}=st;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 ir(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=st,o=H(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=st,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(st._tlv);Object.freeze(st._int);Object.freeze(st);var pt=BigInt(0),Yt=BigInt(1),mh=BigInt(2),Us=BigInt(3),X0=BigInt(4);function gh(r,e={}){let t=Cs("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;nt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=bh(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(q,b,w){if(l&&b.is0())return Uint8Array.of(0);let{x:_,y:E}=b.toAffine(),x=n.toBytes(_);if(tt(w,"isCompressed"),w){f();let A=!n.isOdd(E);return he(yh(A),x)}else return he(Uint8Array.of(4),x,n.toBytes(E))}function h(q){H(q,void 0,"Point");let{publicKey:b,publicKeyUncompressed:w}=u,_=q.length,E=q[0],x=q.subarray(1);if(l&&_===1&&E===0)return{x:n.ZERO,y:n.ZERO};if(_===b&&(E===2||E===3)){let A=n.fromBytes(x);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let T=p(A),C;try{C=n.sqrt(T)}catch(V){let j=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}f();let O=n.isOdd(C);return(E&1)===1!==O&&(C=n.neg(C)),{x:A,y:C}}else if(_===w&&E===4){let A=n.BYTES,T=n.fromBytes(x.subarray(0,A)),C=n.fromBytes(x.subarray(A,A*2));if(!y(T,C))throw new Error("bad point: is not on curve");return{x:T,y:C}}else throw new Error(`bad point: got length ${_}, expected compressed=${b} or uncompressed=${w}`)}let m=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function p(q){let b=n.sqr(q),w=n.mul(b,q);return n.add(n.add(w,n.mul(q,s.a)),s.b)}function y(q,b){let w=n.sqr(b),_=p(q);return n.eql(w,_)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,Us),X0),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function k(q,b,w=!1){if(!n.isValid(b)||w&&n.is0(b))throw new Error(`bad point coordinate ${q}`);return b}function L(q){if(!(q instanceof I))throw new Error("Weierstrass Point expected")}function U(q){if(!c||!c.basises)throw new Error("no endo");return Z0(q,c.basises,o.ORDER)}function R(q,b,w,_,E){return w=new I(n.mul(w.X,q),w.Y,w.Z),b=ro(_,b),w=ro(E,w),b.add(w)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,w,_){this.X=k("x",b),this.Y=k("y",w,!0),this.Z=k("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:w,y:_}=b||{};if(!b||!n.isValid(w)||!n.isValid(_))throw new Error("invalid affine point");if(b instanceof I)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(_)?I.ZERO:new I(w,_,n.ONE)}static fromBytes(b){let w=I.fromAffine(g(H(b,void 0,"point")));return w.assertValidity(),w}static fromHex(b){return I.fromBytes(Hr(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,w=!0){return Y.createCache(this,b),w||this.multiply(Us),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:w,y:_}=b.toAffine();if(!n.isValid(w)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!y(w,_))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){L(b);let{X:w,Y:_,Z:E}=this,{X:x,Y:A,Z:T}=b,C=n.eql(n.mul(w,T),n.mul(x,E)),O=n.eql(n.mul(_,T),n.mul(A,E));return C&&O}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:w}=s,_=n.mul(w,Us),{X:E,Y:x,Z:A}=this,T=n.ZERO,C=n.ZERO,O=n.ZERO,F=n.mul(E,E),V=n.mul(x,x),j=n.mul(A,A),$=n.mul(E,x);return $=n.add($,$),O=n.mul(E,A),O=n.add(O,O),T=n.mul(b,O),C=n.mul(_,j),C=n.add(T,C),T=n.sub(V,C),C=n.add(V,C),C=n.mul(T,C),T=n.mul($,T),O=n.mul(_,O),j=n.mul(b,j),$=n.sub(F,j),$=n.mul(b,$),$=n.add($,O),O=n.add(F,F),F=n.add(O,F),F=n.add(F,j),F=n.mul(F,$),C=n.add(C,F),j=n.mul(x,A),j=n.add(j,j),F=n.mul(j,$),T=n.sub(T,F),O=n.mul(j,V),O=n.add(O,O),O=n.add(O,O),new I(T,C,O)}add(b){L(b);let{X:w,Y:_,Z:E}=this,{X:x,Y:A,Z:T}=b,C=n.ZERO,O=n.ZERO,F=n.ZERO,V=s.a,j=n.mul(s.b,Us),$=n.mul(w,x),de=n.mul(_,A),pe=n.mul(E,T),me=n.add(w,_),le=n.add(x,A);me=n.mul(me,le),le=n.add($,de),me=n.sub(me,le),le=n.add(w,E);let Me=n.add(x,T);return le=n.mul(le,Me),Me=n.add($,pe),le=n.sub(le,Me),Me=n.add(_,E),C=n.add(A,T),Me=n.mul(Me,C),C=n.add(de,pe),Me=n.sub(Me,C),F=n.mul(V,le),C=n.mul(j,pe),F=n.add(C,F),C=n.sub(de,F),F=n.add(de,F),O=n.mul(C,F),de=n.add($,$),de=n.add(de,$),pe=n.mul(V,pe),le=n.mul(j,le),de=n.add(de,pe),pe=n.sub($,pe),pe=n.mul(V,pe),le=n.add(le,pe),$=n.mul(de,le),O=n.add(O,$),$=n.mul(Me,le),C=n.mul(me,C),C=n.sub(C,$),$=n.mul(me,de),F=n.mul(Me,F),F=n.add(F,$),new I(C,O,F)}subtract(b){return L(b),this.add(b.negate())}is0(){return this.equals(I.ZERO)}multiply(b){let{endo:w}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let _,E,x=A=>Y.cached(this,A,T=>lr(I,T));if(w){let{k1neg:A,k1:T,k2neg:C,k2:O}=U(b),{p:F,f:V}=x(T),{p:j,f:$}=x(O);E=V.add($),_=R(w.beta,F,j,A,C)}else{let{p:A,f:T}=x(b);_=A,E=T}return lr(I,[_,E])[0]}multiplyUnsafe(b){let{endo:w}=e,_=this,E=b;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===pt||_.is0())return I.ZERO;if(E===Yt)return _;if(Y.hasCache(this))return this.multiply(E);if(w){let{k1neg:x,k1:A,k2neg:T,k2:C}=U(E),{p1:O,p2:F}=Md(I,_,A,C);return R(w.beta,O,F,x,T)}else return Y.unsafe(_,E)}toAffine(b){let w=this,_=b,{X:E,Y:x,Z:A}=w;if(n.eql(A,n.ONE))return{x:E,y:x};let T=w.is0();_==null&&(_=T?n.ONE:n.inv(A));let C=n.mul(E,_),O=n.mul(x,_),F=n.mul(A,_);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}isTorsionFree(){let{isTorsionFree:b}=e;return i===Yt?!0:b?b(I,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Yt?this:b?b(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Yt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return tt(b,"isCompressed"),this.assertValidity(),m(I,this,b)}toHex(b=!0){return Vr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let K=o.BITS,Y=new Zr(I,e.endo?Math.ceil(K/2):K);return K>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function yh(r){return Uint8Array.of(r?2:3)}function bh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Q0(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Xn:e.randomBytes,o=Object.assign(bh(r.Fp,t),{seed:Math.max(Nc(t.ORDER),16)});function s(h){try{let m=t.fromBytes(h);return t.isValidNot0(m)}catch{return!1}}function i(h,m){let{publicKey:g,publicKeyUncompressed:p}=o;try{let y=h.length;return m===!0&&y!==g||m===!1&&y!==p?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Fc(H(h,o.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(m)}function l(h){let{secretKey:m,publicKey:g,publicKeyUncompressed:p}=o,y=t._lengths;if(!sr(h))return;let v=H(h,void 0,"key").length,S=v===g||v===p,k=v===m||!!y?.includes(v);if(!(S&&k))return S}function u(h,m,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(h);return r.fromBytes(m).multiply(p).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ts(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function wh(r,e,t={}){let n=e;ps(n),nt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Xn:t.randomBytes,s=t.hmac===void 0?(E,x)=>hh(n,E,x):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:m}=Q0(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*mh+Yt<i.ORDER;function y(E){let x=c>>Yt;return E>x}function v(E,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return x}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(E,x){_l(x);let A=m.signature,T=x==="compact"?A:x==="recovered"?A+1:void 0;return H(E,T)}class L{r;s;recovery;constructor(x,A,T){if(this.r=v("r",x),this.s=v("s",A),T!=null){if(S(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(x,A=g.format){k(x,A);let T;if(A==="der"){let{r:V,s:j}=st.toSig(H(x));return new L(V,j)}A==="recovered"&&(T=x[0],A="compact",x=x.subarray(1));let C=m.signature/2,O=x.subarray(0,C),F=x.subarray(C,C*2);return new L(a.fromBytes(O),a.fromBytes(F),T)}static fromHex(x,A){return this.fromBytes(Hr(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new L(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:T}=this,C=this.assertRecovery(),O=C===2||C===3?A+c:A;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(O),V=r.fromBytes(he(yh((C&1)===0),F)),j=a.inv(O),$=R(H(x,void 0,"msgHash")),de=a.create(-$*j),pe=a.create(T*j),me=r.BASE.multiplyUnsafe(de).add(V.multiplyUnsafe(pe));if(me.is0())throw new Error("invalid recovery: point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}toBytes(x=g.format){if(_l(x),x==="der")return Hr(st.hexFromSig(this));let{r:A,s:T}=this,C=a.toBytes(A),O=a.toBytes(T);return x==="recovered"?(S(),he(Uint8Array.of(this.assertRecovery()),C,O)):he(C,O)}toHex(x){return Vr(this.toBytes(x))}}Object.freeze(L.prototype),Object.freeze(L);let U=t.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let A=ir(x),T=x.length*8-l;return T>0?A>>BigInt(T):A}:t.bits2int,R=t.bits2int_modN===void 0?function(x){return a.create(U(x))}:t.bits2int_modN,I=eo(l);function K(E){return Wr("num < 2^"+l,E,pt,I),a.toBytes(E)}function Y(E,x){return H(E,void 0,"message"),x?H(n(E),void 0,"prehashed message"):E}function q(E,x,A){let{lowS:T,prehash:C,extraEntropy:O}=Sl(A,g);E=Y(E,C);let F=R(E),V=a.fromBytes(x);if(!a.isValidNot0(V))throw new Error("invalid private key");let j=[K(V),K(F)];if(O!=null&&O!==!1){let me=O===!0?o(m.secretKey):O;j.push(H(me,void 0,"extraEntropy"))}let $=he(...j),de=F;function pe(me){let le=U(me);if(!a.isValidNot0(le))return;let Me=a.inv(le),Rr=r.BASE.multiply(le).toAffine(),Rn=a.create(Rr.x);if(Rn===pt)return;let Xo=a.create(Me*a.create(de+Rn*V));if(Xo===pt)return;let xf=(Rr.x===Rn?0:2)|Number(Rr.y&Yt),Ef=Xo;return T&&y(Xo)&&(Ef=a.neg(Xo),xf^=1),new L(Rn,Ef,p?void 0:xf)}return{seed:$,k2sig:pe}}function b(E,x,A={}){let{seed:T,k2sig:C}=q(E,x,A);return xd(n.outputLen,a.BYTES,s)(T,C).toBytes(A.format)}function w(E,x,A,T={}){let{lowS:C,prehash:O,format:F}=Sl(T,g);if(A=H(A,void 0,"publicKey"),x=Y(x,O),!sr(E)){let V=E instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+V)}k(E,F);try{let V=L.fromBytes(E,F),j=r.fromBytes(A);if(C&&V.hasHighS())return!1;let{r:$,s:de}=V,pe=R(x),me=a.inv(de),le=a.create(pe*me),Me=a.create($*me),Rr=r.BASE.multiplyUnsafe(le).add(j.multiplyUnsafe(Me));return Rr.is0()?!1:a.create(Rr.x)===$}catch{return!1}}function _(E,x,A={}){let{prehash:T}=Sl(A,g);return x=Y(x,T),L.fromBytes(E,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:m,Point:r,sign:b,verify:w,recoverPublicKey:_,Signature:L,hash:n})}var Cl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},J0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var xh=BigInt(2);function ey(r){let e=Cl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=oe(u,t,e)*u%e,d=oe(f,t,e)*u%e,h=oe(d,xh,e)*l%e,m=oe(h,o,e)*h%e,g=oe(m,s,e)*m%e,p=oe(g,a,e)*g%e,y=oe(p,c,e)*p%e,v=oe(y,a,e)*g%e,S=oe(v,t,e)*u%e,k=oe(S,i,e)*m%e,L=oe(k,n,e)*l%e,U=oe(L,xh,e);if(!Il.eql(Il.sqr(U),r))throw new Error("Cannot find square root");return U}var Il=jr(Cl.p,{sqrt:ey}),ty=gh(Cl,{Fp:Il,endo:J0}),it=wh(ty,zr);function Eh(r,e,t){let n=qr.digest(e instanceof Uint8Array?e:e.subarray());if(Jr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),it.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new so(String(o))});try{return it.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new so(String(o))}}function vh(r,e,t,n){let o=qr.digest(t instanceof Uint8Array?t:t.subarray());if(Jr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),it.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new io(String(s))});try{return n?.signal?.throwIfAborted(),it.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new io(String(s))}}var yo=class{type="secp256k1";raw;_key;constructor(e){this._key=Ah(e),this.raw=Sh(this._key)}toMultihash(){return Xe.digest(Ge(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return vh(this._key,t,e,n)}},Ks=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=_h(e),this.publicKey=new yo(t??Ih(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return Eh(this.raw,e,t)}};function Tl(r){return new yo(r)}async function Ch(){let r=ry();return new Ks(r)}function Sh(r){return it.Point.fromBytes(r).toBytes()}function _h(r){try{return it.getPublicKey(r,!0),r}catch(e){throw new Nn(String(e))}}function Ah(r){try{return it.Point.fromBytes(r),r}catch(e){throw new Or(String(e))}}function Ih(r){try{return it.getPublicKey(r,!0)}catch(e){throw new Nn(String(e))}}function ry(){return it.utils.randomSecretKey()}async function Th(r,e){if(r==="Ed25519")return Xd();if(r==="secp256k1")return Ch();if(r==="RSA")return vl(ny(e));if(r==="ECDSA")return od(oy(e));throw new Nt}function nn(r,e){let{Type:t,Data:n}=ht.decode(r),o=n??new Uint8Array;switch(t){case se.RSA:return wl(o,e);case se.Ed25519:return jc(o);case se.secp256k1:return Tl(o);case se.ECDSA:return bc(o);default:throw new Nt}}function Lh(r){let{Type:e,Data:t}=ht.decode(r.digest),n=t??new Uint8Array;switch(e){case se.Ed25519:return jc(n);case se.secp256k1:return Tl(n);case se.ECDSA:return bc(n);default:throw new Nt}}function Ge(r){return ht.encode({Type:se[r.type],Data:r.raw})}function ny(r){return r==null?2048:parseInt(r,10)}function oy(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 P("Unsupported curve, should be P-256, P-384 or P-521")}var Ph=Symbol.for("nodejs.util.inspect.custom"),sy=114,bo=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()})`}[as]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(sy,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ph](){return`PeerId(${this.toString()})`}},wo=class extends bo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xo=class extends bo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Eo=class extends bo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},iy=2336,vo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Xe.digest(D(this.url))}[Ph](){return`PeerId(${this.url})`}[as]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(iy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=B(e)),e.toString()===this.toString())}};var ay=114,Dh=2336;function mt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Et(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return So(ue.parse(r));if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Et(e.decode(r))}return on(t)}function Ll(r){if(r.type==="Ed25519")return new xo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Eo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new wo({multihash:r.toCID().multihash,publicKey:r});throw new Nt}function kh(r){return Ll(r.publicKey)}function on(r){if(ly(r))return new wo({multihash:r});if(cy(r))try{let e=Lh(r);if(e.type==="Ed25519")return new xo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Eo({multihash:r,publicKey:e})}catch{let t=B(r.digest);return new vo(new URL(t))}throw new es("Supplied PeerID Multihash is invalid")}function So(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ay&&r.code!==Dh)throw new Jo("Supplied PeerID CID is invalid");if(r.code===Dh){let e=B(r.multihash.digest);return new vo(new URL(e))}return on(r.multihash)}function cy(r){return r.code===Xe.code}function ly(r){return r.code===qr.code}async function Rh(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new P("Private network is enforced, but no protector was provided");return r}function uy(r,e){if(typeof r=="string")return fy(r);if(typeof r=="number")return py(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var qs=uy;function fy(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function dy(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function hy(r){let e=Math.abs(r);return e>=315576e5?hr(r,e,315576e5,"year"):e>=26298e5?hr(r,e,26298e5,"month"):e>=6048e5?hr(r,e,6048e5,"week"):e>=864e5?hr(r,e,864e5,"day"):e>=36e5?hr(r,e,36e5,"hour"):e>=6e4?hr(r,e,6e4,"minute"):e>=1e3?hr(r,e,1e3,"second"):`${r} ms`}function py(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?hy(r):dy(r)}function hr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Pl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=qs,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u,f){let d,h=null,m,g;function p(...y){if(!p.enabled)return;let v=p,S=Number(new Date),k=S-(d||S);v.diff=k,v.prev=d,v.curr=S,d=S,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let L=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,I)=>{if(R==="%%")return"%";L++;let K=t.formatters[I];if(typeof K=="function"){let Y=y[L];R=K.call(v,Y),y.splice(L,1),L--}return R}),t.formatArgs.call(v,y),f?.onLog!=null&&f.onLog(...y),(v.log||t.log).apply(v,y)}return p.namespace=u,p.useColors=t.useColors(),p.color=t.selectColor(u),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(m!==t.namespaces&&(m=t.namespaces,g=t.enabled(u)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(p),p}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var $s=Ey(),my=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function gy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function yy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+qs(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var by=console.debug??console.log??(()=>{});function wy(r){try{r?$s?.setItem("debug",r):$s?.removeItem("debug")}catch{}}function xy(){let r;try{r=$s?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ey(){try{return localStorage}catch{}}function vy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Oh=Pl({formatArgs:yy,save:wy,load:xy,useColors:gy,setupFormatters:vy,colors:my,storage:$s,log:by});var Ke=Oh;Ke.formatters.b=r=>r==null?"undefined":te.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":sc.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();function Nh(r,e=""){let t=Fh(r.message),n=Fh(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
${e}`)}`:`${t}
|
|
5
5
|
${e}${n.split(`
|
|
6
6
|
`).join(`
|
|
7
7
|
${e}`)}`:n!=null?`${n.split(`
|
|
8
8
|
`).join(`
|
|
9
|
-
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function
|
|
10
|
-
${e}${r.errors.map(n=>`${
|
|
9
|
+
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Sy(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Mh(r,e=""){if(Sy(r)){let t=Nh(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
10
|
+
${e}${r.errors.map(n=>`${Mh(n,`${e}`)}`).join(`
|
|
11
11
|
${e}`)}`):t+=`
|
|
12
|
-
${e}[Error list was empty]`,t.trim()}return Oh(r,e)}Ke.formatters.e=r=>r==null?"undefined":Fh(r);function Sy(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function zs(r){return{forComponent(e){return Mh(e,r)}}}function Mh(r,e){let t=Sy(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ke(`${r}:trace`,e)),Object.assign(Ke(r,e),{error:Ke(`${r}:error`,e),trace:t,newScope:n=>Mh(`${r}:${n}`,e)})}function Nh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function pr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Vs(r){let e=Et(te.decode(`z${r}`));return on(e)}var Ye=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return pr(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 pr(this.map.values(),e=>e.key)}values(){return pr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var mr=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 pr(this.set.entries(),e=>{let t=Vs(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Vs(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pr(this.set.values(),e=>Vs(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Dl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Bh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Uh=new globalThis.TextEncoder;function _y(r,e){let t=Dl[e],n=Bh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Ay(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Dl[e],o=Bh[e],s=r;for(;s.length>0;){let i=Uh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function kl(r,{size:e=32,utf8Buffer:t}={}){if(!Dl[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 Ay(r,e,t);r=Uh.encode(r)}return _y(r,e)}var _o={hash:r=>Number(kl(r,{size:32})),hashV:(r,e)=>Iy(_o.hash(r,e))};function Iy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Rl=64,at=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Rl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ae(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function gr(r,e){return Math.floor(Math.random()*(e-r))+r}var yr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof at))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof at))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 at))throw new TypeError("Invalid Fingerprint");let t=gr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof at))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Cy=500,Ao=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??_o,this.seed=e.seed??gr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new yr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new yr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[gr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new yr(this.bucketSize));for(let a=0;a<Cy;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 yr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ty={1:.5,2:.84,4:.95,8:.98};function Ly(r=.001){return r>.002?2:r>1e-5?4:8}function Kh(r,e=.001){let t=Ly(e),n=Ty[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Rl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Hs=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??_o,this.seed=e.seed??gr(0,Math.pow(2,10)),this.filterSeries=[new Ao({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(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 Ao({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=D(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=D(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 Io(r,e=.001,t){return new Hs({...Kh(r,e),...t??{}})}function V(r){let e=r.getComponents(),t={},n=0;if(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)throw new P(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Ws=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var qh=45,Py=15,sn=new Ws;function Gs(r){if(!(r.length>Py))return sn.new(r).parseWith(()=>sn.readIPv4Addr())}function js(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>qh))return sn.new(r).parseWith(()=>sn.readIPv6Addr())}function an(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>qh)return;let t=sn.new(r).parseWith(()=>sn.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 $h(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function zh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Ol(r){switch(r.length){case br:return r.join(".");case wr:{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 Vh(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 o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Hh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var br=4,wr=16,g_=parseInt("0xFFFF",16),Dy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Co(r,e){e.length===wr&&r.length===br&&$h(e,0,11)&&(e=e.slice(12)),e.length===br&&r.length===wr&&zh(r,Dy,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 o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Wh(r,e){if(typeof e=="string"&&(e=an(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 Nl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=br,o=Gs(e);if(o==null&&(n=wr,o=js(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Fl(s,8*n);return{network:Co(o,i),mask:i}}function Fl(r,e){if(e!==8*br&&e!==8*wr)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 o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var cn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Nl(e));else{let n=an(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=an(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Fl(o,8*n.length);this.network=Co(n,this.mask)}}contains(e){return Wh({network:this.network,mask:this.mask},e)}toString(){let e=Vh(this.mask),t=e!==-1?String(e):Hh(this.mask);return Ol(this.network)+"/"+t}};function Gh(r){try{let e=V(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 jh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function To(r){try{let e=V(r);switch(e.type){case"ip4":case"ip6":return jh(e.host);default:return!1}}catch{return!1}}function ve(r){try{return V(r),!0}catch{return!1}}function ct(r){return!!Gs(r)}function Ys(r){return!!js(r)}var Qh=Ua(Xh(),1),By=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Uy=By.map(r=>new Qh.Netmask(r));function zl(r){for(let e of Uy)if(e.contains(r))return!0;return!1}function Ky(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function qy(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return zl(o)}function $y(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function zy(r){let e=r.split(":"),t=e[e.length-1];return zl(t)}function Vy(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 dn(r){if(ct(r))return zl(r);if(Ky(r))return qy(r);if($y(r))return zy(r);if(Ys(r))return Vy(r)}function Tt(r){try{let e=V(r);switch(e.type){case"ip4":case"ip6":return dn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function be(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Xs=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}},hn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Xs(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 Xs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Vl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pn(r={}){return Hy(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 Hy(r,e){e=e??{};let t=e.onEnd,n=new hn,o,s,i,a=be(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,y)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){y(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=be()})}},l=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new hn,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(e?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?u(p):l({done:!0})),h=()=>(n=new hn,d(),{done:!0}),m=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async p=>{let y=p?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,S;y!=null&&(v=new Promise((k,L)=>{S=()=>{L(new Vl)},y.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&y!=null&&y?.removeEventListener("abort",S)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(p){return g.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(p){return g.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:p=>g.onEmpty(p)},o}var Hl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Jh=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(Jh(i));return}if(i&&(c=()=>{d(Jh(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Hl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(m){d(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Wy=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 Gy(r,e,t){let n,o=new Promise((s,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}=Wy(r),f=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(g){n(),i(g);return}c.push(m),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Lo(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Gy(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Po(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Qs=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}},Js=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Er=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function jy(r){return r.reason}async function ze(r,e,t){if(e==null)return r;let n=t?.translateError??jy;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var ei=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=be(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ze)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Yy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ti=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Yy(),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 Ze),this.cleanup())}async join(e){let t=new ei(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 ze(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var mn=class extends Pe{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=Po(this.emitEmpty.bind(this),1),this.emitIdle=Po(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 Js;let n=new ti(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ze)}),this.clear()}async onEmpty(e){this.size!==0&&await lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(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=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ze("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function yt(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var gn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Zy=1.2,Xy=2,Qy=5e3,Jy=6e4,eb=5e3,ri=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??eb;this.success=new gn(t),this.failure=new gn(t),this.next=new gn(t),this.failureMultiplier=e.failureMultiplier??Xy,this.timeoutMultiplier=e.timeoutMultiplier??Zy,this.minTimeout=e.minTimeout??Qy,this.maxTimeout=e.maxTimeout??Jy,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),o=yt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}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 Se=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Lt=class extends Error{static name="ValidationError";name="ValidationError"},ni=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},oi=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Gl(r){return e=>B(e,r)}function jl(r){return e=>D(e,r)}function yn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function vr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function ep(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=D(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 o=vr(n);return Qe([t,o],t.length+o.length)}function tp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=vr(n);return Qe([t,o],t.length+o.length)}function Yl(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=B(e,"base32"),o=yn(t);return`${n}:${o}`}var Zl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Se("Invalid byte value in IP address");e[n]=o}),e},rp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ct(t[n]),i;s&&(i=Zl(t[n]),t[n]=B(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,B(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Se("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},np=function(r){if(r.byteLength!==4)throw new Se("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},op=function(r){if(r.byteLength!==16)throw new Se("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.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 Se(`Invalid IPv6 address "${t}"`)}};function sp(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Se(`Invalid IPv6 address "${r}"`)}}var Wl=Object.values(zn).map(r=>r.decoder),tb=(function(){let r=Wl[0].or(Wl[1]);return Wl.slice(2).forEach(e=>r=r.or(e)),r})();function ip(r){return tb.decode(r)}function ap(r){return e=>r.encoder.encode(e)}function rb(r){if(parseInt(r).toString()!==r)throw new Lt("Value must be an integer")}function nb(r){if(r<0)throw new Lt("Value must be a positive integer, or zero")}function ob(r){return e=>{if(e>r)throw new Lt(`Value must be smaller than or equal to ${r}`)}}function sb(...r){return e=>{for(let t of r)t(e)}}var Do=sb(rb,nb,ob(65535));var we=-1,Xl=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 oi(`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)}))}},Dt=new Xl,wb=[{code:4,name:"ip4",size:32,valueToBytes:Zl,bytesToValue:np,validate:r=>{if(!ct(r))throw new Lt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:273,name:"udp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:33,name:"dccp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:41,name:"ip6",size:128,valueToBytes:rp,bytesToValue:op,stringToValue:sp,validate:r=>{if(!Ys(r))throw new Lt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:we},{code:43,name:"ipcidr",size:8,bytesToValue:Gl("base10"),valueToBytes:jl("base10")},{code:53,name:"dns",size:we},{code:54,name:"dns4",size:we},{code:55,name:"dns6",size:we},{code:56,name:"dnsaddr",size:we},{code:132,name:"sctp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:we,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:we,bytesToValue:Gl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?jl("base58btc")(r):ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Yl,valueToBytes:ep},{code:445,name:"onion3",size:296,bytesToValue:Yl,valueToBytes:tp},{code:446,name:"garlic64",size:we},{code:447,name:"garlic32",size:we},{code:448,name:"tls"},{code:449,name:"sni",size:we},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:we,bytesToValue:ap(ic),valueToBytes:ip},{code:480,name:"http"},{code:481,name:"http-path",size:we,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:we}];wb.forEach(r=>{Dt.addProtocol(r)});function cp(r){let e=[],t=0;for(;t<r.length;){let n=ur(r,t),o=Dt.getProtocol(n),s=ye(n),i=xb(o,r,t+s),a=0;i>0&&o.size===we&&(a=ye(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??B(f)}e.push(l),t+=c}return e}function lp(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Dt.getProtocol(n.code),s=ye(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,o.size===we&&(c=ye(a)));let l=new Uint8Array(s+c+a),u=0;en(n.code,l,u),u+=s,i!=null&&(o.size===we&&(en(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Qe(t,e)}function up(r){if(r.charAt(0)!=="/")throw new Se('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Dt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Se(`Component ${o} 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 Se(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Se("Incomplete multiaddr");return e}function fp(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Dt.getProtocol(e.code);if(t==null)throw new Se(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function xb(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ur(e,t)}var Eb=Symbol.for("nodejs.util.inspect.custom"),fu=Symbol.for("@multiformats/multiaddr");function vb(r){if(r==null&&(r="/"),Qt(r))return r.getComponents();if(r instanceof Uint8Array)return cp(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),up(r);if(Array.isArray(r))return r;throw new Se("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ui=class r{[fu]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=vb(e),t.validate!==!1&&Sb(this)}get bytes(){return this.#n==null&&(this.#n=lp(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=fp(this.#e)),this.#r}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(),o=n.lastIndexOf(t);if(o<0)throw new ni(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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 Q(this.bytes,e.bytes)}[Eb](){return`Multiaddr(${this.toString()})`}};function Sb(r){r.getComponents().forEach(e=>{let t=Dt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Qt(r){return!!r?.[fu]}function X(r){return new ui(r)}var du=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=be(),this.haveNext=be()}[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=be(),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=be(),await ze(this.readNext.promise,t?.signal,t)}};function dp(){return new du}function _b(r){return r[Symbol.asyncIterator]!=null}async function Ab(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Ib(r){let e=new AbortController,t=dp();Ab(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Cb(r){for(let e of r)yield*e}function Tb(...r){let e=[];for(let t of r)_b(t)||e.push(t);return e.length===r.length?Cb(e):Ib(r)}var Sn=Tb;var Lb=4194304,fi=class extends Error{static name="UnwrappedError";name="UnwrappedError"},pu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},mu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},gu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Pb(r){return typeof r?.closeRead=="function"}function Db(r){return typeof r?.close=="function"}function hu(r){return Pb(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Db(r)?r.status!=="open":!1}function kb(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function yu(r,e){let t=e?.maxBufferSize??Lb,n=new J,o,s=!1;if(!kb(r))throw new P("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new fi("Stream was unwrapped");if(hu(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Er(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await ze(o.promise,u?.signal),hu(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(hu(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Er(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new fi("Stream was unwrapped");r.send(u)||await lt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function di(r,e={}){let t=yu(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ye(e.maxDataLength));let n=e?.lengthDecoder??ur,o=e?.lengthEncoder??Gt;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(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new pu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new gu(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new mu(`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 Er(`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 Er(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var hi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_n=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},pi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ko=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mi(r){return r[Symbol.asyncIterator]!=null}function hp(r,e){if(r.byteLength>e)throw new _n("Message length too long")}var yi=r=>{let e=ye(r),t=_e(e);return Gt(r,t),yi.bytes=e,t};yi.bytes=0;function bi(r,e){e=e??{};let t=e.lengthEncoder??yi,n=e?.maxDataLength??4194304;function*o(s){hp(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mi(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}bi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??yi,n=e?.maxDataLength??4194304;return hp(r,n),new J(t(r.byteLength),r)};var _r;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_r||(_r={}));var wu=r=>{let e=ur(r);return wu.bytes=ye(e),e};wu.bytes=0;function bu(r,e){let t=new J,n=_r.LENGTH,o=-1,s=e?.lengthDecoder??wu,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===_r.LENGTH)try{if(o=s(t),o<0)throw new hi("Invalid message length");if(o>a)throw new _n("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=_r.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new pi("Message length length too long");break}throw l}if(n===_r.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=_r.LENGTH}}}return mi(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ko("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ko("Unexpected end of input")})()}bu.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return bu(n,{...e??{},onLength:s=>{t=s}})};var wi=class extends mn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xi=class extends mn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Ei=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 xu}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Qs("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},xu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Eu=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 Ce(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Eu({name:e,metrics:t}):n=new Map,n}var vu=class extends Ye{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 Su(r){let{name:e,metrics:t}=r,n;return t!=null?n=new vu({name:e,metrics:t}):n=new Ye,n}var Ro;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ae(0),payloadType:ae(0),payload:ae(0),signature:ae(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Ro||(Ro={}));var vi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var An=class r{static createFromProtobuf=e=>{let t=Ro.decode(e),n=nn(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 o=e.domain,s=e.codec,i=e.marshal(),a=pp(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new vi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({publicKey:Ge(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Q(this.marshal(),e.marshal())}async validate(e,t){let n=pp(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},pp=(r,e,t)=>{let n=D(r),o=Gt(n.byteLength),s=Gt(e.length),i=Gt(t.length);return new J(o,n,s,e,i,t)};var mp="libp2p-peer-record",gp=Uint8Array.from([3,1]);var Oo;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ne((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let m={multiaddr:ae(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let p=f.uint32();p>>>3===1?m.multiaddr=f.bytes():f.skipType(p&7)}return m},function*(f,d,h,m={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let p=f.uint32();p>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(p&7)}})),a);function c(f){return Re(f,i.codec())}i.encode=c;function l(f,d){return ke(f,i.codec(),d)}i.decode=l;function u(f,d){return Oe(f,i.codec(),d)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((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:ae(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>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 je('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(f&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>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 je('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(d&7);break}}}})),t);function n(i){return Re(i,r.codec())}r.encode=n;function o(i,a){return ke(i,r.codec(),a)}r.decode=o;function s(i,a){return Oe(i,r.codec(),a)}r.stream=s})(Oo||(Oo={}));function yp(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ar=class r{static createFromProtobuf=e=>{let t=Oo.decode(e),n=on(Et(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=mp;static CODEC=gp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Oo.encode({peerId:this.peerId.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||!yp(this.multiaddrs,e.multiaddrs))}};function Ob(r){return r[Symbol.asyncIterator]!=null}function Nb(r){if(Ob(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 No=Nb;var Ve=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Si(r,e,t,n){let o=new Ve(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Au(t,"abort",f),Au(r,e,l),Au(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.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.`))},f=()=>{c(),a(o)};_u(t,"abort",f),_u(r,e,l),_u(r,s,u)})}function _u(r,e,t){r!=null&&(bp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Au(r,e,t){r!=null&&(bp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function bp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var _i=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ai=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 Ve)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Fb(),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 Ve),this.cleanup())}async join(e={}){let t=new Ai(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 ze(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 Iu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Fo=class extends Pe{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=Iu(this.emitEmpty.bind(this),1),this.emitIdle=Iu(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 _i;let n=new Ii(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ve)}),this.clear()}async onEmpty(e){this.size!==0&&await Si(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Si(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Si(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=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ve("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ci="lock:worker:request-read",Ti="lock:worker:abort-read-request",Li="lock:worker:release-read",Pi="lock:master:grant-read",Di="lock:master:error-read",ki="lock:worker:request-write",Ri="lock:worker:abort-write-request",Oi="lock:worker:release-write",Ni="lock:master:grant-write",Fi="lock:master:error-write",Mi="lock:worker:finalize",Bi="mortice",wp={singleProcess:!1};var Cu=(r,e,t,n,o,s,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===o&&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(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Mi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var xp=(r=10)=>Math.random().toString().substring(2,r+2);var Ui=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Bi)}readLock(e){return this.sendRequest(Ci,Ti,Pi,Di,Li,e)}writeLock(e){return this.sendRequest(ki,Ri,Ni,Fi,Oi,e)}finalize(){this.channel.postMessage({type:Mi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=xp();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 f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var Ep=r=>{if(r=Object.assign({},wp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Bi),n=new Pe;return t.addEventListener("message",Cu(n,t,"requestReadLock","abortReadLockRequest",Ci,Ti,Di,Li,Pi)),t.addEventListener("message",Cu(n,t,"requestWriteLock","abortWriteLockRequest",ki,Ri,Fi,Oi,Ni)),n}return new Ui(r.name)};var Ir=new Map,Mo;function vp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Mb(r){if(Mo==null&&(Mo=Ep(r),!vp(Mo))){let e=Mo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Ir.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.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,o=t.detail.identifier,s=Ir.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.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,o=Ir.get(n);o?.finalize()})}return Mo}async function Tu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ve)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Sp=(r,e)=>{let t=Ir.get(r);if(t!=null)return t;let n=Mb(e);if(vp(n))return t=n,Ir.set(r,t),t;let o=new Fo({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Tu(s,i);s=new Fo({concurrency:e.concurrency,autoStart:!1});let a=s,c=Tu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Tu(o,i)},finalize:()=>{Ir.delete(r)},queue:o},Ir.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Bb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Lu(r){let e=Object.assign({},Bb,r);return Sp(e.name,e)}var kt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),m.lengthDelimited!==!1&&h.ldelim()},(d,h,m={})=>{let g={key:"",value:ae(0)},p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,m,g={}){let p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${m}.key`,value:d.string()};break}case 2:{yield{field:`${m}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Uo.codec().encode(d.value,h)),m.lengthDelimited!==!1&&h.ldelim()},(d,h,m={})=>{let g={key:""},p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=Uo.codec().decode(d,d.uint32(),{limits:m.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,m,g={}){let p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${m}.key`,value:d.string()};break}case 2:{yield*Uo.codec().stream(d,d.uint32(),`${m}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((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),Bo.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,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[u,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:f},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},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new je('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Bo.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 je('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 po('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 po('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(d&7);break}}}return u},function*(a,c,l,u={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&f.addresses===u.limits.addresses)throw new je('Streaming decode error - repeated field "addresses" had too many elements');for(let m of Bo.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...m,index:f.addresses};f.addresses++;break}case 2:{if(u.limits?.protocols!=null&&f.protocols===u.limits.protocols)throw new je('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:f.protocols,value:a.string()},f.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&&f.metadata===u.limits.metadata)throw new je('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}}),f.metadata++;break}case 7:{if(u.limits?.tags!=null&&f.tags===u.limits.tags)throw new je('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}}),f.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,r.codec())}r.encode=o;function s(a,c){return ke(a,r.codec(),c)}r.decode=s;function i(a,c){return Oe(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ae(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Bo||(Bo={}));var Uo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Uo||(Uo={}));function Ub(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=nn(e.publicKey,t);return Ll(n)}function _p(r,e,t){let n=kt.decode(e);return In(r,n,t)}function In(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:Ub(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:X(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Ap(r,e){return Kb(r.addresses,e.addresses)&&qb(r.protocols,e.protocols)&&$b(r.publicKey,e.publicKey)&&zb(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Vb(r.metadata,e.metadata)&&Hb(r.tags,e.tags)}function Kb(r,e){return Cp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Q(t.multiaddr,n.multiaddr)))}function qb(r,e){return Cp(r,e,(t,n)=>t===n)}function $b(r,e){return Ip(r,e)}function zb(r,e){return Ip(r,e)}function Vb(r,e){return Tp(r,e,(t,n)=>Q(t,n))}function Hb(r,e){return Tp(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Ip(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Q(r,e):!1}function Cp(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 Tp(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Rt="/",Lp=new TextEncoder().encode(Rt),Ki=Lp[0],Cr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ki)throw new Error("Invalid key")}toString(e="utf8"){return B(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rt))}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=Lp),this._buf[0]!==Ki){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ki,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ki;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rt).slice(1)}type(){return Wb(this.baseNamespace())}name(){return Gb(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rt)||(e+=Rt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rt):new r(e.slice(0,-1).join(Rt))}child(e){return this.toString()===Rt?e:e.toString()===Rt?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(),...jb(e.map(t=>t.namespaces()))])}};function Wb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Gb(r){let e=r.split(":");return e[e.length-1]}function jb(r){return[].concat(...r)}var Pu="/peers/";function Ko(r){if(!Ft(r)||r.type==null)throw new P("Invalid PeerId");let e=r.toCID().toString();return new Cr(`${Pu}${e}`)}async function Pp(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=X(i.multiaddr)),!Qt(i.multiaddr))throw new P("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.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(X(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function $i(r,e,t,n){if(e==null)throw new P("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new P("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new P("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=qi(d,{validate:Dp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=qi(d,{validate:kp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,m]of d)m==null?a.delete(h):a.set(h,m);a=qi([...a.entries()],{validate:Dp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[m,g]of d)g==null?h.delete(m):h.set(m,g);c=qi([...h.entries()],{validate:kp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Ge(o.id.publicKey):e.publicKey!=null?u=Ge(e.publicKey):r.publicKey!=null&&(u=Ge(r.publicKey));let f={addresses:await Pp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Q(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function qi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Dp(r,e){if(typeof r!="string")throw new P("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new P("Metadata value must be a Uint8Array")}function kp(r,e){if(typeof r!="string")throw new P("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new P("Tag value must be an integer");if(e.value<0||e.value>100)throw new P("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new P("Tag ttl must be an integer");if(e.ttl<0)throw new P("Tag ttl must be between greater than 0")}}function Rp(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 Op(r){let e=r.toString().split("/")[2],t=ue.parse(e,We);return So(t)}function Du(r,e,t){let n=Op(r);return _p(n,e,t)}function Yb(r,e){return{prefix:Pu,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Du(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Du(n.key,n.value,e),Du(o.key,o.value,e)))}}var zi=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=Su({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:Lu({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 o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}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(Ko(e),t)}async load(e,t){let n=Ko(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new tr;return In(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#r(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Yb(e??{},this.maxAddressAge),e)){let o=Op(t);if(o.equals(this.peerId))continue;let s=kt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield In(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ko(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new tr;return{peerPB:s,peer:In(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#r(e,t,n,o){t.updated=Date.now();let s=kt.encode(t);return await this.datastore.put(Ko(e),s,o),{peer:In(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Ap(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var ku=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 zi(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 No(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:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ft(t)?t:Ft(t?.expectedPeer)?t.expectedPeer:void 0,s=Ft(t)||t===void 0?n:t,i=await An.openAndCertify(e,Ar.DOMAIN,s),a=So(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Ar.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=An.createFromProtobuf(l.peerRecordEnvelope),f=Ar.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!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 Np(r,e={}){return new ku(r,e)}var Vi=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 Zb(r){return r[Symbol.asyncIterator]!=null}function Xb(r){if(Zb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ru=Xb;function Qb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Fp=Qb;function Jb(r){return r[Symbol.asyncIterator]!=null}function ew(r,e){let t=0;if(Jb(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Fp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Tr=ew;function tw(r){return r[Symbol.asyncIterator]!=null}function rw(r,e){return tw(r)?(async function*(){yield*(await No(r)).sort(e)})():(function*(){yield*No(r).sort(e)})()}var Ou=rw;function nw(r){return r[Symbol.asyncIterator]!=null}function ow(r,e){return nw(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 Nu=ow;var Hi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ru(this.putMany(e,n)),e=[],await Ru(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ou(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Tr(n,()=>o++>=s)}return e.limit!=null&&(n=Nu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ou(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Tr(n,()=>s++>=o)}return e.limit!=null&&(n=Nu(n,e.limit)),n}};var Wi=class extends Hi{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 Vi;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,o]of this.data.entries())yield{key:new Cr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Cr(n),t?.signal?.throwIfAborted()}};var re=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Mp=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Te=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),G=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ne(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var sw=N(421),Bp=ne(sw),ji=N(54),Yi=N(55),Zi=N(56),Mu=N(53),k6=ne(ji,z(N(421))),R6=ne(Yi,z(N(421))),O6=ne(Zi,z(N(421))),N6=ne(Te(Mu,Zi,ji,Yi),z(N(421))),Up=G(N(4),z(N(43))),Kp=G(z(N(42)),N(41),z(N(43))),Bu=Te(Up,Kp),Cn=Te(Bu,Mu,ji,Yi,Zi),F6=ne(Te(Bu,G(Te(Mu,Zi,ji,Yi),z(N(421))))),Uu=ne(Up),Ku=ne(Kp),M6=ne(Bu),qu=G(Cn,N(6)),qo=G(Cn,N(273)),$o=ne(G(qu,z(N(421)))),B6=ne(qo),$u=G(qo,re(460),z(N(421))),Xi=G(qo,re(461),z(N(421))),iw=Te($u,Xi),U6=ne($u),qp=ne(Xi),Fu=Te(Cn,qu,qo,$u,Xi),$p=Te(G(Fu,re(477),z(N(421)))),Lr=ne($p),zp=Te(G(Fu,re(478),z(N(421))),G(Fu,re(448),z(N(449)),re(477),z(N(421)))),zo=ne(zp),Vp=G(qo,re(280),z(N(466)),z(N(466)),z(N(421))),zu=ne(Vp),Hp=G(Xi,re(465),z(N(466)),z(N(466)),z(N(421))),Vu=ne(Hp),Gi=Te($p,zp,G(qu,z(N(421))),G(iw,z(N(421))),G(Cn,z(N(421))),Vp,Hp,N(421)),K6=ne(Gi),aw=G(z(Gi),re(290),Mp(re(281)),z(N(421))),Pr=ne(aw),cw=Te(G(Gi,re(290),re(281),z(N(421))),G(Gi,re(281),z(N(421))),G(re(281),z(N(421)))),Hu=ne(cw),lw=G(Cn,Te(G(N(6,"80")),G(N(6),re(480)),re(480)),z(N(481)),z(N(421))),q6=ne(lw),uw=G(Cn,Te(G(N(6,"443")),G(N(6,"443"),re(480)),G(N(6),re(443)),G(N(6),re(448),re(480)),G(re(448),re(480)),re(448),re(443)),z(N(481)),z(N(421))),$6=ne(uw),fw=Te(G(N(777),z(N(421)))),z6=ne(fw),dw=Te(G(N(400),z(N(421)))),V6=ne(dw);var Wp=864e13;var Qi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ce({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=V(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=dn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Wp-Date.now():0,lastVerified:o?Wp-Date.now():void 0})})}remove(e){let t=V(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!ve(o))continue;let s=V(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,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 o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),X(n)}confirm(e,t){let n=V(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=V(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Ji=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ce({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=V(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ct(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=V(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[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,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!ve(n))continue;let o=V(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);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,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,X(i)):e}confirm(e,t){if(!ve(e))return!1;let n=V(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!ve(e))return!1;let n=V(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[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),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var hw={maxObservedAddresses:10},ea=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??hw.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&&(Tt(e)||Gh(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:X(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(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var pw={maxObservedAddresses:10},ta=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??pw.maxObservedAddresses}get(e,t){if(Tt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!ve(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.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),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!ve(e))return e.toString();let t=V(e);return`${t.host}-${t.port}-${t.protocol}`}};var Gp=6e4,jp={maxObservedAddresses:10,addressVerificationTTL:Gp*10,addressVerificationRetry:Gp*5},mw=r=>r;function Wu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&mt(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var ra=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new ea(e,t),this.dnsMappings=new Qi(e,t),this.ipMappings=new Ji(e,t),this.transportAddresses=new ta(e,t),this.announceFilter=t.announceFilter??mw,this.observedAddressFilter=Io(1024),this.addressVerificationTTL=t.addressVerificationTTL??jp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??jp.addressVerificationRetry,this._updatePeerStoreAddresses=Po(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=>X(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>X(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>X(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=V(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=Wu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Wu(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=Wu(e,this.components.peerId);let n=!1;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 o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=X(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,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(X(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ct(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${ct(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!ve(e))return!1;let t=V(e);if(t.type!=="ip4"||dn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Lr.exactMatch(s)||zo.exactMatch(s),s=>$o.exactMatch(s),s=>qp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>V(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!To(l)).pop();if(a==null)continue;let c=V(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 Yp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Yp||(Yp={}));var na=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},oa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Tn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Vo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},sa=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ia=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},aa=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ho=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},ca=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},la=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ua=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},fa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},da=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Jt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Dr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ha=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},pa=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Gu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=zs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>cs(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")}},gw=["metrics","connectionProtector","dns"],yw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Zp(r={}){let e=new Gu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yw.includes(o)){let i=e.components[o];if(i==null&&!gw.includes(o))throw new na(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function Xp(r){let e={};for(let t of Object.values(r.components))for(let n of bw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of ww(t))if(e[n]!==!0)throw new oa(`Service "${xw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function bw(r){return Array.isArray(r?.[Bn])?r[Bn]:[]}function ww(r){return Array.isArray(r?.[Va])?r[Va]:[]}function xw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Qp(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Lr.matches(e)?!0:Tt(e)),r}var ee=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ma(r){if(Ft(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:mt(n),e.forEach(o=>{if(!Qt(o))throw new Ot("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new P("Multiaddrs must all have the same peer id or have no peer id")}else{let i=mt(s);if(t?.equals(i)!==!0)throw new P("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Bp.exactMatch(n)),{peerId:t,multiaddrs:e}}var Ew=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Jp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Ew;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Wo(r){let e=V(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new P(`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 P(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new cn(e.host,t)}function ju(r){return!Pr.exactMatch(r)}function ga(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>ju(s)))return n}var ya=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Wo(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 o=new Ye;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(ve(c.remoteAddr)){let f=V(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Jp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var em="last-dial-failure",tm="last-dial-success";var rm=100,ba=50;function vw(r,e){let t=$o.exactMatch(r.multiaddr),n=$o.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=zo.exactMatch(r.multiaddr),s=zo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Lr.exactMatch(r.multiaddr),a=Lr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Hu.exactMatch(r.multiaddr),l=Hu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=zu.exactMatch(r.multiaddr),f=zu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Vu.exactMatch(r.multiaddr),h=Vu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Sw(r,e){let t=To(r.multiaddr),n=To(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _w(r,e){let t=Tt(r.multiaddr),n=Tt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Aw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Iw(r,e){let t=Pr.exactMatch(r.multiaddr),n=Pr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function nm(r){return r.sort(vw).sort(Aw).sort(Iw).sort(_w).sort(Sw)}var wa=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Zu=Ua(sm(),1);function Xu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ln=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=Xu(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var jo=class extends Zu.default{#e;#r;#n=0;#h;#m=!1;#w=!1;#c;#C=0;#x=0;#l;#u;#a;#i=[];#s=0;#t;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ln,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.#r=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#t=new e.queueClass,this.#T=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.#f=e.autoStart===!1,this.#q()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#F(){return this.#r?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#D(),this.#P()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#_(o),!0}return!1}if(this.#l===void 0){let t=this.#C-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#_(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#_(t),!0}return!1}#_(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#A(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#L(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#t.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#F&&this.#M){let o=this.#t.dequeue();this.#r||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#D()},this.#c),this.#C=Date.now()+this.#c)}#D(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#A(),this.#n=this.#e?this.#o:0),this.#I(),this.#p()}#I(){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.#I()}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.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#$(),this.#y.delete(s),d}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=Lo(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:d}=t;u=Promise.race([u,new Promise((h,m)=>{l=()=>{m(d.reason)},d.addEventListener("abort",l,{once:!0})})])}let f=await u;n(f),this.emit("completed",f)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#t.enqueue(a,t);let c=()=>{if(this.#t instanceof Ln){this.#t.remove(a);return}this.#t.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.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.#f?(this.#f=!1,this.#I(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#t=new this.#T,this.#A(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#o===0&&this.#t.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#q(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#$(){this.#r||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#r||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function Ea(r){let e=[He.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Qu=60;function va(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:He[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:He[e.type],TTL:e.TTL??e.ttl??Qu,data:e.data instanceof Uint8Array?B(e.data):e.data}))}}var Lw=4;function Ju(r,e={}){let t=new jo({concurrency:e.queryConcurrency??Lw});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Ea(o.types).forEach(c=>{i.append("type",He[c])}),o.onProgress?.(new ee("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=va(await c.json());return o.onProgress?.(new ee("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function im(){return[Ju("https://cloudflare-dns.com/dns-query"),Ju("https://dns.google/resolve")]}var lm=Ua(cm(),1);var ef=class{lru;constructor(e){this.lru=(0,lm.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return va({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:He[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Qu)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function um(r){return new ef(r)}var Pw=1e3,Sa=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=um(e.cacheSize??Pw),this.logger=e.logger,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["."]=im())}async query(e,t={}){let n=Ea(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new ee("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new ee("dns:error",l))}}throw new wa(a,`DNS lookup of ${e} ${n} failed`)}};var He;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(He||(He={}));function fm(r={}){return new Sa(r)}var tf=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=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[He.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(X(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=fm()),this.dns)}},kr=new tf;async function rf(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new pa("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await rf(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Pn={maxParallelDials:ba,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kr}},_a=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Pn.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Pn.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Pn.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Pn.addressDialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Pn.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new xi({concurrency:t.maxParallelDials??Pn.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Ze.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:o}=ma(e);if(n!=null&&t.force!==!0){let i=ga(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected",i)),i}let s=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 o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new ee("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Fr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new ee("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new ee("dial-queue:start-dial"));let a=yt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??cf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.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 ee("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 Fr("Peer had more than maxPeerAddrsToDial");a++;let m=yt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:m});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[tm]:D(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p - %e",n,p)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[em]:D(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p - %e",n,p)}if(t.aborted)throw new ns(g.message);l.push(g)}finally{m.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:X(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Fr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ho("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await rf(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new ua(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?nm(l):l.sort(this.addressSorter);if(u.length===0)throw new Ho(`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",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Pr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Dw=Object.prototype.toString,kw=r=>Dw.call(r)==="[object Error]",Rw=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 lf(r){if(!(r&&kw(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?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:Rw.has(t)}function Ow(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.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Aa(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 uf(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var ff=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 Nw(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function Ia(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Fw(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function Mw({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof ff)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Nw(t,o);if(Ia(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(u),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Ia(n,a)<=0||Ia(n,a)<=0||i<=0||s instanceof TypeError&&!lf(s)||!await o.shouldRetry(h))throw s;let g=Ia(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let p=Math.min(d,g);return o.signal?.throwIfAborted(),await Fw(p,o),o.signal?.throwIfAborted(),!0}async function df(r,e={}){if(e={...e},Ow(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,uf("onFailedAttempt",e.onFailedAttempt),uf("shouldRetry",e.shouldRetry),uf("shouldConsumeRetry",e.shouldConsumeRetry),Aa("factor",e.factor,{min:0,allowInfinity:!1}),Aa("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Aa("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Aa("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await Mw({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ca=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 wi({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(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);dm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await df(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{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 o={};[...t.tags.keys()].forEach(s=>{s.startsWith(za)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),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=>dm(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 dm(r){for(let e of r.tags.keys())if(e.startsWith(za))return!0;return!1}var cf=50,hf={maxConnections:rm,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ta=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??hf.maxConnections,this.maxConnections<1)throw new P("Connection Manager maxConnections must be greater than 0");this.connections=new Ye,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=>Wo(X(n))),this.deny=(t.deny??[]).map(n=>Wo(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??hf.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ei({points:t.inboundConnectionThreshold??hf.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ya({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new _a(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ba,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections}),this.reconnectQueue=new Ca({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 o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Sf(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 _f(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([lt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));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 P("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,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.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 wt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new ee("connection:open",e));let{peerId:n,multiaddrs:o}=ma(e);if(this.peerId.equals(n))throw new Nr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=ga(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected")),t.onProgress?.(new ee("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??cf});if(s.status!=="open")throw new er("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Ot("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new ee("connection:opened",s)),s}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 o=>{try{await Promise.all([lt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(ve(e.remoteAddr)){let s=V(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(ve(e.remoteAddr)){let s=V(e.remoteAddr);return o.contains(s.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(ve(e.remoteAddr)){let o=V(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.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=>X(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Kw=1e4,qw="1.0.0",$w="ping",zw="ipfs",hm=32,Vw=!0,La=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??zw}/${$w}/${qw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Kw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Vw,this.timeout=new ri({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Bn]=["@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});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=yu(o);t=Date.now(),await Promise.all([s.write(tn(hm),{signal:n}),s.read({bytes:hm,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(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 Pa=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],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(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 Tn("No content routers available");let n=this,o=new mr;for await(let s of Sn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Tn("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 Tn("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 wt;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new wt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Da=globalThis.CustomEvent??Event;async function*pf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=be(),a=be(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(s.length===t&&(i=be(),await i.promise),u)break;let g={done:!1};s.push(g),m().then(p=>{g.done=!0,g.ok=!0,g.value=p,o.dispatchEvent(new Da("task-complete"))},p=>{g.done=!0,g.err=p,o.dispatchEvent(new Da("task-complete"))})}c=!0,o.dispatchEvent(new Da("task-complete"))}catch(m){l=m,o.dispatchEvent(new Da("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(m=>m.done)}function*d(){for(;s.length>0&&s[0].done;){let m=s[0];if(s.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*h(){for(;f();)for(let m=0;m<s.length;m++)if(s[m].done){let g=s[m];if(s.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=be(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var ka=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],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:B(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Vo("No peer routers available");if(e.toString()===this.peerId.toString())throw new sa("Should not try to find self");let n=this,o=Sn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new tr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Vo("No peer routers available");let n=this,o=Io(1024);for await(let s of pf((async function*(){let i=Sn(...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}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Ra=class extends Pe{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=yt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=be(),yield(await lt(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=yt([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 o=tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ze(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var mf=32,gf=64,Oa=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,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ce({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 ia(`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 aa(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:mf,maxOutboundStreams:gf,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new P("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}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 o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);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(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);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(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Na=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=Ce({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ce({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Mn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new P("Transport must have a valid tag");if(this.transports.has(t))throw new P(`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 o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ha(`No transport available for address ${String(e)}`);return t?.onProgress?.(new ee("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 wt("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(s=>{t.errors.set(s.toString(),new ca)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Uu.matches(c)?t.ipv4.attempts++:Ku.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Uu.matches(c)&&t.ipv4.success++,Ku.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Mn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new la(`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:
|
|
12
|
+
${e}[Error list was empty]`,t.trim()}return Nh(r,e)}Ke.formatters.e=r=>r==null?"undefined":Mh(r);function _y(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function zs(r){return{forComponent(e){return Bh(e,r)}}}function Bh(r,e){let t=_y(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ke(`${r}:trace`,e)),Object.assign(Ke(r,e),{error:Ke(`${r}:error`,e),trace:t,newScope:n=>Bh(`${r}:${n}`,e)})}function Fh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function pr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Vs(r){let e=Et(te.decode(`z${r}`));return on(e)}var Ye=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return pr(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 pr(this.map.values(),e=>e.key)}values(){return pr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var mr=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 pr(this.set.entries(),e=>{let t=Vs(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Vs(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pr(this.set.values(),e=>Vs(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Dl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Uh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Kh=new globalThis.TextEncoder;function Ay(r,e){let t=Dl[e],n=Uh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Iy(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Dl[e],o=Uh[e],s=r;for(;s.length>0;){let i=Kh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function kl(r,{size:e=32,utf8Buffer:t}={}){if(!Dl[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 Iy(r,e,t);r=Kh.encode(r)}return Ay(r,e)}var _o={hash:r=>Number(kl(r,{size:32})),hashV:(r,e)=>Cy(_o.hash(r,e))};function Cy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Rl=64,at=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Rl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ae(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function gr(r,e){return Math.floor(Math.random()*(e-r))+r}var yr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof at))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof at))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 at))throw new TypeError("Invalid Fingerprint");let t=gr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof at))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ty=500,Ao=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??_o,this.seed=e.seed??gr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new yr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new yr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[gr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new yr(this.bucketSize));for(let a=0;a<Ty;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 yr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new at(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ly={1:.5,2:.84,4:.95,8:.98};function Py(r=.001){return r>.002?2:r>1e-5?4:8}function qh(r,e=.001){let t=Py(e),n=Ly[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Rl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Hs=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??_o,this.seed=e.seed??gr(0,Math.pow(2,10)),this.filterSeries=[new Ao({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(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 Ao({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=D(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=D(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 Io(r,e=.001,t){return new Hs({...qh(r,e),...t??{}})}function Ol(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 W(r){let e=Ol(r);if(e==null)throw new P(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Ws=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var $h=45,Dy=15,sn=new Ws;function Gs(r){if(!(r.length>Dy))return sn.new(r).parseWith(()=>sn.readIPv4Addr())}function js(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>$h))return sn.new(r).parseWith(()=>sn.readIPv6Addr())}function an(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>$h)return;let t=sn.new(r).parseWith(()=>sn.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 zh(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Vh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Nl(r){switch(r.length){case br:return r.join(".");case wr:{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 Hh(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 o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Wh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var br=4,wr=16,y_=parseInt("0xFFFF",16),ky=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Co(r,e){e.length===wr&&r.length===br&&zh(e,0,11)&&(e=e.slice(12)),e.length===br&&r.length===wr&&Vh(r,ky,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 o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Gh(r,e){if(typeof e=="string"&&(e=an(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 Fl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=br,o=Gs(e);if(o==null&&(n=wr,o=js(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Ml(s,8*n);return{network:Co(o,i),mask:i}}function Ml(r,e){if(e!==8*br&&e!==8*wr)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 o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var cn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Fl(e));else{let n=an(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=an(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ml(o,8*n.length);this.network=Co(n,this.mask)}}contains(e){return Gh({network:this.network,mask:this.mask},e)}toString(){let e=Hh(this.mask),t=e!==-1?String(e):Wh(this.mask);return Nl(this.network)+"/"+t}};function jh(r){try{let e=W(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 Yh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function To(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return Yh(e.host);default:return!1}}catch{return!1}}function ve(r){return Ol(r)!==null}function ct(r){return!!Gs(r)}function Ys(r){return!!js(r)}var Jh=Ua(Qh(),1),Uy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Ky=Uy.map(r=>new Jh.Netmask(r));function Vl(r){for(let e of Ky)if(e.contains(r))return!0;return!1}function qy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function $y(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Vl(o)}function zy(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Vy(r){let e=r.split(":"),t=e[e.length-1];return Vl(t)}function Hy(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 dn(r){if(ct(r))return Vl(r);if(qy(r))return $y(r);if(zy(r))return Vy(r);if(Ys(r))return Hy(r)}function Tt(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return dn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function be(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Xs=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}},hn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Xs(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 Xs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Hl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pn(r={}){return Wy(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 Wy(r,e){e=e??{};let t=e.onEnd,n=new hn,o,s,i,a=be(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,y)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){y(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=be()})}},l=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new hn,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(e?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?u(p):l({done:!0})),h=()=>(n=new hn,d(),{done:!0}),m=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async p=>{let y=p?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,S;y!=null&&(v=new Promise((k,L)=>{S=()=>{L(new Hl)},y.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&y!=null&&y?.removeEventListener("abort",S)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(p){return g.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(p){return g.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:p=>g.onEmpty(p)},o}var Wl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ep=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ep(i));return}if(i&&(c=()=>{d(ep(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Wl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(m){d(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Gy=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 jy(r,e,t){let n,o=new Promise((s,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}=Gy(r),f=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(g){n(),i(g);return}c.push(m),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Lo(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=jy(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Po(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Qs=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}},Js=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Er=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function Yy(r){return r.reason}async function ze(r,e,t){if(e==null)return r;let n=t?.translateError??Yy;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var ei=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=be(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ze)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Zy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ti=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Zy(),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 Ze),this.cleanup())}async join(e){let t=new ei(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 ze(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var mn=class extends Pe{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=Po(this.emitEmpty.bind(this),1),this.emitIdle=Po(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 Js;let n=new ti(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ze)}),this.clear()}async onEmpty(e){this.size!==0&&await lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(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=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ze("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function yt(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var gn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Xy=1.2,Qy=2,Jy=5e3,eb=6e4,tb=5e3,ri=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??tb;this.success=new gn(t),this.failure=new gn(t),this.next=new gn(t),this.failureMultiplier=e.failureMultiplier??Qy,this.timeoutMultiplier=e.timeoutMultiplier??Xy,this.minTimeout=e.minTimeout??Jy,this.maxTimeout=e.maxTimeout??eb,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),o=yt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}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 Se=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Lt=class extends Error{static name="ValidationError";name="ValidationError"},ni=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},oi=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function jl(r){return e=>B(e,r)}function Yl(r){return e=>D(e,r)}function yn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function vr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function tp(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=D(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 o=vr(n);return Qe([t,o],t.length+o.length)}function rp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=vr(n);return Qe([t,o],t.length+o.length)}function Zl(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=B(e,"base32"),o=yn(t);return`${n}:${o}`}var Xl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Se("Invalid byte value in IP address");e[n]=o}),e},np=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ct(t[n]),i;s&&(i=Xl(t[n]),t[n]=B(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,B(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Se("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},op=function(r){if(r.byteLength!==4)throw new Se("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},sp=function(r){if(r.byteLength!==16)throw new Se("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.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 Se(`Invalid IPv6 address "${t}"`)}};function ip(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Se(`Invalid IPv6 address "${r}"`)}}var Gl=Object.values(zn).map(r=>r.decoder),rb=(function(){let r=Gl[0].or(Gl[1]);return Gl.slice(2).forEach(e=>r=r.or(e)),r})();function ap(r){return rb.decode(r)}function cp(r){return e=>r.encoder.encode(e)}function nb(r){if(parseInt(r).toString()!==r)throw new Lt("Value must be an integer")}function ob(r){if(r<0)throw new Lt("Value must be a positive integer, or zero")}function sb(r){return e=>{if(e>r)throw new Lt(`Value must be smaller than or equal to ${r}`)}}function ib(...r){return e=>{for(let t of r)t(e)}}var Do=ib(nb,ob,sb(65535));var we=-1,Ql=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 oi(`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)}))}},Dt=new Ql,xb=[{code:4,name:"ip4",size:32,valueToBytes:Xl,bytesToValue:op,validate:r=>{if(!ct(r))throw new Lt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:273,name:"udp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:33,name:"dccp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:41,name:"ip6",size:128,valueToBytes:np,bytesToValue:sp,stringToValue:ip,validate:r=>{if(!Ys(r))throw new Lt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:we},{code:43,name:"ipcidr",size:8,bytesToValue:jl("base10"),valueToBytes:Yl("base10")},{code:53,name:"dns",size:we},{code:54,name:"dns4",size:we},{code:55,name:"dns6",size:we},{code:56,name:"dnsaddr",size:we},{code:132,name:"sctp",size:16,valueToBytes:vr,bytesToValue:yn,validate:Do},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:we,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:we,bytesToValue:jl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Yl("base58btc")(r):ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Zl,valueToBytes:tp},{code:445,name:"onion3",size:296,bytesToValue:Zl,valueToBytes:rp},{code:446,name:"garlic64",size:we},{code:447,name:"garlic32",size:we},{code:448,name:"tls"},{code:449,name:"sni",size:we},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:we,bytesToValue:cp(ic),valueToBytes:ap},{code:480,name:"http"},{code:481,name:"http-path",size:we,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:we}];xb.forEach(r=>{Dt.addProtocol(r)});function lp(r){let e=[],t=0;for(;t<r.length;){let n=ur(r,t),o=Dt.getProtocol(n),s=ye(n),i=Eb(o,r,t+s),a=0;i>0&&o.size===we&&(a=ye(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??B(f)}e.push(l),t+=c}return e}function up(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Dt.getProtocol(n.code),s=ye(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,o.size===we&&(c=ye(a)));let l=new Uint8Array(s+c+a),u=0;en(n.code,l,u),u+=s,i!=null&&(o.size===we&&(en(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Qe(t,e)}function fp(r){if(r.charAt(0)!=="/")throw new Se('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Dt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Se(`Component ${o} 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 Se(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Se("Incomplete multiaddr");return e}function dp(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Dt.getProtocol(e.code);if(t==null)throw new Se(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Eb(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ur(e,t)}var vb=Symbol.for("nodejs.util.inspect.custom"),du=Symbol.for("@multiformats/multiaddr");function Sb(r){if(r==null&&(r="/"),Qt(r))return r.getComponents();if(r instanceof Uint8Array)return lp(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),fp(r);if(Array.isArray(r))return r;throw new Se("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ui=class r{[du]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=Sb(e),t.validate!==!1&&_b(this)}get bytes(){return this.#n==null&&(this.#n=up(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=dp(this.#e)),this.#r}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(),o=n.lastIndexOf(t);if(o<0)throw new ni(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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 Q(this.bytes,e.bytes)}[vb](){return`Multiaddr(${this.toString()})`}};function _b(r){r.getComponents().forEach(e=>{let t=Dt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Qt(r){return!!r?.[du]}function X(r){return new ui(r)}var hu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=be(),this.haveNext=be()}[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=be(),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=be(),await ze(this.readNext.promise,t?.signal,t)}};function hp(){return new hu}function Ab(r){return r[Symbol.asyncIterator]!=null}async function Ib(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Cb(r){let e=new AbortController,t=hp();Ib(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Tb(r){for(let e of r)yield*e}function Lb(...r){let e=[];for(let t of r)Ab(t)||e.push(t);return e.length===r.length?Tb(e):Cb(r)}var Sn=Lb;var Pb=4194304,fi=class extends Error{static name="UnwrappedError";name="UnwrappedError"},mu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},yu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Db(r){return typeof r?.closeRead=="function"}function kb(r){return typeof r?.close=="function"}function pu(r){return Db(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:kb(r)?r.status!=="open":!1}function Rb(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function bu(r,e){let t=e?.maxBufferSize??Pb,n=new J,o,s=!1;if(!Rb(r))throw new P("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new fi("Stream was unwrapped");if(pu(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Er(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await ze(o.promise,u?.signal),pu(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(pu(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Er(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new fi("Stream was unwrapped");r.send(u)||await lt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function di(r,e={}){let t=bu(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ye(e.maxDataLength));let n=e?.lengthDecoder??ur,o=e?.lengthEncoder??Gt;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(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new mu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new yu(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new gu(`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 Er(`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 Er(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var hi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_n=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},pi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ko=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mi(r){return r[Symbol.asyncIterator]!=null}function pp(r,e){if(r.byteLength>e)throw new _n("Message length too long")}var yi=r=>{let e=ye(r),t=_e(e);return Gt(r,t),yi.bytes=e,t};yi.bytes=0;function bi(r,e){e=e??{};let t=e.lengthEncoder??yi,n=e?.maxDataLength??4194304;function*o(s){pp(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mi(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}bi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??yi,n=e?.maxDataLength??4194304;return pp(r,n),new J(t(r.byteLength),r)};var _r;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_r||(_r={}));var xu=r=>{let e=ur(r);return xu.bytes=ye(e),e};xu.bytes=0;function wu(r,e){let t=new J,n=_r.LENGTH,o=-1,s=e?.lengthDecoder??xu,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===_r.LENGTH)try{if(o=s(t),o<0)throw new hi("Invalid message length");if(o>a)throw new _n("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=_r.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new pi("Message length length too long");break}throw l}if(n===_r.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=_r.LENGTH}}}return mi(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ko("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ko("Unexpected end of input")})()}wu.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return wu(n,{...e??{},onLength:s=>{t=s}})};var wi=class extends mn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xi=class extends mn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Ei=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 Eu}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Qs("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Eu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var vu=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 Ce(r){let{name:e,metrics:t}=r,n;return t!=null?n=new vu({name:e,metrics:t}):n=new Map,n}var Su=class extends Ye{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 _u(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Su({name:e,metrics:t}):n=new Ye,n}var Ro;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ae(0),payloadType:ae(0),payload:ae(0),signature:ae(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Ro||(Ro={}));var vi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var An=class r{static createFromProtobuf=e=>{let t=Ro.decode(e),n=nn(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 o=e.domain,s=e.codec,i=e.marshal(),a=mp(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new vi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({publicKey:Ge(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Q(this.marshal(),e.marshal())}async validate(e,t){let n=mp(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},mp=(r,e,t)=>{let n=D(r),o=Gt(n.byteLength),s=Gt(e.length),i=Gt(t.length);return new J(o,n,s,e,i,t)};var gp="libp2p-peer-record",yp=Uint8Array.from([3,1]);var Oo;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ne((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let m={multiaddr:ae(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let p=f.uint32();p>>>3===1?m.multiaddr=f.bytes():f.skipType(p&7)}return m},function*(f,d,h,m={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let p=f.uint32();p>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(p&7)}})),a);function c(f){return Re(f,i.codec())}i.encode=c;function l(f,d){return ke(f,i.codec(),d)}i.decode=l;function u(f,d){return Oe(f,i.codec(),d)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((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:ae(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>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 je('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(f&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>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 je('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(d&7);break}}}})),t);function n(i){return Re(i,r.codec())}r.encode=n;function o(i,a){return ke(i,r.codec(),a)}r.decode=o;function s(i,a){return Oe(i,r.codec(),a)}r.stream=s})(Oo||(Oo={}));function bp(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ar=class r{static createFromProtobuf=e=>{let t=Oo.decode(e),n=on(Et(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=gp;static CODEC=yp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Oo.encode({peerId:this.peerId.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||!bp(this.multiaddrs,e.multiaddrs))}};function Nb(r){return r[Symbol.asyncIterator]!=null}function Fb(r){if(Nb(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 No=Fb;var Ve=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Si(r,e,t,n){let o=new Ve(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Iu(t,"abort",f),Iu(r,e,l),Iu(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.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.`))},f=()=>{c(),a(o)};Au(t,"abort",f),Au(r,e,l),Au(r,s,u)})}function Au(r,e,t){r!=null&&(wp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Iu(r,e,t){r!=null&&(wp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function wp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var _i=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ai=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 Ve)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Mb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Mb(),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 Ve),this.cleanup())}async join(e={}){let t=new Ai(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 ze(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 Cu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Fo=class extends Pe{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=Cu(this.emitEmpty.bind(this),1),this.emitIdle=Cu(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 _i;let n=new Ii(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ve)}),this.clear()}async onEmpty(e){this.size!==0&&await Si(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Si(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Si(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=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ve("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ci="lock:worker:request-read",Ti="lock:worker:abort-read-request",Li="lock:worker:release-read",Pi="lock:master:grant-read",Di="lock:master:error-read",ki="lock:worker:request-write",Ri="lock:worker:abort-write-request",Oi="lock:worker:release-write",Ni="lock:master:grant-write",Fi="lock:master:error-write",Mi="lock:worker:finalize",Bi="mortice",xp={singleProcess:!1};var Tu=(r,e,t,n,o,s,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===o&&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(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Mi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var Ep=(r=10)=>Math.random().toString().substring(2,r+2);var Ui=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Bi)}readLock(e){return this.sendRequest(Ci,Ti,Pi,Di,Li,e)}writeLock(e){return this.sendRequest(ki,Ri,Ni,Fi,Oi,e)}finalize(){this.channel.postMessage({type:Mi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Ep();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 f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var vp=r=>{if(r=Object.assign({},xp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Bi),n=new Pe;return t.addEventListener("message",Tu(n,t,"requestReadLock","abortReadLockRequest",Ci,Ti,Di,Li,Pi)),t.addEventListener("message",Tu(n,t,"requestWriteLock","abortWriteLockRequest",ki,Ri,Fi,Oi,Ni)),n}return new Ui(r.name)};var Ir=new Map,Mo;function Sp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Bb(r){if(Mo==null&&(Mo=vp(r),!Sp(Mo))){let e=Mo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Ir.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.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,o=t.detail.identifier,s=Ir.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.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,o=Ir.get(n);o?.finalize()})}return Mo}async function Lu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ve)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var _p=(r,e)=>{let t=Ir.get(r);if(t!=null)return t;let n=Bb(e);if(Sp(n))return t=n,Ir.set(r,t),t;let o=new Fo({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Lu(s,i);s=new Fo({concurrency:e.concurrency,autoStart:!1});let a=s,c=Lu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Lu(o,i)},finalize:()=>{Ir.delete(r)},queue:o},Ir.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Ub={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Pu(r){let e=Object.assign({},Ub,r);return _p(e.name,e)}var kt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),m.lengthDelimited!==!1&&h.ldelim()},(d,h,m={})=>{let g={key:"",value:ae(0)},p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,m,g={}){let p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${m}.key`,value:d.string()};break}case 2:{yield{field:`${m}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Uo.codec().encode(d.value,h)),m.lengthDelimited!==!1&&h.ldelim()},(d,h,m={})=>{let g={key:""},p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=Uo.codec().decode(d,d.uint32(),{limits:m.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,m,g={}){let p=h==null?d.len:d.pos+h;for(;d.pos<p;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${m}.key`,value:d.string()};break}case 2:{yield*Uo.codec().stream(d,d.uint32(),`${m}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((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),Bo.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,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[u,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:f},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},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new je('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Bo.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 je('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 po('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 po('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(d&7);break}}}return u},function*(a,c,l,u={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&f.addresses===u.limits.addresses)throw new je('Streaming decode error - repeated field "addresses" had too many elements');for(let m of Bo.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...m,index:f.addresses};f.addresses++;break}case 2:{if(u.limits?.protocols!=null&&f.protocols===u.limits.protocols)throw new je('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:f.protocols,value:a.string()},f.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&&f.metadata===u.limits.metadata)throw new je('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}}),f.metadata++;break}case 7:{if(u.limits?.tags!=null&&f.tags===u.limits.tags)throw new je('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}}),f.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,r.codec())}r.encode=o;function s(a,c){return ke(a,r.codec(),c)}r.decode=s;function i(a,c){return Oe(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ae(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Bo||(Bo={}));var Uo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Uo||(Uo={}));function Kb(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=nn(e.publicKey,t);return Ll(n)}function Ap(r,e,t){let n=kt.decode(e);return In(r,n,t)}function In(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:Kb(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:X(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Ip(r,e){return qb(r.addresses,e.addresses)&&$b(r.protocols,e.protocols)&&zb(r.publicKey,e.publicKey)&&Vb(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Hb(r.metadata,e.metadata)&&Wb(r.tags,e.tags)}function qb(r,e){return Tp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Q(t.multiaddr,n.multiaddr)))}function $b(r,e){return Tp(r,e,(t,n)=>t===n)}function zb(r,e){return Cp(r,e)}function Vb(r,e){return Cp(r,e)}function Hb(r,e){return Lp(r,e,(t,n)=>Q(t,n))}function Wb(r,e){return Lp(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Cp(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Q(r,e):!1}function Tp(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 Lp(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Rt="/",Pp=new TextEncoder().encode(Rt),Ki=Pp[0],Cr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ki)throw new Error("Invalid key")}toString(e="utf8"){return B(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rt))}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=Pp),this._buf[0]!==Ki){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ki,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ki;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rt).slice(1)}type(){return Gb(this.baseNamespace())}name(){return jb(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rt)||(e+=Rt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rt):new r(e.slice(0,-1).join(Rt))}child(e){return this.toString()===Rt?e:e.toString()===Rt?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(),...Yb(e.map(t=>t.namespaces()))])}};function Gb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function jb(r){let e=r.split(":");return e[e.length-1]}function Yb(r){return[].concat(...r)}var Du="/peers/";function Ko(r){if(!Ft(r)||r.type==null)throw new P("Invalid PeerId");let e=r.toCID().toString();return new Cr(`${Du}${e}`)}async function Dp(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=X(i.multiaddr)),!Qt(i.multiaddr))throw new P("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.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(X(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function $i(r,e,t,n){if(e==null)throw new P("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new P("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new P("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=qi(d,{validate:kp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=qi(d,{validate:Rp,map:Op})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,m]of d)m==null?a.delete(h):a.set(h,m);a=qi([...a.entries()],{validate:kp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[m,g]of d)g==null?h.delete(m):h.set(m,g);c=qi([...h.entries()],{validate:Rp,map:Op})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Ge(o.id.publicKey):e.publicKey!=null?u=Ge(e.publicKey):r.publicKey!=null&&(u=Ge(r.publicKey));let f={addresses:await Dp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Q(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function qi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function kp(r,e){if(typeof r!="string")throw new P("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new P("Metadata value must be a Uint8Array")}function Rp(r,e){if(typeof r!="string")throw new P("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new P("Tag value must be an integer");if(e.value<0||e.value>100)throw new P("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new P("Tag ttl must be an integer");if(e.ttl<0)throw new P("Tag ttl must be between greater than 0")}}function Op(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 Np(r){let e=r.toString().split("/")[2],t=ue.parse(e,We);return So(t)}function ku(r,e,t){let n=Np(r);return Ap(n,e,t)}function Zb(r,e){return{prefix:Du,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ku(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ku(n.key,n.value,e),ku(o.key,o.value,e)))}}var zi=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=_u({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:Pu({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 o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}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(Ko(e),t)}async load(e,t){let n=Ko(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new tr;return In(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#r(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await $i(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Zb(e??{},this.maxAddressAge),e)){let o=Np(t);if(o.equals(this.peerId))continue;let s=kt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield In(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ko(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new tr;return{peerPB:s,peer:In(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#r(e,t,n,o){t.updated=Date.now();let s=kt.encode(t);return await this.datastore.put(Ko(e),s,o),{peer:In(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Ip(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Ru=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 zi(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 No(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:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ft(t)?t:Ft(t?.expectedPeer)?t.expectedPeer:void 0,s=Ft(t)||t===void 0?n:t,i=await An.openAndCertify(e,Ar.DOMAIN,s),a=So(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Ar.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=An.createFromProtobuf(l.peerRecordEnvelope),f=Ar.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!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 Fp(r,e={}){return new Ru(r,e)}var Vi=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 Xb(r){return r[Symbol.asyncIterator]!=null}function Qb(r){if(Xb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ou=Qb;function Jb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Mp=Jb;function ew(r){return r[Symbol.asyncIterator]!=null}function tw(r,e){let t=0;if(ew(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Mp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Tr=tw;function rw(r){return r[Symbol.asyncIterator]!=null}function nw(r,e){return rw(r)?(async function*(){yield*(await No(r)).sort(e)})():(function*(){yield*No(r).sort(e)})()}var Nu=nw;function ow(r){return r[Symbol.asyncIterator]!=null}function sw(r,e){return ow(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 Fu=sw;var Hi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ou(this.putMany(e,n)),e=[],await Ou(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Nu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Tr(n,()=>o++>=s)}return e.limit!=null&&(n=Fu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Nu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Tr(n,()=>s++>=o)}return e.limit!=null&&(n=Fu(n,e.limit)),n}};var Wi=class extends Hi{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 Vi;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,o]of this.data.entries())yield{key:new Cr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Cr(n),t?.signal?.throwIfAborted()}};var re=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Bp=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Te=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),G=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ne(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var iw=N(421),Up=ne(iw),ji=N(54),Yi=N(55),Zi=N(56),Bu=N(53),R6=ne(ji,z(N(421))),O6=ne(Yi,z(N(421))),N6=ne(Zi,z(N(421))),F6=ne(Te(Bu,Zi,ji,Yi),z(N(421))),Kp=G(N(4),z(N(43))),qp=G(z(N(42)),N(41),z(N(43))),Uu=Te(Kp,qp),Cn=Te(Uu,Bu,ji,Yi,Zi),M6=ne(Te(Uu,G(Te(Bu,Zi,ji,Yi),z(N(421))))),Ku=ne(Kp),qu=ne(qp),B6=ne(Uu),$u=G(Cn,N(6)),qo=G(Cn,N(273)),$o=ne(G($u,z(N(421)))),U6=ne(qo),zu=G(qo,re(460),z(N(421))),Xi=G(qo,re(461),z(N(421))),aw=Te(zu,Xi),K6=ne(zu),$p=ne(Xi),Mu=Te(Cn,$u,qo,zu,Xi),zp=Te(G(Mu,re(477),z(N(421)))),Lr=ne(zp),Vp=Te(G(Mu,re(478),z(N(421))),G(Mu,re(448),z(N(449)),re(477),z(N(421)))),zo=ne(Vp),Hp=G(qo,re(280),z(N(466)),z(N(466)),z(N(421))),Vu=ne(Hp),Wp=G(Xi,re(465),z(N(466)),z(N(466)),z(N(421))),Hu=ne(Wp),Gi=Te(zp,Vp,G($u,z(N(421))),G(aw,z(N(421))),G(Cn,z(N(421))),Hp,Wp,N(421)),q6=ne(Gi),cw=G(z(Gi),re(290),Bp(re(281)),z(N(421))),Pr=ne(cw),lw=Te(G(Gi,re(290),re(281),z(N(421))),G(Gi,re(281),z(N(421))),G(re(281),z(N(421)))),Wu=ne(lw),uw=G(Cn,Te(G(N(6,"80")),G(N(6),re(480)),re(480)),z(N(481)),z(N(421))),$6=ne(uw),fw=G(Cn,Te(G(N(6,"443")),G(N(6,"443"),re(480)),G(N(6),re(443)),G(N(6),re(448),re(480)),G(re(448),re(480)),re(448),re(443)),z(N(481)),z(N(421))),z6=ne(fw),dw=Te(G(N(777),z(N(421)))),V6=ne(dw),hw=Te(G(N(400),z(N(421)))),H6=ne(hw);var Gp=864e13;var Qi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ce({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=W(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=dn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Gp-Date.now():0,lastVerified:o?Gp-Date.now():void 0})})}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!ve(o))continue;let s=W(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,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 o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),X(n)}confirm(e,t){let n=W(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=W(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Ji=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ce({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ct(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[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,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!ve(n))continue;let o=W(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);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,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,X(i)):e}confirm(e,t){if(!ve(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!ve(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[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),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var pw={maxObservedAddresses:10},ea=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??pw.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&&(Tt(e)||jh(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:X(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(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var mw={maxObservedAddresses:10},ta=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??mw.maxObservedAddresses}get(e,t){if(Tt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!ve(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.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),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!ve(e))return e.toString();let t=W(e);return`${t.host}-${t.port}-${t.protocol}`}};var jp=6e4,Yp={maxObservedAddresses:10,addressVerificationTTL:jp*10,addressVerificationRetry:jp*5},gw=r=>r;function Gu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&mt(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var ra=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new ea(e,t),this.dnsMappings=new Qi(e,t),this.ipMappings=new Ji(e,t),this.transportAddresses=new ta(e,t),this.announceFilter=t.announceFilter??gw,this.observedAddressFilter=Io(1024),this.addressVerificationTTL=t.addressVerificationTTL??Yp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Yp.addressVerificationRetry,this._updatePeerStoreAddresses=Po(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=>X(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>X(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>X(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=W(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=Gu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Gu(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=Gu(e,this.components.peerId);let n=!1;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 o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=X(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,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(X(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ct(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${ct(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!ve(e))return!1;let t=W(e);if(t.type!=="ip4"||dn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Lr.exactMatch(s)||zo.exactMatch(s),s=>$o.exactMatch(s),s=>$p.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>W(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!To(l)).pop();if(a==null)continue;let c=W(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 Zp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Zp||(Zp={}));var na=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},oa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Tn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Vo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},sa=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ia=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},aa=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ho=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},ca=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},la=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ua=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},fa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},da=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Jt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Dr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ha=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},pa=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var ju=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=zs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>cs(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")}},yw=["metrics","connectionProtector","dns"],bw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Xp(r={}){let e=new ju(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!bw.includes(o)){let i=e.components[o];if(i==null&&!yw.includes(o))throw new na(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function Qp(r){let e={};for(let t of Object.values(r.components))for(let n of ww(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of xw(t))if(e[n]!==!0)throw new oa(`Service "${Ew(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function ww(r){return Array.isArray(r?.[Bn])?r[Bn]:[]}function xw(r){return Array.isArray(r?.[Va])?r[Va]:[]}function Ew(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Jp(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Lr.matches(e)?!0:Tt(e)),r}var ee=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ma(r){if(Ft(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:mt(n),e.forEach(o=>{if(!Qt(o))throw new Ot("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new P("Multiaddrs must all have the same peer id or have no peer id")}else{let i=mt(s);if(t?.equals(i)!==!0)throw new P("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Up.exactMatch(n)),{peerId:t,multiaddrs:e}}var vw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function em(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??vw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Wo(r){let e=W(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new P(`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 P(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new cn(e.host,t)}function Yu(r){return!Pr.exactMatch(r)}function ga(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Yu(s)))return n}var ya=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Wo(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 o=new Ye;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(ve(c.remoteAddr)){let f=W(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await em(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var tm="last-dial-failure",rm="last-dial-success";var nm=100,ba=50;function Sw(r,e){let t=$o.exactMatch(r.multiaddr),n=$o.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=zo.exactMatch(r.multiaddr),s=zo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Lr.exactMatch(r.multiaddr),a=Lr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Wu.exactMatch(r.multiaddr),l=Wu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Vu.exactMatch(r.multiaddr),f=Vu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Hu.exactMatch(r.multiaddr),h=Hu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function _w(r,e){let t=To(r.multiaddr),n=To(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Aw(r,e){let t=Tt(r.multiaddr),n=Tt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Iw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Cw(r,e){let t=Pr.exactMatch(r.multiaddr),n=Pr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function om(r){return r.sort(Sw).sort(Iw).sort(Cw).sort(Aw).sort(_w)}var wa=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Xu=Ua(im(),1);function Qu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ln=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=Qu(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var jo=class extends Xu.default{#e;#r;#n=0;#h;#m=!1;#w=!1;#c;#C=0;#x=0;#l;#u;#a;#i=[];#s=0;#t;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ln,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.#r=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#t=new e.queueClass,this.#T=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.#f=e.autoStart===!1,this.#q()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#F(){return this.#r?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#D(),this.#P()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#_(o),!0}return!1}if(this.#l===void 0){let t=this.#C-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#_(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#_(t),!0}return!1}#_(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#A(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#L(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#t.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#F&&this.#M){let o=this.#t.dequeue();this.#r||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#D()},this.#c),this.#C=Date.now()+this.#c)}#D(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#A(),this.#n=this.#e?this.#o:0),this.#I(),this.#p()}#I(){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.#I()}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.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#$(),this.#y.delete(s),d}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=Lo(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:d}=t;u=Promise.race([u,new Promise((h,m)=>{l=()=>{m(d.reason)},d.addEventListener("abort",l,{once:!0})})])}let f=await u;n(f),this.emit("completed",f)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#t.enqueue(a,t);let c=()=>{if(this.#t instanceof Ln){this.#t.remove(a);return}this.#t.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.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.#f?(this.#f=!1,this.#I(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#t=new this.#T,this.#A(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#o===0&&this.#t.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#q(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#$(){this.#r||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#r||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function Ea(r){let e=[He.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Ju=60;function va(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:He[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:He[e.type],TTL:e.TTL??e.ttl??Ju,data:e.data instanceof Uint8Array?B(e.data):e.data}))}}var Pw=4;function ef(r,e={}){let t=new jo({concurrency:e.queryConcurrency??Pw});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Ea(o.types).forEach(c=>{i.append("type",He[c])}),o.onProgress?.(new ee("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=va(await c.json());return o.onProgress?.(new ee("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function am(){return[ef("https://cloudflare-dns.com/dns-query"),ef("https://dns.google/resolve")]}var um=Ua(lm(),1);var tf=class{lru;constructor(e){this.lru=(0,um.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return va({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:He[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Ju)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function fm(r){return new tf(r)}var Dw=1e3,Sa=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=fm(e.cacheSize??Dw),this.logger=e.logger,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["."]=am())}async query(e,t={}){let n=Ea(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new ee("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new ee("dns:error",l))}}throw new wa(a,`DNS lookup of ${e} ${n} failed`)}};var He;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(He||(He={}));function dm(r={}){return new Sa(r)}var rf=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=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[He.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(X(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=dm()),this.dns)}},kr=new rf;async function nf(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new pa("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await nf(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Pn={maxParallelDials:ba,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kr}},_a=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Pn.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Pn.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Pn.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Pn.addressDialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Pn.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new xi({concurrency:t.maxParallelDials??Pn.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Ze.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:o}=ma(e);if(n!=null&&t.force!==!0){let i=ga(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected",i)),i}let s=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 o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new ee("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Fr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new ee("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new ee("dial-queue:start-dial"));let a=yt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??lf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.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 ee("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 Fr("Peer had more than maxPeerAddrsToDial");a++;let m=yt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:m});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[rm]:D(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p - %e",n,p)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[tm]:D(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p - %e",n,p)}if(t.aborted)throw new ns(g.message);l.push(g)}finally{m.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:X(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Fr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ho("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await nf(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new ua(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?om(l):l.sort(this.addressSorter);if(u.length===0)throw new Ho(`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",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Pr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var kw=Object.prototype.toString,Rw=r=>kw.call(r)==="[object Error]",Ow=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 uf(r){if(!(r&&Rw(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?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:Ow.has(t)}function Nw(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.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Aa(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 ff(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var df=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 Fw(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function Ia(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Mw(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function Bw({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof df)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Fw(t,o);if(Ia(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(u),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Ia(n,a)<=0||Ia(n,a)<=0||i<=0||s instanceof TypeError&&!uf(s)||!await o.shouldRetry(h))throw s;let g=Ia(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let p=Math.min(d,g);return o.signal?.throwIfAborted(),await Mw(p,o),o.signal?.throwIfAborted(),!0}async function hf(r,e={}){if(e={...e},Nw(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,ff("onFailedAttempt",e.onFailedAttempt),ff("shouldRetry",e.shouldRetry),ff("shouldConsumeRetry",e.shouldConsumeRetry),Aa("factor",e.factor,{min:0,allowInfinity:!1}),Aa("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Aa("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Aa("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await Bw({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ca=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 wi({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(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);hm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await hf(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{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 o={};[...t.tags.keys()].forEach(s=>{s.startsWith(za)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),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=>hm(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 hm(r){for(let e of r.tags.keys())if(e.startsWith(za))return!0;return!1}var lf=50,pf={maxConnections:nm,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ta=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??pf.maxConnections,this.maxConnections<1)throw new P("Connection Manager maxConnections must be greater than 0");this.connections=new Ye,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=>Wo(X(n))),this.deny=(t.deny??[]).map(n=>Wo(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??pf.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ei({points:t.inboundConnectionThreshold??pf.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ya({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new _a(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ba,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections}),this.reconnectQueue=new Ca({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 o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await _f(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 Af(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([lt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));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 P("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,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.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 wt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new ee("connection:open",e));let{peerId:n,multiaddrs:o}=ma(e);if(this.peerId.equals(n))throw new Nr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=ga(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected")),t.onProgress?.(new ee("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??lf});if(s.status!=="open")throw new er("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Ot("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new ee("connection:opened",s)),s}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 o=>{try{await Promise.all([lt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(ve(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(ve(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.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(ve(e.remoteAddr)){let o=W(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.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=>X(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var qw=1e4,$w="1.0.0",zw="ping",Vw="ipfs",pm=32,Hw=!0,La=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Vw}/${zw}/${$w}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??qw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Hw,this.timeout=new ri({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Bn]=["@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});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=bu(o);t=Date.now(),await Promise.all([s.write(tn(pm),{signal:n}),s.read({bytes:pm,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(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 Pa=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],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(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 Tn("No content routers available");let n=this,o=new mr;for await(let s of Sn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Tn("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 Tn("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 wt;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new wt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Da=globalThis.CustomEvent??Event;async function*mf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=be(),a=be(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(s.length===t&&(i=be(),await i.promise),u)break;let g={done:!1};s.push(g),m().then(p=>{g.done=!0,g.ok=!0,g.value=p,o.dispatchEvent(new Da("task-complete"))},p=>{g.done=!0,g.err=p,o.dispatchEvent(new Da("task-complete"))})}c=!0,o.dispatchEvent(new Da("task-complete"))}catch(m){l=m,o.dispatchEvent(new Da("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(m=>m.done)}function*d(){for(;s.length>0&&s[0].done;){let m=s[0];if(s.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*h(){for(;f();)for(let m=0;m<s.length;m++)if(s[m].done){let g=s[m];if(s.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=be(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var ka=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],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:B(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Vo("No peer routers available");if(e.toString()===this.peerId.toString())throw new sa("Should not try to find self");let n=this,o=Sn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new tr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Vo("No peer routers available");let n=this,o=Io(1024);for await(let s of mf((async function*(){let i=Sn(...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}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Ra=class extends Pe{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=yt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=be(),yield(await lt(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=yt([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 o=tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ze(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var gf=32,yf=64,Oa=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,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ce({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 ia(`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 aa(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:gf,maxOutboundStreams:yf,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new P("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}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 o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);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(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);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(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Na=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=Ce({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ce({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Mn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new P("Transport must have a valid tag");if(this.transports.has(t))throw new P(`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 o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ha(`No transport available for address ${String(e)}`);return t?.onProgress?.(new ee("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 wt("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(s=>{t.errors.set(s.toString(),new ca)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Ku.matches(c)?t.ipv4.attempts++:qu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Ku.matches(c)&&t.ipv4.success++,qu.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Mn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new la(`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:
|
|
13
13
|
${[...t.errors.entries()].map(([s,i])=>`
|
|
14
|
-
${s}: ${`${
|
|
14
|
+
${s}: ${`${Ww(i)}`.split(`
|
|
15
15
|
`).join(`
|
|
16
16
|
`)}
|
|
17
|
-
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function
|
|
18
|
-
`);async function Yo(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==
|
|
17
|
+
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function Ww(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var bt="/multistream/1.0.0";var Gw=D(`
|
|
18
|
+
`);async function Yo(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Gw[0])throw new rs("Missing newline");return B(n).trimEnd()}async function Dn(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=di(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',bt,i);let c=D(`${bt}
|
|
19
19
|
`),l=D(`${i}
|
|
20
20
|
`);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await Yo(o,t),n.trace('read "%s"',a),a!==bt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(D(`${i}
|
|
21
21
|
`),t);if(n.trace("reading protocol response"),a=await Yo(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new ts(`Protocol selection failed - could not negotiate ${e}`)}async function kn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=di(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Yo(o,t);if(n.trace('read "%s"',s),s===bt){n.trace('respond with "%s" for "%s"',bt,s),await o.write(D(`${bt}
|
|
@@ -23,7 +23,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
|
|
|
23
23
|
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new J(...e.map(a=>bi.single(D(`${a}
|
|
24
24
|
`))),D(`
|
|
25
25
|
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(D(`na
|
|
26
|
-
`),t),n('responded with "na" for "%s"',s)}}var bf=class extends Pe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=ju(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new is(n.local,n.error))})}[Symbol.toStringTag]="Connection";[vf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Jt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new er(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new er(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Fn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new ee("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Dn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Yw(n.protocol,this.components.registrar,t),s=ym(n.protocol,"outbound",this);if(s>o){let c=new ss(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new ee("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await kn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=jw(t.protocol,this.components.registrar);if(ym(t.protocol,"inbound",this)>o)throw new os(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Fn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function bm(r,e){return new bf(r,e)}function jw(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return mf}function Yw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??gf}function ym(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Fa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ce({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ce({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=yt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new da("Connection denied");await ze(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=mt(n),await ze(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(Zw(n)){if(n.remotePeer==null)throw new Ot(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=mt(f)),n?.onProgress?.(new ee(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new Nr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new ee(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=bm(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await kn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Dr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Dr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Dn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Dr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Dr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Dn(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Jt(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await kn(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Zw(r){return r.skipEncryption===!0}var Ma="3.2.2",Ba="js-libp2p";function xm(r,e){return`${r??Ba}/${e??Ma} browser/${globalThis.navigator.userAgent}`}var Zo=class extends Pe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Pe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??zs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Ba,s=e.nodeInfo?.version??Ma,i=this.components=Zp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??xm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:Qp(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Np(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Fa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Na(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ta(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new La(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Oa(this.components)),this.configureComponent("addressManager",new ra(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ka(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Pa(this.components,{routers:c})),this.configureComponent("randomWalk",new Ra(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ka]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ka])),f[$a]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[$a])),f[qa]!=null&&(this.log("registering service %s for peer discovery",l),f[qa].addEventListener?.("peer",d=>{this.#e(d)}))}Xp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new mr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new P("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new P("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Qt(e)&&(e=mt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Qe([D("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=nn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Xw(r={}){r.privateKey??=await Ch("Ed25519");let e=new Zo({...await kh(r),peerId:Dh(r.privateKey)});return r.start!==!1&&await e.start(),e}var Qw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Jw(r){return r==null?!1:r instanceof Zo?!0:Qw.every(e=>typeof r[e]=="function")}return Im(ex);})();
|
|
26
|
+
`),t),n('responded with "na" for "%s"',s)}}var wf=class extends Pe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Yu(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new is(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Sf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Jt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new er(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new er(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Fn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new ee("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Dn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Zw(n.protocol,this.components.registrar,t),s=bm(n.protocol,"outbound",this);if(s>o){let c=new ss(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new ee("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await kn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Yw(t.protocol,this.components.registrar);if(bm(t.protocol,"inbound",this)>o)throw new os(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Fn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function wm(r,e){return new wf(r,e)}function Yw(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return gf}function Zw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??yf}function bm(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Fa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ce({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ce({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=yt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new da("Connection denied");await ze(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=mt(n),await ze(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(Xw(n)){if(n.remotePeer==null)throw new Ot(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=mt(f)),n?.onProgress?.(new ee(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new Nr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new ee(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=wm(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await kn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Dr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Dr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Dn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Dr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Dr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Dn(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Jt(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await kn(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Xw(r){return r.skipEncryption===!0}var Ma="3.2.3-10b2bdf50",Ba="js-libp2p";function Em(r,e){return`${r??Ba}/${e??Ma} browser/${globalThis.navigator.userAgent}`}var Zo=class extends Pe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Pe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??zs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Ba,s=e.nodeInfo?.version??Ma,i=this.components=Xp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Em(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:Jp(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Fp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Fa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Na(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ta(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new La(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Oa(this.components)),this.configureComponent("addressManager",new ra(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ka(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Pa(this.components,{routers:c})),this.configureComponent("randomWalk",new Ra(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ka]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ka])),f[$a]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[$a])),f[qa]!=null&&(this.log("registering service %s for peer discovery",l),f[qa].addEventListener?.("peer",d=>{this.#e(d)}))}Qp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new mr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new P("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new P("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Qt(e)&&(e=mt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Qe([D("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=nn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Qw(r={}){r.privateKey??=await Th("Ed25519");let e=new Zo({...await Rh(r),peerId:kh(r.privateKey)});return r.start!==!1&&await e.start(),e}var Jw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function ex(r){return r==null?!1:r instanceof Zo?!0:Jw.every(e=>typeof r[e]=="function")}return Cm(tx);})();
|
|
27
27
|
/*! Bundled license information:
|
|
28
28
|
|
|
29
29
|
@noble/curves/utils.js:
|