libp2p 3.1.3 → 3.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,29 +1,29 @@
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 Np=Object.create;var Po=Object.defineProperty;var Mp=Object.getOwnPropertyDescriptor;var Bp=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,Up=Object.prototype.hasOwnProperty;var aa=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Me=(r,e)=>{for(var t in e)Po(r,t,{get:e[t],enumerable:!0})},Nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Bp(e))!Up.call(r,o)&&o!==t&&Po(r,o,{get:()=>e[o],enumerable:!(n=Mp(e,o))||n.enumerable});return r};var ca=(r,e,t)=>(t=r!=null?Np(Fp(r)):{},Nu(e||!r||!r.__esModule?Po(t,"default",{value:r,enumerable:!0}):t,r)),Kp=r=>Nu(Po({},"__esModule",{value:!0}),r);var ch=aa(io=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,f,u,d;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,d=c&255,[l,f,u,d].join(".")},i=function(c){var l,f,u,d,h,p;for(l=[],u=d=0;d<=3&&c.length!==0;u=++d){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,f,u,d,h;for(d=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)d=d*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")d=d*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")d=d*l+(10+t(c[u])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[d,u]},r=(function(){function c(l,f){var u,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(E){throw u=E,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(E){throw u=E,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,u,d;for(d=i(this.first),u=i(this.last),f=0;d<=u;)l(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),io.ip2long=i,io.long2ip=a,io.Netmask=r}).call(io)});var yp=aa((BT,uu)=>{"use strict";var Lb=Object.prototype.hasOwnProperty,Ne="~";function So(){}Object.create&&(So.prototype=Object.create(null),new So().__proto__||(Ne=!1));function Pb(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function gp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Pb(t,n||r,o),i=Ne?Ne+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 Vi(r,e){--r._eventsCount===0?r._events=new So:delete r._events[e]}function Te(){this._events=new So,this._eventsCount=0}Te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Lb.call(t,n)&&e.push(Ne?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Te.prototype.listeners=function(e){var t=Ne?Ne+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};Te.prototype.listenerCount=function(e){var t=Ne?Ne+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Te.prototype.emit=function(e,t,n,o,s,i){var a=Ne?Ne+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,u;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(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var d=c.length,h;for(u=0;u<d;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};Te.prototype.on=function(e,t,n){return gp(this,e,t,n,!1)};Te.prototype.once=function(e,t,n){return gp(this,e,t,n,!0)};Te.prototype.removeListener=function(e,t,n,o){var s=Ne?Ne+e:e;if(!this._events[s])return this;if(!t)return Vi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Vi(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:Vi(this,s)}return this};Te.prototype.removeAllListeners=function(e){var t;return e?(t=Ne?Ne+e:e,this._events[t]&&Vi(this,t)):(this._events=new So,this._eventsCount=0),this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.addListener=Te.prototype.on;Te.prefixed=Ne;Te.EventEmitter=Te;typeof uu<"u"&&(uu.exports=Te)});var Ep=aa((i4,xp)=>{xp.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 tw={};Me(tw,{createLibp2p:()=>Qb,dnsaddrResolver:()=>Ar,isLibp2p:()=>ew});var Mu=Symbol.for("@libp2p/connection");var la=Symbol.for("@libp2p/content-routing");var Ge=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var C=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_r=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},yn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var zt=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Ht=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ir=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ct=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Do=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ro=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ko=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Oo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var No=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ut=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Cr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var bn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Mo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Bo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Tt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Fo=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var ua=Symbol.for("@libp2p/peer-discovery");var Uo=Symbol.for("@libp2p/peer-id");function Lt(r){return!!r?.[Uo]}var fa=Symbol.for("@libp2p/peer-routing");var da="keep-alive";function Ko(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Bu(...r){let e=[];for(let t of r)Ko(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 Fu(...r){let e=[];for(let t of r)Ko(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 dw=Symbol.for("@libp2p/transport");var wn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(wn||(wn={}));var Le=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){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xn=Symbol.for("@libp2p/service-capabilities"),ha=Symbol.for("@libp2p/service-dependencies");var ba={};Me(ba,{base58btc:()=>J,base58flickr:()=>Gp});var Kw=new Uint8Array(0);function Uu(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 ft(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 Ku(r){return new TextEncoder().encode(r)}function qu(r){return new TextDecoder().decode(r)}function qp(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),f=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var E=0,m=0,g=0,A=p.length;g!==A&&p[g]===0;)g++,E++;for(var x=(A-g)*f+1>>>0,I=new Uint8Array(x);g!==A;){for(var O=p[g],$=0,q=x-1;(O!==0||$<m)&&q!==-1;q--,$++)O+=256*I[q]>>>0,I[q]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=$,g++}for(var S=x-m;S!==x&&I[S]===0;)S++;for(var v=c.repeat(E);S<x;++S)v+=r.charAt(I[S]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var E=0;if(p[E]!==" "){for(var m=0,g=0;p[E]===c;)m++,E++;for(var A=(p.length-E)*l+1>>>0,x=new Uint8Array(A);p[E];){var I=t[p.charCodeAt(E)];if(I===255)return;for(var O=0,$=A-1;(I!==0||O<g)&&$!==-1;$--,O++)I+=a*x[$]>>>0,x[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=O,E++}if(p[E]!==" "){for(var q=A-g;q!==A&&x[q]===0;)q++;for(var S=new Uint8Array(m+(A-q)),v=m;q!==A;)S[v++]=x[q++];return S}}}function h(p){var E=d(p);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:h}}var $p=qp,Vp=$p,Vu=Vp;var pa=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")}},ma=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 zu(this,e)}},ga=class{decoders;constructor(e){this.decoders=e}or(e){return zu(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 zu(r,e){return new ga({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ya=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 pa(e,t,n),this.decoder=new ma(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Tr({name:r,prefix:e,encode:t,decode:n}){return new ya(r,e,t,n)}function Pt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Vu(t,r);return Tr({prefix:e,name:r,encode:n,decode:s=>ft(o(s))})}function zp(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 f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,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 Hp(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 Wp(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Wp(n);return Tr({prefix:e,name:r,encode(s){return Hp(s,n,t)},decode(s){return zp(s,o,t,r)}})}var J=Pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gp=Pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wa={};Me(wa,{base32:()=>ze,base32hex:()=>jp,base32hexpad:()=>Jp,base32hexpadupper:()=>em,base32hexupper:()=>Qp,base32pad:()=>Xp,base32padupper:()=>Zp,base32upper:()=>Yp,base32z:()=>tm});var ze=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yp=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xp=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zp=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jp=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qp=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jp=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),em=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tm=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xa={};Me(xa,{base36:()=>En,base36upper:()=>rm});var En=Pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rm=Pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nm=Gu,Hu=128,om=127,sm=~om,im=Math.pow(2,31);function Gu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=im;)e[t++]=r&255|Hu,r/=128;for(;r&sm;)e[t++]=r&255|Hu,r>>>=7;return e[t]=r|0,Gu.bytes=t-n+1,e}var am=Ea,cm=128,Wu=127;function Ea(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ea.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Wu)<<o:(i&Wu)*Math.pow(2,o),o+=7}while(i>=cm);return Ea.bytes=s-n,t}var lm=Math.pow(2,7),um=Math.pow(2,14),fm=Math.pow(2,21),dm=Math.pow(2,28),hm=Math.pow(2,35),pm=Math.pow(2,42),mm=Math.pow(2,49),gm=Math.pow(2,56),ym=Math.pow(2,63),bm=function(r){return r<lm?1:r<um?2:r<fm?3:r<dm?4:r<hm?5:r<pm?6:r<mm?7:r<gm?8:r<ym?9:10},wm={encode:nm,decode:am,encodingLength:bm},xm=wm,vn=xm;function Sn(r,e=0){return[vn.decode(r,e),vn.decode.bytes]}function Lr(r,e,t=0){return vn.encode(r,e,t),e}function Pr(r){return vn.encodingLength(r)}function ot(r,e){let t=e.byteLength,n=Pr(r),o=n+Pr(t),s=new Uint8Array(o+t);return Lr(r,s,0),Lr(t,s,n),s.set(e,o),new Dr(r,t,e,s)}function dt(r){let e=ft(r),[t,n]=Sn(e),[o,s]=Sn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Dr(t,o,i,e)}function Yu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Uu(r.bytes,t.bytes)}}var Dr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Xu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return vm(t,va(r),e??J.encoder);default:return Sm(t,va(r),e??ze.encoder)}}var Zu=new WeakMap;function va(r){let e=Zu.get(r);if(e==null){let t=new Map;return Zu.set(r,t),t}return e}var le=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!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Am)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=ot(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&&Yu(e.multihash,n.multihash)}toString(e){return Xu(this,e)}toJSON(){return{"/":Xu(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??ju(n,o,s.bytes))}else if(t[_m]===!0){let{version:n,multihash:o,code:s}=t,i=dt(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!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ju(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,An,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=ft(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 Dr(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[u,d]=Sn(e.subarray(t));return t+=d,u},o=n(),s=An;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,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Em(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 va(s).set(n,e),s}};function Em(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.prefix,t.decode(r)]}case En.prefix:{let t=e??En;return[En.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 vm(r,e,t){let{prefix:n}=t;if(n!==J.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 Sm(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 An=112,Am=18;function ju(r,e,t){let n=Pr(r),o=n+Pr(e),s=new Uint8Array(o+t.byteLength);return Lr(r,s,0),Lr(e,s,n),s.set(t,o),s}var _m=Symbol.for("@ipld/js-cid/CID");var Sa={};Me(Sa,{identity:()=>Ye});var Qu=0,Im="identity",Ju=ft;function Cm(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 ot(Qu,Ju(r))}var Ye={code:Qu,name:Im,encode:Ju,digest:Cm};function j(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 ce(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function Xe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var tf=Symbol.for("@achingbrain/uint8arraylist");function ef(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 $o(r){return!!r?.[tf]}var Q=class r{bufs;length;[tf]=!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($o(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if($o(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=ef(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ef(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($o(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 Xe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Xe(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,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!$o(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 u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}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=Se(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=ce(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=ce(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=ce(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=Se(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=ce(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=ce(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=ce(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=ce(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=ce(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(!j(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 Aa={};Me(Aa,{base10:()=>Tm});var Tm=Pt({prefix:"9",name:"base10",alphabet:"0123456789"});var _a={};Me(_a,{base16:()=>Lm,base16upper:()=>Pm});var Lm=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Pm=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ia={};Me(Ia,{base2:()=>Dm});var Dm=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ca={};Me(Ca,{base256emoji:()=>Mm});var rf=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}"),Rm=rf.reduce((r,e,t)=>(r[t]=e,r),[]),km=rf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Om(r){return r.reduce((e,t)=>(e+=Rm[t],e),"")}function Nm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=km[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Mm=Tr({prefix:"\u{1F680}",name:"base256emoji",encode:Om,decode:Nm});var Pa={};Me(Pa,{base64:()=>Ta,base64pad:()=>Bm,base64url:()=>La,base64urlpad:()=>Fm});var Ta=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Bm=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),La=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fm=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Da={};Me(Da,{base8:()=>Um});var Um=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ra={};Me(Ra,{identity:()=>Km});var Km=Tr({prefix:"\0",name:"identity",encode:r=>qu(r),decode:r=>Ku(r)});var Sx=new TextEncoder,Ax=new TextDecoder;var Na={};Me(Na,{sha256:()=>Rr,sha512:()=>zm});var Vm=20;function Oa({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ka(r,e,t,n,o)}var ka=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Vm,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?nf(n,this.code,t?.truncate):n.then(o=>nf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function nf(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 ot(e,r)}function sf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Rr=Oa({name:"sha2-256",code:18,encode:sf("SHA-256")}),zm=Oa({name:"sha2-512",code:19,encode:sf("SHA-512")});var _n={...Ra,...Ia,...Da,...Aa,..._a,...wa,...xa,...ba,...Pa,...Ca},Mx={...Na,...Sa};function cf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var af=cf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ma=cf("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=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hm={utf8:af,"utf-8":af,hex:_n.base16,latin1:Ma,ascii:Ma,binary:Ma,..._n},Vo=Hm;function L(r,e="utf8"){let t=Vo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function U(r,e="utf8"){let t=Vo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Wm=parseInt("11111",2),Ba=parseInt("10000000",2),Gm=parseInt("01111111",2),lf={0:In,1:In,2:Ym,3:jm,4:Qm,5:Zm,6:Xm,16:In,22:In,48:In};function ht(r,e={offset:0}){let t=r[e.offset]&Wm;if(e.offset++,lf[t]!=null)return lf[t](r,e);throw new Error("No decoder for tag "+t)}function Cn(r,e){let t=0;if((r[e.offset]&Ba)===Ba){let n=r[e.offset]&Gm,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 In(r,e){Cn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ht(r,e);if(n===null)break;t.push(n)}return t}function Ym(r,e){let t=Cn(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 Xm(r,e){let t=Cn(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 f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function Zm(r,e){return e.offset++,null}function jm(r,e){let t=Cn(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 Qm(r,e){let t=Cn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Jm(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Q;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function zo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Jm(r.byteLength);return new Q(Uint8Array.from([e.byteLength|Ba]),e)}function Pe(r){let e=new Q,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Q(Uint8Array.from([2]),zo(e),e)}function Tn(r){let e=Uint8Array.from([0]),t=new Q(e,r);return new Q(Uint8Array.from([3]),zo(t),t)}function uf(r){return new Q(Uint8Array.from([4]),zo(r),r)}function Ze(r,e=48){let t=new Q;for(let n of r)t.append(n);return new Q(Uint8Array.from([e]),zo(t),t)}async function ff(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 df(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 hf(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}var eg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),tg=Uint8Array.from([6,5,43,129,4,0,34]),rg=Uint8Array.from([6,5,43,129,4,0,35]),ng={ext:!0,kty:"EC",crv:"P-256"},og={ext:!0,kty:"EC",crv:"P-384"},sg={ext:!0,kty:"EC",crv:"P-521"},Fa=32,Ua=48,Ka=66;function qa(r){let e=ht(r);return pf(e)}function pf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Fa*2+1)return n=U(e.subarray(t,t+Fa),"base64url"),o=U(e.subarray(t+Fa),"base64url"),new Wt({...ng,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ua*2+1)return n=U(e.subarray(t,t+Ua),"base64url"),o=U(e.subarray(t+Ua),"base64url"),new Wt({...og,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ka*2+1)return n=U(e.subarray(t,t+Ka),"base64url"),o=U(e.subarray(t+Ka),"base64url"),new Wt({...sg,key_ops:["verify"],x:n,y:o});throw new C(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function mf(r){return Ze([Pe(Uint8Array.from([1])),uf(L(r.d??"","base64url")),Ze([yf(r.crv)],160),Ze([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function gf(r){return Ze([Pe(Uint8Array.from([1])),Ze([yf(r.crv)],160),Ze([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function yf(r){if(r==="P-256")return eg;if(r==="P-384")return tg;if(r==="P-521")return rg;throw new C(`Invalid curve ${r}`)}async function bf(r="P-256"){let e=await ff(r);return new Ho(e.privateKey)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=gf(this.jwk)),this._raw}toMultihash(){return Ye.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}async verify(e,t,n){return hf(this.jwk,t,e,n)}},Ho=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Wt({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=mf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}async sign(e,t){return df(this.jwk,e,t)}};function Gt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function st(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function V(r,e,t=""){let n=Gt(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}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Wo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");st(r.outputLen),st(r.blockLen)}function kr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function xf(r,e){V(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function mt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Go(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function je(r,e){return r<<32-e|r>>>e}var Ef=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ig=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gt(r){if(V(r),Ef)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=ig[r[t]];return e}var pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function wf(r){if(r>=pt._0&&r<=pt._9)return r-pt._0;if(r>=pt.A&&r<=pt.F)return r-(pt.A-10);if(r>=pt.a&&r<=pt.f)return r-(pt.a-10)}function yt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ef)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("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=wf(r.charCodeAt(s)),a=wf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Be(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];V(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 $a(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.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Rt(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var Va=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function vf(r,e,t){return r&e^~r&t}function Sf(r,e,t){return r&e^r&t^e&t}var Ln=class{blockLen;outputLen;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=Go(this.buffer)}update(e){kr(this),V(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=Go(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kr(this),xf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,mt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Go(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],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()}},bt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yo=BigInt(4294967295),Af=BigInt(32);function ag(r,e=!1){return e?{h:Number(r&Yo),l:Number(r>>Af&Yo)}:{h:Number(r>>Af&Yo)|0,l:Number(r&Yo)|0}}function _f(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}=ag(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var za=(r,e,t)=>r>>>t,Ha=(r,e,t)=>r<<32-t|e>>>t,Yt=(r,e,t)=>r>>>t|e<<32-t,Xt=(r,e,t)=>r<<32-t|e>>>t,Pn=(r,e,t)=>r<<64-t|e>>>t-32,Dn=(r,e,t)=>r>>>t-32|e<<64-t;function it(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var If=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Cf=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Tf=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Lf=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Pf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Df=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var lg=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),Wa=class extends Ln{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 u=0;u<16;u++,t+=4)kt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=kt[u-15],h=kt[u-2],p=je(d,7)^je(d,18)^d>>>3,E=je(h,17)^je(h,19)^h>>>10;kt[u]=E+kt[u-7]+p+kt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=je(a,6)^je(a,11)^je(a,25),h=f+d+vf(a,c,l)+lg[u]+kt[u]|0,E=(je(n,2)^je(n,13)^je(n,22))+Sf(n,o,s)|0;f=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|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,f=f+this.H|0,this.set(n,o,s,i,a,c,l,f)}roundClean(){mt(kt)}destroy(){this.set(0,0,0,0,0,0,0,0),mt(this.buffer)}},Ga=class extends Wa{A=bt[0]|0;B=bt[1]|0;C=bt[2]|0;D=bt[3]|0;E=bt[4]|0;F=bt[5]|0;G=bt[6]|0;H=bt[7]|0;constructor(){super(32)}};var Rf=_f(["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))),ug=Rf[0],fg=Rf[1],Ot=new Uint32Array(80),Nt=new Uint32Array(80),Ya=class extends Ln{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:f,Fh:u,Fl:d,Gh:h,Gl:p,Hh:E,Hl:m}=this;return[e,t,n,o,s,i,a,c,l,f,u,d,h,p,E,m]}set(e,t,n,o,s,i,a,c,l,f,u,d,h,p,E,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=E|0,this.Hl=m|0}process(e,t){for(let x=0;x<16;x++,t+=4)Ot[x]=e.getUint32(t),Nt[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let I=Ot[x-15]|0,O=Nt[x-15]|0,$=Yt(I,O,1)^Yt(I,O,8)^za(I,O,7),q=Xt(I,O,1)^Xt(I,O,8)^Ha(I,O,7),S=Ot[x-2]|0,v=Nt[x-2]|0,B=Yt(S,v,19)^Pn(S,v,61)^za(S,v,6),z=Xt(S,v,19)^Dn(S,v,61)^Ha(S,v,6),R=Tf(q,z,Nt[x-7],Nt[x-16]),b=Lf(R,$,B,Ot[x-7],Ot[x-16]);Ot[x]=b|0,Nt[x]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:p,Gh:E,Gl:m,Hh:g,Hl:A}=this;for(let x=0;x<80;x++){let I=Yt(u,d,14)^Yt(u,d,18)^Pn(u,d,41),O=Xt(u,d,14)^Xt(u,d,18)^Dn(u,d,41),$=u&h^~u&E,q=d&p^~d&m,S=Pf(A,O,q,fg[x],Nt[x]),v=Df(S,g,I,$,ug[x],Ot[x]),B=S|0,z=Yt(n,o,28)^Pn(n,o,34)^Pn(n,o,39),R=Xt(n,o,28)^Dn(n,o,34)^Dn(n,o,39),b=n&s^n&a^s&a,w=o&i^o&c^i&c;g=E|0,A=m|0,E=h|0,m=p|0,h=u|0,p=d|0,{h:u,l:d}=it(l|0,f|0,v|0,B|0),l=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=If(B,R,w);n=Cf(y,v,z,b),o=y|0}({h:n,l:o}=it(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=it(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=it(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=it(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=it(this.Eh|0,this.El|0,u|0,d|0),{h,l:p}=it(this.Fh|0,this.Fl|0,h|0,p|0),{h:E,l:m}=it(this.Gh|0,this.Gl|0,E|0,m|0),{h:g,l:A}=it(this.Hh|0,this.Hl|0,g|0,A|0),this.set(n,o,s,i,a,c,l,f,u,d,h,p,E,m,g,A)}roundClean(){mt(Ot,Nt)}destroy(){mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xa=class extends Ya{Ah=we[0]|0;Al=we[1]|0;Bh=we[2]|0;Bl=we[3]|0;Ch=we[4]|0;Cl=we[5]|0;Dh=we[6]|0;Dl=we[7]|0;Eh=we[8]|0;El=we[9]|0;Fh=we[10]|0;Fl=we[11]|0;Gh=we[12]|0;Gl=we[13]|0;Hh=we[14]|0;Hl=we[15]|0;constructor(){super(64)}};var Or=$a(()=>new Ga,Va(1));var kf=$a(()=>new Xa,Va(3));var ja=BigInt(0),Za=BigInt(1);function wt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Of(r){if(typeof r=="bigint"){if(!Xo(r))throw new Error("positive bigint expected, got "+r)}else st(r);return r}function Rn(r){let e=Of(r).toString(16);return e.length&1?"0"+e:e}function Nf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ja:BigInt("0x"+r)}function Nr(r){return Nf(gt(r))}function Zt(r){return Nf(gt(jo(V(r)).reverse()))}function Zo(r,e){st(e),r=Of(r);let t=yt(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Qa(r,e){return Zo(r,e).reverse()}function jo(r){return Uint8Array.from(r)}var Xo=r=>typeof r=="bigint"&&ja<=r;function dg(r,e,t){return Xo(r)&&Xo(e)&&Xo(t)&&e<=r&&r<t}function kn(r,e,t,n){if(!dg(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Ja(r){let e;for(e=0;r>ja;r>>=Za,e+=1);return e}var On=r=>(Za<<BigInt(r))-Za;function Mf(r,e,t){if(st(r,"hashLen"),st(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),f=0,u=()=>{c.fill(1),l.fill(0),f=0},d=(...m)=>t(l,Be(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let A=c.slice();g.push(A),m+=c.length}return Be(...g)};return(m,g)=>{u(),h(m);let A;for(;!(A=g(p()));)h();return u(),A}}function Mt(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`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)}function Mr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var De=BigInt(0),he=BigInt(1),jt=BigInt(2),Uf=BigInt(3),Kf=BigInt(4),qf=BigInt(5),hg=BigInt(7),$f=BigInt(8),pg=BigInt(9),Vf=BigInt(16);function ue(r,e){let t=r%e;return t>=De?t:e+t}function ne(r,e,t){let n=r;for(;e-- >De;)n*=n,n%=t;return n}function Bf(r,e){if(r===De)throw new Error("invert: expected non-zero number");if(e<=De)throw new Error("invert: expected positive modulus, got "+e);let t=ue(r,e),n=e,o=De,s=he,i=he,a=De;for(;t!==De;){let l=n/t,f=n%t,u=o-i*l,d=s-a*l;n=t,t=f,o=i,s=a,i=u,a=d}if(n!==he)throw new Error("invert: does not exist");return ue(o,e)}function tc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function zf(r,e){let t=(r.ORDER+he)/Kf,n=r.pow(e,t);return tc(r,n,e),n}function mg(r,e){let t=(r.ORDER-qf)/$f,n=r.mul(e,jt),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,jt),o),a=r.mul(s,r.sub(i,r.ONE));return tc(r,a,e),a}function gg(r){let e=Br(r),t=Hf(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+hg)/Vf;return(a,c)=>{let l=a.pow(c,i),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(f),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,p);let E=a.eql(a.sqr(f),c),m=a.cmov(l,f,E);return tc(a,m,c),m}}function Hf(r){if(r<Uf)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%jt===De;)e/=jt,t++;let n=jt,o=Br(r);for(;Ff(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return zf;let s=o.pow(n,e),i=(e+he)/jt;return function(c,l){if(c.is0(l))return l;if(Ff(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,E=c.sqr(d);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===f)throw new Error("Cannot find square root");let m=he<<BigInt(f-p-1),g=c.pow(u,m);f=p,u=c.sqr(g),d=c.mul(d,u),h=c.mul(h,g)}return h}}function yg(r){return r%Kf===Uf?zf:r%$f===qf?mg:r%Vf===pg?gg(r):Hf(r)}var Wf=(r,e)=>(ue(r,e)&he)===he,bg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=bg.reduce((n,o)=>(n[o]="function",n),e);return Mt(r,t),r}function wg(r,e,t){if(t<De)throw new Error("invalid exponent, negatives unsupported");if(t===De)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>De;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Nn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Ff(r,e){let t=(r.ORDER-he)/jt,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function xg(r,e){e!==void 0&&st(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var ec=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=he;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=De)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=xg(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return De<=e&&e<this.ORDER}is0(e){return e===De}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return wg(this,e,t)}div(e,t){return ue(e*Bf(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 Bf(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=yg(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Qa(e,this.BYTES):Zo(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!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?Zt(e):Nr(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e)}cmov(e,t,n){return n?t:e}};function Br(r,e={}){return new ec(r,e)}function Gf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function nc(r){let e=Gf(r);return e+Math.ceil(e/2)}function oc(r,e,t=!1){V(r);let n=r.length,o=Gf(e),s=nc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Zt(r):Nr(r),a=ue(i,e-he)+he;return t?Qa(a,o):Zo(a,o)}var Fr=BigInt(0),Qt=BigInt(1);function Mn(r,e){let t=e.negate();return r?t:e}function Jt(r,e){let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function jf(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function sc(r,e){jf(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=On(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Yf(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+=Qt);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}var ic=new WeakMap,Qf=new WeakMap;function ac(r){return Qf.get(r)||1}function Xf(r){if(r!==Fr)throw new Error("invalid wNAF")}var Ur=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>Fr;)t&Qt&&(n=n.add(o)),o=o.double(),t>>=Qt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=sc(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=sc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=Yf(n,a,i);n=c,f?s=s.add(Mn(d,t[h])):o=o.add(Mn(u,t[l]))}return Xf(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=sc(e,this.bits);for(let i=0;i<s.windows&&n!==Fr;i++){let{nextN:a,offset:c,isZero:l,isNeg:f}=Yf(n,i,s);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return Xf(n),o}getPrecomputes(e,t,n){let o=ic.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),ic.set(t,o))),o}cached(e,t,n){let o=ac(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ac(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){jf(t,this.bits),Qf.set(e,t),ic.delete(e)}hasCache(e){return ac(e)!==1}};function Jf(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Fr||n>Fr;)t&Qt&&(s=s.add(o)),n&Qt&&(i=i.add(o)),o=o.double(),t>>=Qt,n>>=Qt;return{p1:s,p2:i}}function Zf(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return rc(e),e}else return Br(r,{isLE:t})}function Qo(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>Fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Zf(e.p,t.Fp,n),s=Zf(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 Jo(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Bt=BigInt(0),pe=BigInt(1),cc=BigInt(2),Eg=BigInt(8);function vg(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 ed(r,e={}){let t=Qo("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Mt(e,{},{uvRatio:"function"});let a=cc<<BigInt(o.BYTES*8)-pe,c=m=>n.create(m),l=e.uvRatio||((m,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(m,g))}}catch{return{isValid:!1,value:Bt}}});if(!vg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(m,g,A=!1){let x=A?pe:Bt;return kn("coordinate "+m,g,x,a),g}function u(m){if(!(m instanceof p))throw new Error("EdwardsPoint expected")}let d=Mr((m,g)=>{let{X:A,Y:x,Z:I}=m,O=m.is0();g==null&&(g=O?Eg:n.inv(I));let $=c(A*g),q=c(x*g),S=n.mul(I,g);if(O)return{x:Bt,y:pe};if(S!==pe)throw new Error("invZ was invalid");return{x:$,y:q}}),h=Mr(m=>{let{a:g,d:A}=s;if(m.is0())throw new Error("bad point: ZERO");let{X:x,Y:I,Z:O,T:$}=m,q=c(x*x),S=c(I*I),v=c(O*O),B=c(v*v),z=c(q*g),R=c(v*c(z+S)),b=c(B+c(A*c(q*S)));if(R!==b)throw new Error("bad point: equation left != right (1)");let w=c(x*I),y=c(O*$);if(w!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy));static ZERO=new p(Bt,pe,pe,Bt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,A,x,I){this.X=f("x",g),this.Y=f("y",A),this.Z=f("z",x,!0),this.T=f("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:A,y:x}=g||{};return f("x",A),f("y",x),new p(A,x,pe,c(A*x))}static fromBytes(g,A=!1){let x=n.BYTES,{a:I,d:O}=s;g=jo(V(g,x,"point")),wt(A,"zip215");let $=jo(g),q=g[x-1];$[x-1]=q&-129;let S=Zt($),v=A?a:n.ORDER;kn("point.y",S,Bt,v);let B=c(S*S),z=c(B-pe),R=c(O*B-I),{isValid:b,value:w}=l(z,R);if(!b)throw new Error("bad point: invalid y coordinate");let y=(w&pe)===pe,_=(q&128)!==0;if(!A&&w===Bt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==y&&(w=c(-w)),p.fromAffine({x:w,y:S})}static fromHex(g,A=!1){return p.fromBytes(yt(g),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return E.createCache(this,g),A||this.multiply(cc),this}assertValidity(){h(this)}equals(g){u(g);let{X:A,Y:x,Z:I}=this,{X:O,Y:$,Z:q}=g,S=c(A*q),v=c(O*I),B=c(x*q),z=c($*I);return S===v&&B===z}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:A,Y:x,Z:I}=this,O=c(A*A),$=c(x*x),q=c(cc*c(I*I)),S=c(g*O),v=A+x,B=c(c(v*v)-O-$),z=S+$,R=z-q,b=S-$,w=c(B*R),y=c(z*b),_=c(B*b),T=c(R*z);return new p(w,y,T,_)}add(g){u(g);let{a:A,d:x}=s,{X:I,Y:O,Z:$,T:q}=this,{X:S,Y:v,Z:B,T:z}=g,R=c(I*S),b=c(O*v),w=c(q*x*z),y=c($*B),_=c((I+O)*(S+v)-R-b),T=y-w,D=y+w,k=c(b-A*R),P=c(_*T),M=c(D*k),K=c(_*k),oe=c(T*D);return new p(P,M,oe,K)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:x}=E.cached(this,g,I=>Jt(p,I));return Jt(p,[A,x])[0]}multiplyUnsafe(g,A=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Bt?p.ZERO:this.is0()||g===pe?this:E.unsafe(this,g,x=>Jt(p,x),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:A}=this.toAffine(),x=n.toBytes(A);return x[x.length-1]|=g&pe?128:0,x}toHex(){return gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new Ur(p,o.BITS);return p.BASE.precompute(8),p}function td(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Mt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Rt,c=t.adjustScalarBytes||(S=>S),l=t.domain||((S,v,B)=>{if(wt(B,"phflag"),v.length||B)throw new Error("Contexts/pre-hash are not supported");return S});function f(S){return i.create(Zt(S))}function u(S){let v=x.secretKey;V(S,x.secretKey,"secretKey");let B=V(e(S),2*v,"hashedSecretKey"),z=c(B.slice(0,v)),R=B.slice(v,2*v),b=f(z);return{head:z,prefix:R,scalar:b}}function d(S){let{head:v,prefix:B,scalar:z}=u(S),R=o.multiply(z),b=R.toBytes();return{head:v,prefix:B,scalar:z,point:R,pointBytes:b}}function h(S){return d(S).pointBytes}function p(S=Uint8Array.of(),...v){let B=Be(...v);return f(e(l(B,V(S,void 0,"context"),!!n)))}function E(S,v,B={}){S=V(S,void 0,"message"),n&&(S=n(S));let{prefix:z,scalar:R,pointBytes:b}=d(v),w=p(B.context,z,S),y=o.multiply(w).toBytes(),_=p(B.context,y,b,S),T=i.create(w+_*R);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=Be(y,i.toBytes(T));return V(D,x.signature,"result")}let m={zip215:!0};function g(S,v,B,z=m){let{context:R,zip215:b}=z,w=x.signature;S=V(S,w,"signature"),v=V(v,void 0,"message"),B=V(B,x.publicKey,"publicKey"),b!==void 0&&wt(b,"zip215"),n&&(v=n(v));let y=w/2,_=S.subarray(0,y),T=Zt(S.subarray(y,w)),D,k,P;try{D=r.fromBytes(B,b),k=r.fromBytes(_,b),P=o.multiplyUnsafe(T)}catch{return!1}if(!b&&D.isSmallOrder())return!1;let M=p(R,k.toBytes(),D.toBytes(),v);return k.add(D.multiplyUnsafe(M)).subtract(P).clearCofactor().is0()}let A=s.BYTES,x={secretKey:A,publicKey:A,signature:2*A,seed:A};function I(S=a(x.seed)){return V(S,x.seed,"seed")}function O(S){return Gt(S)&&S.length===i.BYTES}function $(S,v){try{return!!r.fromBytes(S,v)}catch{return!1}}let q={getExtendedPublicKey:d,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:$,toMontgomery(S){let{y:v}=r.fromBytes(S),B=x.publicKey,z=B===32;if(!z&&B!==57)throw new Error("only defined for 25519 and 448");let R=z?s.div(pe+v,pe-v):s.div(v-pe,v+pe);return s.toBytes(R)},toMontgomerySecret(S){let v=x.secretKey;V(S,v);let B=e(S.subarray(0,v));return c(B).subarray(0,v)}};return Object.freeze({keygen:Jo(I,h),getPublicKey:h,sign:E,verify:g,utils:q,Point:r,lengths:x})}var Sg=BigInt(1),rd=BigInt(2);var Ag=BigInt(5),_g=BigInt(8),lc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ig={p:lc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_g,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=lc,a=r*r%s*r%s,c=ne(a,rd,s)*a%s,l=ne(c,Sg,s)*r%s,f=ne(l,Ag,s)*l%s,u=ne(f,e,s)*f%s,d=ne(u,t,s)*u%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,E=ne(p,o,s)*h%s,m=ne(E,e,s)*f%s;return{pow_p_5_8:ne(m,rd,s)*r%s,b2:a}}function Tg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var nd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Lg(r,e){let t=lc,n=ue(e*e*e,t),o=ue(n*n*e,t),s=Cg(r*o).pow_p_5_8,i=ue(r*n*s,t),a=ue(e*i*i,t),c=i,l=ue(i*nd,t),f=a===r,u=a===ue(-r,t),d=a===ue(-r*nd,t);return f&&(i=c),(u||d)&&(i=l),Wf(i,t)&&(i=ue(-i,t)),{isValid:f||u,value:i}}var Pg=ed(Ig,{uvRatio:Lg});function Dg(r){return td(Pg,kf,Object.assign({adjustScalarBytes:Tg},r))}var Bn=Dg({});var Fn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Un=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},es=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var od={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new es("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 Fe=od;var ts=32,Kn=64,uc=32;var Kr,sd=(async()=>{try{return await Fe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function id(){let r=Bn.utils.randomSecretKey(),e=Bn.getPublicKey(r);return{privateKey:Mg(r,e),publicKey:e}}async function Rg(r,e){let t;r.length===Kn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Fe.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Fe.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function kg(r,e){let t=r.subarray(0,uc);return Bn.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function ad(r,e){return Kr==null&&(Kr=await sd),Kr?Rg(r,e):kg(r,e)}async function Og(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Fe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Fe.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 Ng(r,e,t){return Bn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function cd(r,e,t){return Kr==null&&(Kr=await sd),Kr?Og(r,e,t):Ng(r,e,t)}function Mg(r,e){let t=new Uint8Array(Kn);for(let n=0;n<uc;n++)t[n]=r[n],t[uc+n]=e[n];return t}function qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var qn=class{type="Ed25519";raw;constructor(e){this.raw=ns(e,ts)}toMultihash(){return Ye.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=cd(this.raw,t,e);return qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},rs=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ns(e,Kn),this.publicKey=new qn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=ad(this.raw,e);return qr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function fc(r){return r=ns(r,ts),new qn(r)}async function ud(){let{privateKey:r,publicKey:e}=id();return new rs(r,e)}function ns(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new C(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Bg=Math.pow(2,7),Fg=Math.pow(2,14),Ug=Math.pow(2,21),dc=Math.pow(2,28),hc=Math.pow(2,35),pc=Math.pow(2,42),mc=Math.pow(2,49),Y=128,Ae=127;function me(r){if(r<Bg)return 1;if(r<Fg)return 2;if(r<Ug)return 3;if(r<dc)return 4;if(r<hc)return 5;if(r<pc)return 6;if(r<mc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $r(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Kg(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function gc(r,e){let t=r[e],n=0;if(n+=t&Ae,t<Y||(t=r[e+1],n+=(t&Ae)<<7,t<Y)||(t=r[e+2],n+=(t&Ae)<<14,t<Y)||(t=r[e+3],n+=(t&Ae)<<21,t<Y)||(t=r[e+4],n+=(t&Ae)*dc,t<Y)||(t=r[e+5],n+=(t&Ae)*hc,t<Y)||(t=r[e+6],n+=(t&Ae)*pc,t<Y)||(t=r[e+7],n+=(t&Ae)*mc,t<Y))return n;throw new RangeError("Could not decode varint")}function qg(r,e){let t=r.get(e),n=0;if(n+=t&Ae,t<Y||(t=r.get(e+1),n+=(t&Ae)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ae)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ae)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ae)*dc,t<Y)||(t=r.get(e+5),n+=(t&Ae)*hc,t<Y)||(t=r.get(e+6),n+=(t&Ae)*pc,t<Y)||(t=r.get(e+7),n+=(t&Ae)*mc,t<Y))return n;throw new RangeError("Could not decode varint")}function Ft(r,e,t=0){return e==null&&(e=Se(me(r))),e instanceof Uint8Array?$r(r,e,t):Kg(r,e,t)}function er(r,e=0){return r instanceof Uint8Array?gc(r,e):qg(r,e)}var yc=new Float32Array([-0]),Ut=new Uint8Array(yc.buffer);function fd(r,e,t){yc[0]=r,e[t]=Ut[0],e[t+1]=Ut[1],e[t+2]=Ut[2],e[t+3]=Ut[3]}function dd(r,e){return Ut[0]=r[e],Ut[1]=r[e+1],Ut[2]=r[e+2],Ut[3]=r[e+3],yc[0]}var bc=new Float64Array([-0]),_e=new Uint8Array(bc.buffer);function hd(r,e,t){bc[0]=r,e[t]=_e[0],e[t+1]=_e[1],e[t+2]=_e[2],e[t+3]=_e[3],e[t+4]=_e[4],e[t+5]=_e[5],e[t+6]=_e[6],e[t+7]=_e[7]}function pd(r,e){return _e[0]=r[e],_e[1]=r[e+1],_e[2]=r[e+2],_e[3]=r[e+3],_e[4]=r[e+4],_e[5]=r[e+5],_e[6]=r[e+6],_e[7]=r[e+7],bc[0]}var $g=BigInt(Number.MAX_SAFE_INTEGER),Vg=BigInt(Number.MIN_SAFE_INTEGER),Ke=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return tr;if(e<$g&&e>Vg)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>md&&(o=0n,++n>md&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return tr;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):tr}},tr=new Ke(0,0);tr.toBigInt=function(){return 0n};tr.zzEncode=tr.zzDecode=function(){return this};tr.length=function(){return 1};var md=4294967296n;function gd(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 yd(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 wc(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 Qe(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 xc=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,Qe(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 Qe(this,4);return os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);let e=dd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);let e=pd(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 Qe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return yd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(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 Ke(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Qe(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 Qe(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 Qe(this,8);let e=os(this.buf,this.pos+=4),t=os(this.buf,this.pos+=4);return new Ke(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=gc(this.buf,this.pos);return this.pos+=me(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ec(r){return new xc(r instanceof Uint8Array?r:r.subarray())}function Re(r,e,t){let n=Ec(r);return e.decode(n,void 0,t)}function vc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var rr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Sc(){}var _c=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},zg=vc();function Hg(r){return globalThis.Buffer!=null?Se(r):zg(r)}var zn=class{len;head;tail;states;constructor(){this.len=0,this.head=new rr(Sc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new rr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ic((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(ss,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ke.fromBigInt(e);return this._push(ss,t.length(),t)}uint64Number(e){return this._push($r,me(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ke.fromBigInt(e).zzEncode();return this._push(ss,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push(ss,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ac,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,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(fd,4,e)}double(e){return this._push(hd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ac,1,0):this.uint32(t)._push(Gg,t,e)}string(e){let t=gd(e);return t!==0?this.uint32(t)._push(wc,t,e):this._push(Ac,1,0)}fork(){return this.states=new _c(this),this.head=this.tail=new rr(Sc,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 rr(Sc,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=Hg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ac(r,e,t){e[t]=r&255}function Wg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ic=class extends rr{next;constructor(e,t){super(Wg,e,t),this.next=void 0}};function ss(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 Vn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Gg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(zn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Yg,e,r),this},zn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Xg,e,r),this});function Yg(r,e,t){e.set(r,t)}function Xg(r,e,t){r.length<40?wc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Cc(){return new zn}function ke(r,e){let t=Cc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Vr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Vr||(Vr={}));function is(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Tc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return is("enum",Vr.VARINT,t,n)}function Oe(r,e){return is("message",Vr.LENGTH_DELIMITED,r,e)}var nr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Hn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));var Lc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Lc||(Lc={}));(function(r){r.codec=()=>Tc(Lc)})(fe||(fe={}));var at;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(at||(at={}));var Pc;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Pc||(Pc={}));function zr(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return Rt(r)}var Gn={};Me(Gn,{MAX_RSA_KEY_SIZE:()=>Dc,generateRSAKeyPair:()=>Kc,jwkToJWKKeyPair:()=>Sd,jwkToPkcs1:()=>Jg,jwkToPkix:()=>Nc,jwkToRSAPrivateKey:()=>Uc,pkcs1MessageToJwk:()=>kc,pkcs1MessageToRSAPrivateKey:()=>Mc,pkcs1ToJwk:()=>Qg,pkcs1ToRSAPrivateKey:()=>vd,pkixMessageToJwk:()=>Oc,pkixMessageToRSAPublicKey:()=>Fc,pkixToJwk:()=>e0,pkixToRSAPublicKey:()=>Bc});var Hr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}verify(e,t,n){return Ed(this.jwk,t,e,n)}},Wn=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}sign(e,t){return xd(this.jwk,e,t)}};var Dc=8192,Rc=18,Zg=1062,jg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Qg(r){let e=ht(r);return kc(e)}function kc(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function Jg(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 C("JWK was missing components");return Ze([Pe(Uint8Array.from([0])),Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url")),Pe(L(r.d,"base64url")),Pe(L(r.p,"base64url")),Pe(L(r.q,"base64url")),Pe(L(r.dp,"base64url")),Pe(L(r.dq,"base64url")),Pe(L(r.qi,"base64url"))]).subarray()}function e0(r){let e=ht(r,{offset:0});return Oc(e)}function Oc(r){let e=ht(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function Nc(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");return Ze([jg,Tn(Ze([Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url"))]))]).subarray()}function vd(r){let e=ht(r);return Mc(e)}function Mc(r){let e=kc(r);return Uc(e)}function Bc(r,e){if(r.byteLength>=Zg)throw new _r("Key size is too large");let t=ht(r,{offset:0});return Fc(t,r,e)}function Fc(r,e,t){let n=Oc(r);if(t==null){let o=Or(at.encode({Type:fe.RSA,Data:e}));t=ot(Rc,o)}return new Hr(n,t)}function Uc(r){if(_d(r)>Dc)throw new C("Key size is too large");let e=Sd(r),t=Or(at.encode({Type:fe.RSA,Data:Nc(e.publicKey)})),n=ot(Rc,t);return new Wn(e.privateKey,new Hr(e.publicKey,n))}async function Kc(r){if(r>Dc)throw new C("Key size is too large");let e=await Ad(r),t=Or(at.encode({Type:fe.RSA,Data:Nc(e.publicKey)})),n=ot(Rc,t);return new Wn(e.privateKey,new Hr(e.publicKey,n))}function Sd(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ad(r,e){let t=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await t0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function xd(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Fe.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 Ed(r,e,t,n){let o=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function t0(r,e){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");let t=await Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function _d(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return L(r.n,"base64url").length*8}var as=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Wo(e),V(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),mt(o)}update(e){return kr(this),this.iHash.update(e),this}digestInto(e){kr(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=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()}},qc=(r,e,t)=>new as(r,e).update(t).digest();qc.create=(r,e)=>new as(r,e);var Id=(r,e)=>(r+(r>=0?e:-e)/Cd)/e;function r0(r,e,t){let[[n,o],[s,i]]=e,a=Id(i*r,t),c=Id(-o*r,t),l=r-a*n-c*s,f=-a*o-c*i,u=l<xt,d=f<xt;u&&(l=-l),d&&(f=-f);let h=On(Math.ceil(Ja(t)/2))+Wr;if(l<xt||l>=h||f<xt||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function Vc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function $c(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return wt(t.lowS,"lowS"),wt(t.prehash,"prehash"),t.format!==void 0&&Vc(t.format),t}var zc=class extends Error{constructor(e=""){super(e)}},Kt={Err:zc,_tlv:{encode:(r,e)=>{let{Err:t}=Kt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Rn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Rn(o.length/2|128):"";return Rn(r)+s+o+e},decode(r,e){let{Err:t}=Kt,n=0;if(r<0||r>256)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 f of l)i=i<<8|f;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}=Kt;if(r<xt)throw new e("integer: negative integers are not allowed");let t=Rn(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}=Kt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Nr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Kt,o=V(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:f}=n.decode(2,c);if(f.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}=Kt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},xt=BigInt(0),Wr=BigInt(1),Cd=BigInt(2),cs=BigInt(3),n0=BigInt(4);function Td(r,e={}){let t=Qo("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Mt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=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 l=Pd(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,b,w){let{x:y,y:_}=b.toAffine(),T=n.toBytes(y);if(wt(w,"isCompressed"),w){f();let D=!n.isOdd(_);return Be(Ld(D),T)}else return Be(Uint8Array.of(4),T,n.toBytes(_))}function d(R){V(R,void 0,"Point");let{publicKey:b,publicKeyUncompressed:w}=l,y=R.length,_=R[0],T=R.subarray(1);if(y===b&&(_===2||_===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let k=E(D),P;try{P=n.sqrt(k)}catch(oe){let re=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+re)}f();let M=n.isOdd(P);return(_&1)===1!==M&&(P=n.neg(P)),{x:D,y:P}}else if(y===w&&_===4){let D=n.BYTES,k=n.fromBytes(T.subarray(0,D)),P=n.fromBytes(T.subarray(D,D*2));if(!m(k,P))throw new Error("bad point: is not on curve");return{x:k,y:P}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${w}`)}let h=e.toBytes||u,p=e.fromBytes||d;function E(R){let b=n.sqr(R),w=n.mul(b,R);return n.add(n.add(w,n.mul(R,s.a)),s.b)}function m(R,b){let w=n.sqr(b),y=E(R);return n.eql(w,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,cs),n0),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,A)))throw new Error("bad curve params: a or b");function x(R,b,w=!1){if(!n.isValid(b)||w&&n.is0(b))throw new Error(`bad point coordinate ${R}`);return b}function I(R){if(!(R instanceof v))throw new Error("Weierstrass Point expected")}function O(R){if(!c||!c.basises)throw new Error("no endo");return r0(R,c.basises,o.ORDER)}let $=Mr((R,b)=>{let{X:w,Y:y,Z:_}=R;if(n.eql(_,n.ONE))return{x:w,y};let T=R.is0();b==null&&(b=T?n.ONE:n.inv(_));let D=n.mul(w,b),k=n.mul(y,b),P=n.mul(_,b);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:D,y:k}}),q=Mr(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:w}=R.toAffine();if(!n.isValid(b)||!n.isValid(w))throw new Error("bad point: x or y not field elements");if(!m(b,w))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(R,b,w,y,_){return w=new v(n.mul(w.X,R),w.Y,w.Z),b=Mn(y,b),w=Mn(_,w),b.add(w)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,w,y){this.X=x("x",b),this.Y=x("y",w,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:w,y}=b||{};if(!b||!n.isValid(w)||!n.isValid(y))throw new Error("invalid affine point");if(b instanceof v)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(y)?v.ZERO:new v(w,y,n.ONE)}static fromBytes(b){let w=v.fromAffine(p(V(b,void 0,"point")));return w.assertValidity(),w}static fromHex(b){return v.fromBytes(yt(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,w=!0){return z.createCache(this,b),w||this.multiply(cs),this}assertValidity(){q(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){I(b);let{X:w,Y:y,Z:_}=this,{X:T,Y:D,Z:k}=b,P=n.eql(n.mul(w,k),n.mul(T,_)),M=n.eql(n.mul(y,k),n.mul(D,_));return P&&M}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:w}=s,y=n.mul(w,cs),{X:_,Y:T,Z:D}=this,k=n.ZERO,P=n.ZERO,M=n.ZERO,K=n.mul(_,_),oe=n.mul(T,T),re=n.mul(D,D),G=n.mul(_,T);return G=n.add(G,G),M=n.mul(_,D),M=n.add(M,M),k=n.mul(b,M),P=n.mul(y,re),P=n.add(k,P),k=n.sub(oe,P),P=n.add(oe,P),P=n.mul(k,P),k=n.mul(G,k),M=n.mul(y,M),re=n.mul(b,re),G=n.sub(K,re),G=n.mul(b,G),G=n.add(G,M),M=n.add(K,K),K=n.add(M,K),K=n.add(K,re),K=n.mul(K,G),P=n.add(P,K),re=n.mul(T,D),re=n.add(re,re),K=n.mul(re,G),k=n.sub(k,K),M=n.mul(re,oe),M=n.add(M,M),M=n.add(M,M),new v(k,P,M)}add(b){I(b);let{X:w,Y:y,Z:_}=this,{X:T,Y:D,Z:k}=b,P=n.ZERO,M=n.ZERO,K=n.ZERO,oe=s.a,re=n.mul(s.b,cs),G=n.mul(w,T),se=n.mul(y,D),be=n.mul(_,k),nt=n.add(w,y),ie=n.add(T,D);nt=n.mul(nt,ie),ie=n.add(G,se),nt=n.sub(nt,ie),ie=n.add(w,_);let ve=n.add(T,k);return ie=n.mul(ie,ve),ve=n.add(G,be),ie=n.sub(ie,ve),ve=n.add(y,_),P=n.add(D,k),ve=n.mul(ve,P),P=n.add(se,be),ve=n.sub(ve,P),K=n.mul(oe,ie),P=n.mul(re,be),K=n.add(P,K),P=n.sub(se,K),K=n.add(se,K),M=n.mul(P,K),se=n.add(G,G),se=n.add(se,G),be=n.mul(oe,be),ie=n.mul(re,ie),se=n.add(se,be),be=n.sub(G,be),be=n.mul(oe,be),ie=n.add(ie,be),G=n.mul(se,ie),M=n.add(M,G),G=n.mul(ve,ie),P=n.mul(nt,P),P=n.sub(P,G),G=n.mul(nt,se),K=n.mul(ve,K),K=n.add(K,G),new v(P,M,K)}subtract(b){return this.add(b.negate())}is0(){return this.equals(v.ZERO)}multiply(b){let{endo:w}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,_,T=D=>z.cached(this,D,k=>Jt(v,k));if(w){let{k1neg:D,k1:k,k2neg:P,k2:M}=O(b),{p:K,f:oe}=T(k),{p:re,f:G}=T(M);_=oe.add(G),y=S(w.beta,K,re,D,P)}else{let{p:D,f:k}=T(b);y=D,_=k}return Jt(v,[y,_])[0]}multiplyUnsafe(b){let{endo:w}=e,y=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===xt||y.is0())return v.ZERO;if(b===Wr)return y;if(z.hasCache(this))return this.multiply(b);if(w){let{k1neg:_,k1:T,k2neg:D,k2:k}=O(b),{p1:P,p2:M}=Jf(v,y,T,k);return S(w.beta,P,M,_,D)}else return z.unsafe(y,b)}toAffine(b){return $(this,b)}isTorsionFree(){let{isTorsionFree:b}=e;return i===Wr?!0:b?b(v,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Wr?this:b?b(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return wt(b,"isCompressed"),this.assertValidity(),h(v,this,b)}toHex(b=!0){return gt(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,z=new Ur(v,e.endo?Math.ceil(B/2):B);return v.BASE.precompute(8),v}function Ld(r){return Uint8Array.of(r?2:3)}function Pd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function o0(r,e={}){let{Fn:t}=r,n=e.randomBytes||Rt,o=Object.assign(Pd(r.Fp,t),{seed:nc(t.ORDER)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:E,publicKeyUncompressed:m}=o;try{let g=h.length;return p===!0&&g!==E||p===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return oc(V(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:E,publicKeyUncompressed:m}=o;if(!Gt(h)||"_lengths"in t&&t._lengths||p===E)return;let g=V(h,void 0,"key").length;return g===E||g===m}function f(h,p,E=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(E)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Jo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:u,lengths:o})}function Dd(r,e,t={}){Wo(e),Mt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Rt,o=t.hmac||((w,y)=>qc(e,w,y)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=o0(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},E=a*Cd<s.ORDER;function m(w){let y=a>>Wr;return w>y}function g(w,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return y}function A(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(w,y){Vc(y);let _=h.signature,T=y==="compact"?_:y==="recovered"?_+1:void 0;return V(w,T)}class I{r;s;recovery;constructor(y,_,T){if(this.r=g("r",y),this.s=g("s",_),T!=null){if(A(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(y,_=p.format){x(y,_);let T;if(_==="der"){let{r:M,s:K}=Kt.toSig(V(y));return new I(M,K)}_==="recovered"&&(T=y[0],_="compact",y=y.subarray(1));let D=h.signature/2,k=y.subarray(0,D),P=y.subarray(D,D*2);return new I(i.fromBytes(k),i.fromBytes(P),T)}static fromHex(y,_){return this.fromBytes(yt(y),_)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new I(this.r,this.s,y)}recoverPublicKey(y){let{r:_,s:T}=this,D=this.assertRecovery(),k=D===2||D===3?_+a:_;if(!s.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=s.toBytes(k),M=r.fromBytes(Be(Ld((D&1)===0),P)),K=i.inv(k),oe=$(V(y,void 0,"msgHash")),re=i.create(-oe*K),G=i.create(T*K),se=r.BASE.multiplyUnsafe(re).add(M.multiplyUnsafe(G));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return m(this.s)}toBytes(y=p.format){if(Vc(y),y==="der")return yt(Kt.hexFromSig(this));let{r:_,s:T}=this,D=i.toBytes(_),k=i.toBytes(T);return y==="recovered"?(A(),Be(Uint8Array.of(this.assertRecovery()),D,k)):Be(D,k)}toHex(y){return gt(this.toBytes(y))}}let O=t.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let _=Nr(y),T=y.length*8-c;return T>0?_>>BigInt(T):_},$=t.bits2int_modN||function(y){return i.create(O(y))},q=On(c);function S(w){return kn("num < 2^"+c,w,xt,q),i.toBytes(w)}function v(w,y){return V(w,void 0,"message"),y?V(e(w),void 0,"prehashed message"):w}function B(w,y,_){let{lowS:T,prehash:D,extraEntropy:k}=$c(_,p);w=v(w,D);let P=$(w),M=i.fromBytes(y);if(!i.isValidNot0(M))throw new Error("invalid private key");let K=[S(M),S(P)];if(k!=null&&k!==!1){let se=k===!0?n(h.secretKey):k;K.push(V(se,void 0,"extraEntropy"))}let oe=Be(...K),re=P;function G(se){let be=O(se);if(!i.isValidNot0(be))return;let nt=i.inv(be),ie=r.BASE.multiply(be).toAffine(),ve=i.create(ie.x);if(ve===xt)return;let Lo=i.create(nt*i.create(re+ve*M));if(Lo===xt)return;let ku=(ie.x===ve?0:2)|Number(ie.y&Wr),Ou=Lo;return T&&m(Lo)&&(Ou=i.neg(Lo),ku^=1),new I(ve,Ou,E?void 0:ku)}return{seed:oe,k2sig:G}}function z(w,y,_={}){let{seed:T,k2sig:D}=B(w,y,_);return Mf(e.outputLen,i.BYTES,o)(T,D).toBytes(_.format)}function R(w,y,_,T={}){let{lowS:D,prehash:k,format:P}=$c(T,p);if(_=V(_,void 0,"publicKey"),y=v(y,k),!Gt(w)){let M=w instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}x(w,P);try{let M=I.fromBytes(w,P),K=r.fromBytes(_);if(D&&M.hasHighS())return!1;let{r:oe,s:re}=M,G=$(y),se=i.inv(re),be=i.create(G*se),nt=i.create(oe*se),ie=r.BASE.multiplyUnsafe(be).add(K.multiplyUnsafe(nt));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function b(w,y,_={}){let{prehash:T}=$c(_,p);return y=v(y,T),I.fromBytes(w,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:z,verify:R,recoverPublicKey:b,Signature:I,hash:e})}var Wc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},s0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Rd=BigInt(2);function i0(r){let e=Wc.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,f=l*l*r%e,u=ne(f,t,e)*f%e,d=ne(u,t,e)*f%e,h=ne(d,Rd,e)*l%e,p=ne(h,o,e)*h%e,E=ne(p,s,e)*p%e,m=ne(E,a,e)*E%e,g=ne(m,c,e)*m%e,A=ne(g,a,e)*E%e,x=ne(A,t,e)*f%e,I=ne(x,i,e)*p%e,O=ne(I,n,e)*l%e,$=ne(O,Rd,e);if(!Hc.eql(Hc.sqr($),r))throw new Error("Cannot find square root");return $}var Hc=Br(Wc.p,{sqrt:i0}),a0=Td(Wc,{Fp:Hc,endo:s0}),Je=Dd(a0,Or);function kd(r,e,t){let n=Rr.digest(e instanceof Uint8Array?e:e.subarray());if(qr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Je.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Fn(String(o))});try{return Je.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Fn(String(o))}}function Od(r,e,t,n){let o=Rr.digest(t instanceof Uint8Array?t:t.subarray());if(qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Je.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Un(String(s))});try{return n?.signal?.throwIfAborted(),Je.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Un(String(s))}}var Yn=class{type="secp256k1";raw;_key;constructor(e){this._key=Bd(e),this.raw=Nd(this._key)}toMultihash(){return Ye.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}verify(e,t,n){return Od(this._key,t,e,n)}},ls=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Md(e),this.publicKey=new Yn(t??Fd(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:j(this.raw,e.raw)}sign(e,t){return kd(this.raw,e,t)}};function Gc(r){return new Yn(r)}async function Ud(){let r=c0();return new ls(r)}function Nd(r){return Je.Point.fromBytes(r).toBytes()}function Md(r){try{return Je.getPublicKey(r,!0),r}catch(e){throw new yn(String(e))}}function Bd(r){try{return Je.Point.fromBytes(r),r}catch(e){throw new _r(String(e))}}function Fd(r){try{return Je.getPublicKey(r,!0)}catch(e){throw new yn(String(e))}}function c0(){return Je.utils.randomSecretKey()}async function Kd(r,e){if(r==="Ed25519")return ud();if(r==="secp256k1")return Ud();if(r==="RSA")return Kc(l0(e));if(r==="ECDSA")return bf(u0(e));throw new Tt}function Gr(r,e){let{Type:t,Data:n}=at.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return Bc(o,e);case fe.Ed25519:return fc(o);case fe.secp256k1:return Gc(o);case fe.ECDSA:return qa(o);default:throw new Tt}}function qd(r){let{Type:e,Data:t}=at.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return fc(n);case fe.secp256k1:return Gc(n);case fe.ECDSA:return qa(n);default:throw new Tt}}function He(r){return at.encode({Type:fe[r.type],Data:r.raw})}function l0(r){return r==null?2048:parseInt(r,10)}function u0(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 C("Unsupported curve, should be P-256, P-384 or P-521")}var $d=Symbol.for("nodejs.util.inspect.custom"),f0=114,Xn=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()})`}[Uo]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(f0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return j(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return j(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[$d](){return`PeerId(${this.toString()})`}},Zn=class extends Xn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},jn=class extends Xn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Qn=class extends Xn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},d0=2336,Jn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ye.digest(L(this.url))}[$d](){return`PeerId(${this.url})`}[Uo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(d0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var h0=114,Vd=2336;function ct(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=dt(J.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return eo(le.parse(r));if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=dt(e.decode(r))}return Yr(t)}function Yc(r){if(r.type==="Ed25519")return new jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Qn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Zn({multihash:r.toCID().multihash,publicKey:r});throw new Tt}function zd(r){return Yc(r.publicKey)}function Yr(r){if(m0(r))return new Zn({multihash:r});if(p0(r))try{let e=qd(r);if(e.type==="Ed25519")return new jn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Qn({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new Jn(new URL(t))}throw new Ro("Supplied PeerID Multihash is invalid")}function eo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==h0&&r.code!==Vd)throw new Do("Supplied PeerID CID is invalid");if(r.code===Vd){let e=U(r.multihash.digest);return new Jn(new URL(e))}return Yr(r.multihash)}function p0(r){return r.code===Ye.code}function m0(r){return r.code===Rr.code}async function Hd(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return r}function g0(r,e){if(typeof r=="string")return y0(r);if(typeof r=="number")return x0(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var us=g0;function y0(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 b0(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 w0(r){let e=Math.abs(r);return e>=315576e5?or(r,e,315576e5,"year"):e>=26298e5?or(r,e,26298e5,"month"):e>=6048e5?or(r,e,6048e5,"week"):e>=864e5?or(r,e,864e5,"day"):e>=36e5?or(r,e,36e5,"hour"):e>=6e4?or(r,e,6e4,"minute"):e>=1e3?or(r,e,1e3,"second"):`${r} ms`}function x0(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?w0(r):b0(r)}function or(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Xc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=us,t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let d=0;d<f.length;d++)u=(u<<5)-u+f.charCodeAt(d),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f,u){let d,h=null,p,E;function m(...g){if(!m.enabled)return;let A=m,x=Number(new Date),I=x-(d||x);A.diff=I,A.prev=d,A.curr=x,d=x,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let O=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(q,S)=>{if(q==="%%")return"%";O++;let v=t.formatters[S];if(typeof v=="function"){let B=g[O];q=v.call(A,B),g.splice(O,1),O--}return q}),t.formatArgs.call(A,g),u?.onLog!=null&&u.onLog(...g),(A.log||t.log).apply(A,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,E=t.enabled(f)),E),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,u){let d=t(this.namespace+(typeof u>"u"?":":u)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(u=0;u<h;u++)d[u]&&(f=d[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let u,d;for(u=0,d=t.skips.length;u<d;u++)if(t.skips[u].test(f))return!1;for(u=0,d=t.names.length;u<d;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function 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 fs=C0(),E0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function v0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.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 S0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+us(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 A0=console.debug??console.log??(()=>{});function _0(r){try{r?fs?.setItem("debug",r):fs?.removeItem("debug")}catch{}}function I0(){let r;try{r=fs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function C0(){try{return localStorage}catch{}}function T0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Wd=Xc({formatArgs:S0,save:_0,load:I0,useColors:v0,setupFormatters:T0,colors:E0,storage:fs,log:A0});var Ue=Wd;Ue.formatters.b=r=>r==null?"undefined":J.baseEncode(r);Ue.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);Ue.formatters.m=r=>r==null?"undefined":Ta.baseEncode(r);Ue.formatters.p=r=>r==null?"undefined":r.toString();Ue.formatters.c=r=>r==null?"undefined":r.toString();Ue.formatters.k=r=>r==null?"undefined":r.toString();Ue.formatters.a=r=>r==null?"undefined":r.toString();function Gd(r,e=""){let t=Yd(r.message),n=Yd(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var Libp2P=(()=>{var Pp=Object.create;var Do=Object.defineProperty;var Dp=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var kp=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var ca=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Me=(r,e)=>{for(var t in e)Do(r,t,{get:e[t],enumerable:!0})},Ru=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rp(e))!Op.call(r,o)&&o!==t&&Do(r,o,{get:()=>e[o],enumerable:!(n=Dp(e,o))||n.enumerable});return r};var la=(r,e,t)=>(t=r!=null?Pp(kp(r)):{},Ru(e||!r||!r.__esModule?Do(t,"default",{value:r,enumerable:!0}):t,r)),Np=r=>Ru(Do({},"__esModule",{value:!0}),r);var sh=ca(io=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,f,u,d;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,d=c&255,[l,f,u,d].join(".")},i=function(c){var l,f,u,d,h,p;for(l=[],u=d=0;d<=3&&c.length!==0;u=++d){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,f,u,d,h;for(d=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)d=d*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")d=d*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")d=d*l+(10+t(c[u])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[d,u]},r=(function(){function c(l,f){var u,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(E){throw u=E,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(E){throw u=E,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,u,d;for(d=i(this.first),u=i(this.last),f=0;d<=u;)l(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),io.ip2long=i,io.long2ip=a,io.Netmask=r}).call(io)});var hp=ca((RT,lu)=>{"use strict";var Ab=Object.prototype.hasOwnProperty,Ne="~";function Ao(){}Object.create&&(Ao.prototype=Object.create(null),new Ao().__proto__||(Ne=!1));function _b(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function dp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new _b(t,n||r,o),i=Ne?Ne+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 zi(r,e){--r._eventsCount===0?r._events=new Ao:delete r._events[e]}function Te(){this._events=new Ao,this._eventsCount=0}Te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ab.call(t,n)&&e.push(Ne?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Te.prototype.listeners=function(e){var t=Ne?Ne+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};Te.prototype.listenerCount=function(e){var t=Ne?Ne+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Te.prototype.emit=function(e,t,n,o,s,i){var a=Ne?Ne+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,u;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(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var d=c.length,h;for(u=0;u<d;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};Te.prototype.on=function(e,t,n){return dp(this,e,t,n,!1)};Te.prototype.once=function(e,t,n){return dp(this,e,t,n,!0)};Te.prototype.removeListener=function(e,t,n,o){var s=Ne?Ne+e:e;if(!this._events[s])return this;if(!t)return zi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&zi(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:zi(this,s)}return this};Te.prototype.removeAllListeners=function(e){var t;return e?(t=Ne?Ne+e:e,this._events[t]&&zi(this,t)):(this._events=new Ao,this._eventsCount=0),this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.addListener=Te.prototype.on;Te.prefixed=Ne;Te.EventEmitter=Te;typeof lu<"u"&&(lu.exports=Te)});var gp=ca((e4,mp)=>{mp.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 Yb={};Me(Yb,{createLibp2p:()=>Gb,dnsaddrResolver:()=>Ar,isLibp2p:()=>Xb});var ku=Symbol.for("@libp2p/connection");var ua=Symbol.for("@libp2p/content-routing");var Ge=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var C=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_r=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},yn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var zt=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Ht=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ir=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ct=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ro=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ko=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Oo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},No=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Mo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ut=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Cr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var bn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Bo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Fo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Tt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Uo=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var fa=Symbol.for("@libp2p/peer-discovery");var Ko=Symbol.for("@libp2p/peer-id");function Lt(r){return!!r?.[Ko]}var da=Symbol.for("@libp2p/peer-routing");var ha="keep-alive";function qo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ou(...r){let e=[];for(let t of r)qo(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 Nu(...r){let e=[];for(let t of r)qo(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 aw=Symbol.for("@libp2p/transport");var wn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(wn||(wn={}));var Le=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){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xn=Symbol.for("@libp2p/service-capabilities"),pa=Symbol.for("@libp2p/service-dependencies");var wa={};Me(wa,{base58btc:()=>J,base58flickr:()=>$p});var Nw=new Uint8Array(0);function Mu(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 ft(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 Bu(r){return new TextEncoder().encode(r)}function Fu(r){return new TextDecoder().decode(r)}function Mp(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),f=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var E=0,m=0,g=0,A=p.length;g!==A&&p[g]===0;)g++,E++;for(var x=(A-g)*f+1>>>0,I=new Uint8Array(x);g!==A;){for(var O=p[g],$=0,q=x-1;(O!==0||$<m)&&q!==-1;q--,$++)O+=256*I[q]>>>0,I[q]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=$,g++}for(var S=x-m;S!==x&&I[S]===0;)S++;for(var v=c.repeat(E);S<x;++S)v+=r.charAt(I[S]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var E=0;if(p[E]!==" "){for(var m=0,g=0;p[E]===c;)m++,E++;for(var A=(p.length-E)*l+1>>>0,x=new Uint8Array(A);p[E];){var I=t[p.charCodeAt(E)];if(I===255)return;for(var O=0,$=A-1;(I!==0||O<g)&&$!==-1;$--,O++)I+=a*x[$]>>>0,x[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=O,E++}if(p[E]!==" "){for(var q=A-g;q!==A&&x[q]===0;)q++;for(var S=new Uint8Array(m+(A-q)),v=m;q!==A;)S[v++]=x[q++];return S}}}function h(p){var E=d(p);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:h}}var Bp=Mp,Fp=Bp,Ku=Fp;var ma=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")}},ga=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 qu(this,e)}},ya=class{decoders;constructor(e){this.decoders=e}or(e){return qu(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 qu(r,e){return new ya({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ba=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 ma(e,t,n),this.decoder=new ga(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Tr({name:r,prefix:e,encode:t,decode:n}){return new ba(r,e,t,n)}function Pt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Ku(t,r);return Tr({prefix:e,name:r,encode:n,decode:s=>ft(o(s))})}function Up(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 f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,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 Kp(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 qp(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=qp(n);return Tr({prefix:e,name:r,encode(s){return Kp(s,n,t)},decode(s){return Up(s,o,t,r)}})}var J=Pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$p=Pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xa={};Me(xa,{base32:()=>ze,base32hex:()=>Wp,base32hexpad:()=>jp,base32hexpadupper:()=>Xp,base32hexupper:()=>Gp,base32pad:()=>zp,base32padupper:()=>Hp,base32upper:()=>Vp,base32z:()=>Yp});var ze=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vp=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zp=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hp=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wp=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gp=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jp=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xp=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yp=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ea={};Me(Ea,{base36:()=>En,base36upper:()=>Zp});var En=Pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zp=Pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qp=zu,$u=128,Jp=127,em=~Jp,tm=Math.pow(2,31);function zu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tm;)e[t++]=r&255|$u,r/=128;for(;r&em;)e[t++]=r&255|$u,r>>>=7;return e[t]=r|0,zu.bytes=t-n+1,e}var rm=va,nm=128,Vu=127;function va(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw va.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Vu)<<o:(i&Vu)*Math.pow(2,o),o+=7}while(i>=nm);return va.bytes=s-n,t}var om=Math.pow(2,7),sm=Math.pow(2,14),im=Math.pow(2,21),am=Math.pow(2,28),cm=Math.pow(2,35),lm=Math.pow(2,42),um=Math.pow(2,49),fm=Math.pow(2,56),dm=Math.pow(2,63),hm=function(r){return r<om?1:r<sm?2:r<im?3:r<am?4:r<cm?5:r<lm?6:r<um?7:r<fm?8:r<dm?9:10},pm={encode:Qp,decode:rm,encodingLength:hm},mm=pm,vn=mm;function Sn(r,e=0){return[vn.decode(r,e),vn.decode.bytes]}function Lr(r,e,t=0){return vn.encode(r,e,t),e}function Pr(r){return vn.encodingLength(r)}function ot(r,e){let t=e.byteLength,n=Pr(r),o=n+Pr(t),s=new Uint8Array(o+t);return Lr(r,s,0),Lr(t,s,n),s.set(e,o),new Dr(r,t,e,s)}function dt(r){let e=ft(r),[t,n]=Sn(e),[o,s]=Sn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Dr(t,o,i,e)}function Hu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Mu(r.bytes,t.bytes)}}var Dr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Wu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return ym(t,Sa(r),e??J.encoder);default:return bm(t,Sa(r),e??ze.encoder)}}var Gu=new WeakMap;function Sa(r){let e=Gu.get(r);if(e==null){let t=new Map;return Gu.set(r,t),t}return e}var le=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!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wm)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=ot(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&&Hu(e.multihash,n.multihash)}toString(e){return Wu(this,e)}toJSON(){return{"/":Wu(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??ju(n,o,s.bytes))}else if(t[xm]===!0){let{version:n,multihash:o,code:s}=t,i=dt(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!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ju(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,An,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=ft(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 Dr(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[u,d]=Sn(e.subarray(t));return t+=d,u},o=n(),s=An;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,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=gm(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 Sa(s).set(n,e),s}};function gm(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.prefix,t.decode(r)]}case En.prefix:{let t=e??En;return[En.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 ym(r,e,t){let{prefix:n}=t;if(n!==J.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 bm(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 An=112,wm=18;function ju(r,e,t){let n=Pr(r),o=n+Pr(e),s=new Uint8Array(o+t.byteLength);return Lr(r,s,0),Lr(e,s,n),s.set(t,o),s}var xm=Symbol.for("@ipld/js-cid/CID");var Aa={};Me(Aa,{identity:()=>je});var Xu=0,Em="identity",Yu=ft;function vm(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 ot(Xu,Yu(r))}var je={code:Xu,name:Em,encode:Yu,digest:vm};function Z(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 ce(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function Xe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Qu=Symbol.for("@achingbrain/uint8arraylist");function Zu(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 Vo(r){return!!r?.[Qu]}var Q=class r{bufs;length;[Qu]=!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(Vo(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Vo(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=Zu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Zu(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(Vo(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 Xe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Xe(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,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Vo(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 u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}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=Se(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=ce(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=ce(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=ce(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=Se(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=ce(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=ce(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=ce(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=ce(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=ce(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(!Z(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 _a={};Me(_a,{base10:()=>Sm});var Sm=Pt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ia={};Me(Ia,{base16:()=>Am,base16upper:()=>_m});var Am=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_m=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ca={};Me(Ca,{base2:()=>Im});var Im=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ta={};Me(Ta,{base256emoji:()=>Dm});var Ju=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}"),Cm=Ju.reduce((r,e,t)=>(r[t]=e,r),[]),Tm=Ju.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Lm(r){return r.reduce((e,t)=>(e+=Cm[t],e),"")}function Pm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Tm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Dm=Tr({prefix:"\u{1F680}",name:"base256emoji",encode:Lm,decode:Pm});var Da={};Me(Da,{base64:()=>La,base64pad:()=>Rm,base64url:()=>Pa,base64urlpad:()=>km});var La=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rm=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Pa=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),km=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ra={};Me(Ra,{base8:()=>Om});var Om=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ka={};Me(ka,{identity:()=>Nm});var Nm=Tr({prefix:"\0",name:"identity",encode:r=>Fu(r),decode:r=>Bu(r)});var bx=new TextEncoder,wx=new TextDecoder;var Ma={};Me(Ma,{sha256:()=>Rr,sha512:()=>Um});var Fm=20;function Na({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Oa(r,e,t,n,o)}var Oa=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Fm,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?ef(n,this.code,t?.truncate):n.then(o=>ef(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ef(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 ot(e,r)}function rf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Rr=Na({name:"sha2-256",code:18,encode:rf("SHA-256")}),Um=Na({name:"sha2-512",code:19,encode:rf("SHA-512")});var _n={...ka,...Ca,...Ra,..._a,...Ia,...xa,...Ea,...wa,...Da,...Ta},Dx={...Ma,...Aa};function of(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var nf=of("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ba=of("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=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Km={utf8:nf,"utf-8":nf,hex:_n.base16,latin1:Ba,ascii:Ba,binary:Ba,..._n},zo=Km;function L(r,e="utf8"){let t=zo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function U(r,e="utf8"){let t=zo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var qm=parseInt("11111",2),Fa=parseInt("10000000",2),$m=parseInt("01111111",2),sf={0:In,1:In,2:Vm,3:Wm,4:Gm,5:Hm,6:zm,16:In,22:In,48:In};function ht(r,e={offset:0}){let t=r[e.offset]&qm;if(e.offset++,sf[t]!=null)return sf[t](r,e);throw new Error("No decoder for tag "+t)}function Cn(r,e){let t=0;if((r[e.offset]&Fa)===Fa){let n=r[e.offset]&$m,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 In(r,e){Cn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ht(r,e);if(n===null)break;t.push(n)}return t}function Vm(r,e){let t=Cn(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 zm(r,e){let t=Cn(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 f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function Hm(r,e){return e.offset++,null}function Wm(r,e){let t=Cn(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 Gm(r,e){let t=Cn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function jm(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Q;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ho(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=jm(r.byteLength);return new Q(Uint8Array.from([e.byteLength|Fa]),e)}function Pe(r){let e=new Q,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Q(Uint8Array.from([2]),Ho(e),e)}function Tn(r){let e=Uint8Array.from([0]),t=new Q(e,r);return new Q(Uint8Array.from([3]),Ho(t),t)}function af(r){return new Q(Uint8Array.from([4]),Ho(r),r)}function Ye(r,e=48){let t=new Q;for(let n of r)t.append(n);return new Q(Uint8Array.from([e]),Ho(t),t)}async function cf(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 lf(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 uf(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}var Xm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ym=Uint8Array.from([6,5,43,129,4,0,34]),Zm=Uint8Array.from([6,5,43,129,4,0,35]),Qm={ext:!0,kty:"EC",crv:"P-256"},Jm={ext:!0,kty:"EC",crv:"P-384"},eg={ext:!0,kty:"EC",crv:"P-521"},Ua=32,Ka=48,qa=66;function $a(r){let e=ht(r);return ff(e)}function ff(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Ua*2+1)return n=U(e.subarray(t,t+Ua),"base64url"),o=U(e.subarray(t+Ua),"base64url"),new Wt({...Qm,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ka*2+1)return n=U(e.subarray(t,t+Ka),"base64url"),o=U(e.subarray(t+Ka),"base64url"),new Wt({...Jm,key_ops:["verify"],x:n,y:o});if(e.byteLength===qa*2+1)return n=U(e.subarray(t,t+qa),"base64url"),o=U(e.subarray(t+qa),"base64url"),new Wt({...eg,key_ops:["verify"],x:n,y:o});throw new C(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function df(r){return Ye([Pe(Uint8Array.from([1])),af(L(r.d??"","base64url")),Ye([pf(r.crv)],160),Ye([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function hf(r){return Ye([Pe(Uint8Array.from([1])),Ye([pf(r.crv)],160),Ye([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function pf(r){if(r==="P-256")return Xm;if(r==="P-384")return Ym;if(r==="P-521")return Zm;throw new C(`Invalid curve ${r}`)}async function mf(r="P-256"){let e=await cf(r);return new Wo(e.privateKey)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=hf(this.jwk)),this._raw}toMultihash(){return je.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async verify(e,t,n){return uf(this.jwk,t,e,n)}},Wo=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Wt({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=df(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async sign(e,t){return lf(this.jwk,e,t)}};function Gt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function st(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function V(r,e,t=""){let n=Gt(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}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Go(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");st(r.outputLen),st(r.blockLen)}function kr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function yf(r,e){V(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function mt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function jo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ze(r,e){return r<<32-e|r>>>e}var bf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",tg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gt(r){if(V(r),bf)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=tg[r[t]];return e}var pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function gf(r){if(r>=pt._0&&r<=pt._9)return r-pt._0;if(r>=pt.A&&r<=pt.F)return r-(pt.A-10);if(r>=pt.a&&r<=pt.f)return r-(pt.a-10)}function yt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(bf)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("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=gf(r.charCodeAt(s)),a=gf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Be(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];V(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 Va(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.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Rt(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var za=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function wf(r,e,t){return r&e^~r&t}function xf(r,e,t){return r&e^r&t^e&t}var Ln=class{blockLen;outputLen;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=jo(this.buffer)}update(e){kr(this),V(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=jo(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kr(this),yf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,mt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=jo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],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()}},bt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Xo=BigInt(4294967295),Ef=BigInt(32);function rg(r,e=!1){return e?{h:Number(r&Xo),l:Number(r>>Ef&Xo)}:{h:Number(r>>Ef&Xo)|0,l:Number(r&Xo)|0}}function vf(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}=rg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ha=(r,e,t)=>r>>>t,Wa=(r,e,t)=>r<<32-t|e>>>t,jt=(r,e,t)=>r>>>t|e<<32-t,Xt=(r,e,t)=>r<<32-t|e>>>t,Pn=(r,e,t)=>r<<64-t|e>>>t-32,Dn=(r,e,t)=>r>>>t-32|e<<64-t;function it(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Sf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Af=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,_f=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),If=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Cf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Tf=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var og=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),Ga=class extends Ln{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 u=0;u<16;u++,t+=4)kt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=kt[u-15],h=kt[u-2],p=Ze(d,7)^Ze(d,18)^d>>>3,E=Ze(h,17)^Ze(h,19)^h>>>10;kt[u]=E+kt[u-7]+p+kt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=Ze(a,6)^Ze(a,11)^Ze(a,25),h=f+d+wf(a,c,l)+og[u]+kt[u]|0,E=(Ze(n,2)^Ze(n,13)^Ze(n,22))+xf(n,o,s)|0;f=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|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,f=f+this.H|0,this.set(n,o,s,i,a,c,l,f)}roundClean(){mt(kt)}destroy(){this.set(0,0,0,0,0,0,0,0),mt(this.buffer)}},ja=class extends Ga{A=bt[0]|0;B=bt[1]|0;C=bt[2]|0;D=bt[3]|0;E=bt[4]|0;F=bt[5]|0;G=bt[6]|0;H=bt[7]|0;constructor(){super(32)}};var Lf=vf(["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))),sg=Lf[0],ig=Lf[1],Ot=new Uint32Array(80),Nt=new Uint32Array(80),Xa=class extends Ln{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:f,Fh:u,Fl:d,Gh:h,Gl:p,Hh:E,Hl:m}=this;return[e,t,n,o,s,i,a,c,l,f,u,d,h,p,E,m]}set(e,t,n,o,s,i,a,c,l,f,u,d,h,p,E,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=E|0,this.Hl=m|0}process(e,t){for(let x=0;x<16;x++,t+=4)Ot[x]=e.getUint32(t),Nt[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let I=Ot[x-15]|0,O=Nt[x-15]|0,$=jt(I,O,1)^jt(I,O,8)^Ha(I,O,7),q=Xt(I,O,1)^Xt(I,O,8)^Wa(I,O,7),S=Ot[x-2]|0,v=Nt[x-2]|0,B=jt(S,v,19)^Pn(S,v,61)^Ha(S,v,6),z=Xt(S,v,19)^Dn(S,v,61)^Wa(S,v,6),R=_f(q,z,Nt[x-7],Nt[x-16]),b=If(R,$,B,Ot[x-7],Ot[x-16]);Ot[x]=b|0,Nt[x]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:p,Gh:E,Gl:m,Hh:g,Hl:A}=this;for(let x=0;x<80;x++){let I=jt(u,d,14)^jt(u,d,18)^Pn(u,d,41),O=Xt(u,d,14)^Xt(u,d,18)^Dn(u,d,41),$=u&h^~u&E,q=d&p^~d&m,S=Cf(A,O,q,ig[x],Nt[x]),v=Tf(S,g,I,$,sg[x],Ot[x]),B=S|0,z=jt(n,o,28)^Pn(n,o,34)^Pn(n,o,39),R=Xt(n,o,28)^Dn(n,o,34)^Dn(n,o,39),b=n&s^n&a^s&a,w=o&i^o&c^i&c;g=E|0,A=m|0,E=h|0,m=p|0,h=u|0,p=d|0,{h:u,l:d}=it(l|0,f|0,v|0,B|0),l=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=Sf(B,R,w);n=Af(y,v,z,b),o=y|0}({h:n,l:o}=it(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=it(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=it(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=it(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=it(this.Eh|0,this.El|0,u|0,d|0),{h,l:p}=it(this.Fh|0,this.Fl|0,h|0,p|0),{h:E,l:m}=it(this.Gh|0,this.Gl|0,E|0,m|0),{h:g,l:A}=it(this.Hh|0,this.Hl|0,g|0,A|0),this.set(n,o,s,i,a,c,l,f,u,d,h,p,E,m,g,A)}roundClean(){mt(Ot,Nt)}destroy(){mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ya=class extends Xa{Ah=we[0]|0;Al=we[1]|0;Bh=we[2]|0;Bl=we[3]|0;Ch=we[4]|0;Cl=we[5]|0;Dh=we[6]|0;Dl=we[7]|0;Eh=we[8]|0;El=we[9]|0;Fh=we[10]|0;Fl=we[11]|0;Gh=we[12]|0;Gl=we[13]|0;Hh=we[14]|0;Hl=we[15]|0;constructor(){super(64)}};var Or=Va(()=>new ja,za(1));var Pf=Va(()=>new Ya,za(3));var Qa=BigInt(0),Za=BigInt(1);function wt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Df(r){if(typeof r=="bigint"){if(!Yo(r))throw new Error("positive bigint expected, got "+r)}else st(r);return r}function Rn(r){let e=Df(r).toString(16);return e.length&1?"0"+e:e}function Rf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Qa:BigInt("0x"+r)}function Nr(r){return Rf(gt(r))}function Yt(r){return Rf(gt(Qo(V(r)).reverse()))}function Zo(r,e){st(e),r=Df(r);let t=yt(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Ja(r,e){return Zo(r,e).reverse()}function Qo(r){return Uint8Array.from(r)}var Yo=r=>typeof r=="bigint"&&Qa<=r;function ag(r,e,t){return Yo(r)&&Yo(e)&&Yo(t)&&e<=r&&r<t}function kn(r,e,t,n){if(!ag(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ec(r){let e;for(e=0;r>Qa;r>>=Za,e+=1);return e}var On=r=>(Za<<BigInt(r))-Za;function kf(r,e,t){if(st(r,"hashLen"),st(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),f=0,u=()=>{c.fill(1),l.fill(0),f=0},d=(...m)=>t(l,Be(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let A=c.slice();g.push(A),m+=c.length}return Be(...g)};return(m,g)=>{u(),h(m);let A;for(;!(A=g(p()));)h();return u(),A}}function Mt(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`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)}function Mr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var De=BigInt(0),he=BigInt(1),Zt=BigInt(2),Mf=BigInt(3),Bf=BigInt(4),Ff=BigInt(5),cg=BigInt(7),Uf=BigInt(8),lg=BigInt(9),Kf=BigInt(16);function ue(r,e){let t=r%e;return t>=De?t:e+t}function ne(r,e,t){let n=r;for(;e-- >De;)n*=n,n%=t;return n}function Of(r,e){if(r===De)throw new Error("invert: expected non-zero number");if(e<=De)throw new Error("invert: expected positive modulus, got "+e);let t=ue(r,e),n=e,o=De,s=he,i=he,a=De;for(;t!==De;){let l=n/t,f=n%t,u=o-i*l,d=s-a*l;n=t,t=f,o=i,s=a,i=u,a=d}if(n!==he)throw new Error("invert: does not exist");return ue(o,e)}function rc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function qf(r,e){let t=(r.ORDER+he)/Bf,n=r.pow(e,t);return rc(r,n,e),n}function ug(r,e){let t=(r.ORDER-Ff)/Uf,n=r.mul(e,Zt),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,Zt),o),a=r.mul(s,r.sub(i,r.ONE));return rc(r,a,e),a}function fg(r){let e=Br(r),t=$f(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+cg)/Kf;return(a,c)=>{let l=a.pow(c,i),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(f),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,p);let E=a.eql(a.sqr(f),c),m=a.cmov(l,f,E);return rc(a,m,c),m}}function $f(r){if(r<Mf)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%Zt===De;)e/=Zt,t++;let n=Zt,o=Br(r);for(;Nf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return qf;let s=o.pow(n,e),i=(e+he)/Zt;return function(c,l){if(c.is0(l))return l;if(Nf(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,E=c.sqr(d);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===f)throw new Error("Cannot find square root");let m=he<<BigInt(f-p-1),g=c.pow(u,m);f=p,u=c.sqr(g),d=c.mul(d,u),h=c.mul(h,g)}return h}}function dg(r){return r%Bf===Mf?qf:r%Uf===Ff?ug:r%Kf===lg?fg(r):$f(r)}var Vf=(r,e)=>(ue(r,e)&he)===he,hg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=hg.reduce((n,o)=>(n[o]="function",n),e);return Mt(r,t),r}function pg(r,e,t){if(t<De)throw new Error("invalid exponent, negatives unsupported");if(t===De)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>De;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Nn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Nf(r,e){let t=(r.ORDER-he)/Zt,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function mg(r,e){e!==void 0&&st(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var tc=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=he;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=De)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=mg(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return De<=e&&e<this.ORDER}is0(e){return e===De}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return pg(this,e,t)}div(e,t){return ue(e*Of(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 Of(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=dg(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ja(e,this.BYTES):Zo(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!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?Yt(e):Nr(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e)}cmov(e,t,n){return n?t:e}};function Br(r,e={}){return new tc(r,e)}function zf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function oc(r){let e=zf(r);return e+Math.ceil(e/2)}function sc(r,e,t=!1){V(r);let n=r.length,o=zf(e),s=oc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Yt(r):Nr(r),a=ue(i,e-he)+he;return t?Ja(a,o):Zo(a,o)}var Fr=BigInt(0),Qt=BigInt(1);function Mn(r,e){let t=e.negate();return r?t:e}function Jt(r,e){let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function jf(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ic(r,e){jf(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=On(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Hf(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+=Qt);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}var ac=new WeakMap,Xf=new WeakMap;function cc(r){return Xf.get(r)||1}function Wf(r){if(r!==Fr)throw new Error("invalid wNAF")}var Ur=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>Fr;)t&Qt&&(n=n.add(o)),o=o.double(),t>>=Qt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=ic(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=ic(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=Hf(n,a,i);n=c,f?s=s.add(Mn(d,t[h])):o=o.add(Mn(u,t[l]))}return Wf(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=ic(e,this.bits);for(let i=0;i<s.windows&&n!==Fr;i++){let{nextN:a,offset:c,isZero:l,isNeg:f}=Hf(n,i,s);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return Wf(n),o}getPrecomputes(e,t,n){let o=ac.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),ac.set(t,o))),o}cached(e,t,n){let o=cc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=cc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){jf(t,this.bits),Xf.set(e,t),ac.delete(e)}hasCache(e){return cc(e)!==1}};function Yf(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Fr||n>Fr;)t&Qt&&(s=s.add(o)),n&Qt&&(i=i.add(o)),o=o.double(),t>>=Qt,n>>=Qt;return{p1:s,p2:i}}function Gf(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nc(e),e}else return Br(r,{isLE:t})}function Jo(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>Fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Gf(e.p,t.Fp,n),s=Gf(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 es(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Bt=BigInt(0),pe=BigInt(1),lc=BigInt(2),gg=BigInt(8);function yg(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 Zf(r,e={}){let t=Jo("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Mt(e,{},{uvRatio:"function"});let a=lc<<BigInt(o.BYTES*8)-pe,c=m=>n.create(m),l=e.uvRatio||((m,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(m,g))}}catch{return{isValid:!1,value:Bt}}});if(!yg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(m,g,A=!1){let x=A?pe:Bt;return kn("coordinate "+m,g,x,a),g}function u(m){if(!(m instanceof p))throw new Error("EdwardsPoint expected")}let d=Mr((m,g)=>{let{X:A,Y:x,Z:I}=m,O=m.is0();g==null&&(g=O?gg:n.inv(I));let $=c(A*g),q=c(x*g),S=n.mul(I,g);if(O)return{x:Bt,y:pe};if(S!==pe)throw new Error("invZ was invalid");return{x:$,y:q}}),h=Mr(m=>{let{a:g,d:A}=s;if(m.is0())throw new Error("bad point: ZERO");let{X:x,Y:I,Z:O,T:$}=m,q=c(x*x),S=c(I*I),v=c(O*O),B=c(v*v),z=c(q*g),R=c(v*c(z+S)),b=c(B+c(A*c(q*S)));if(R!==b)throw new Error("bad point: equation left != right (1)");let w=c(x*I),y=c(O*$);if(w!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy));static ZERO=new p(Bt,pe,pe,Bt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,A,x,I){this.X=f("x",g),this.Y=f("y",A),this.Z=f("z",x,!0),this.T=f("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:A,y:x}=g||{};return f("x",A),f("y",x),new p(A,x,pe,c(A*x))}static fromBytes(g,A=!1){let x=n.BYTES,{a:I,d:O}=s;g=Qo(V(g,x,"point")),wt(A,"zip215");let $=Qo(g),q=g[x-1];$[x-1]=q&-129;let S=Yt($),v=A?a:n.ORDER;kn("point.y",S,Bt,v);let B=c(S*S),z=c(B-pe),R=c(O*B-I),{isValid:b,value:w}=l(z,R);if(!b)throw new Error("bad point: invalid y coordinate");let y=(w&pe)===pe,_=(q&128)!==0;if(!A&&w===Bt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==y&&(w=c(-w)),p.fromAffine({x:w,y:S})}static fromHex(g,A=!1){return p.fromBytes(yt(g),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return E.createCache(this,g),A||this.multiply(lc),this}assertValidity(){h(this)}equals(g){u(g);let{X:A,Y:x,Z:I}=this,{X:O,Y:$,Z:q}=g,S=c(A*q),v=c(O*I),B=c(x*q),z=c($*I);return S===v&&B===z}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:A,Y:x,Z:I}=this,O=c(A*A),$=c(x*x),q=c(lc*c(I*I)),S=c(g*O),v=A+x,B=c(c(v*v)-O-$),z=S+$,R=z-q,b=S-$,w=c(B*R),y=c(z*b),_=c(B*b),T=c(R*z);return new p(w,y,T,_)}add(g){u(g);let{a:A,d:x}=s,{X:I,Y:O,Z:$,T:q}=this,{X:S,Y:v,Z:B,T:z}=g,R=c(I*S),b=c(O*v),w=c(q*x*z),y=c($*B),_=c((I+O)*(S+v)-R-b),T=y-w,D=y+w,k=c(b-A*R),P=c(_*T),M=c(D*k),K=c(_*k),oe=c(T*D);return new p(P,M,oe,K)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:x}=E.cached(this,g,I=>Jt(p,I));return Jt(p,[A,x])[0]}multiplyUnsafe(g,A=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Bt?p.ZERO:this.is0()||g===pe?this:E.unsafe(this,g,x=>Jt(p,x),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:A}=this.toAffine(),x=n.toBytes(A);return x[x.length-1]|=g&pe?128:0,x}toHex(){return gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new Ur(p,o.BITS);return p.BASE.precompute(8),p}function Qf(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Mt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Rt,c=t.adjustScalarBytes||(S=>S),l=t.domain||((S,v,B)=>{if(wt(B,"phflag"),v.length||B)throw new Error("Contexts/pre-hash are not supported");return S});function f(S){return i.create(Yt(S))}function u(S){let v=x.secretKey;V(S,x.secretKey,"secretKey");let B=V(e(S),2*v,"hashedSecretKey"),z=c(B.slice(0,v)),R=B.slice(v,2*v),b=f(z);return{head:z,prefix:R,scalar:b}}function d(S){let{head:v,prefix:B,scalar:z}=u(S),R=o.multiply(z),b=R.toBytes();return{head:v,prefix:B,scalar:z,point:R,pointBytes:b}}function h(S){return d(S).pointBytes}function p(S=Uint8Array.of(),...v){let B=Be(...v);return f(e(l(B,V(S,void 0,"context"),!!n)))}function E(S,v,B={}){S=V(S,void 0,"message"),n&&(S=n(S));let{prefix:z,scalar:R,pointBytes:b}=d(v),w=p(B.context,z,S),y=o.multiply(w).toBytes(),_=p(B.context,y,b,S),T=i.create(w+_*R);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=Be(y,i.toBytes(T));return V(D,x.signature,"result")}let m={zip215:!0};function g(S,v,B,z=m){let{context:R,zip215:b}=z,w=x.signature;S=V(S,w,"signature"),v=V(v,void 0,"message"),B=V(B,x.publicKey,"publicKey"),b!==void 0&&wt(b,"zip215"),n&&(v=n(v));let y=w/2,_=S.subarray(0,y),T=Yt(S.subarray(y,w)),D,k,P;try{D=r.fromBytes(B,b),k=r.fromBytes(_,b),P=o.multiplyUnsafe(T)}catch{return!1}if(!b&&D.isSmallOrder())return!1;let M=p(R,k.toBytes(),D.toBytes(),v);return k.add(D.multiplyUnsafe(M)).subtract(P).clearCofactor().is0()}let A=s.BYTES,x={secretKey:A,publicKey:A,signature:2*A,seed:A};function I(S=a(x.seed)){return V(S,x.seed,"seed")}function O(S){return Gt(S)&&S.length===i.BYTES}function $(S,v){try{return!!r.fromBytes(S,v)}catch{return!1}}let q={getExtendedPublicKey:d,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:$,toMontgomery(S){let{y:v}=r.fromBytes(S),B=x.publicKey,z=B===32;if(!z&&B!==57)throw new Error("only defined for 25519 and 448");let R=z?s.div(pe+v,pe-v):s.div(v-pe,v+pe);return s.toBytes(R)},toMontgomerySecret(S){let v=x.secretKey;V(S,v);let B=e(S.subarray(0,v));return c(B).subarray(0,v)}};return Object.freeze({keygen:es(I,h),getPublicKey:h,sign:E,verify:g,utils:q,Point:r,lengths:x})}var bg=BigInt(1),Jf=BigInt(2);var wg=BigInt(5),xg=BigInt(8),uc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Eg={p:uc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function vg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=uc,a=r*r%s*r%s,c=ne(a,Jf,s)*a%s,l=ne(c,bg,s)*r%s,f=ne(l,wg,s)*l%s,u=ne(f,e,s)*f%s,d=ne(u,t,s)*u%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,E=ne(p,o,s)*h%s,m=ne(E,e,s)*f%s;return{pow_p_5_8:ne(m,Jf,s)*r%s,b2:a}}function Sg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ed=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ag(r,e){let t=uc,n=ue(e*e*e,t),o=ue(n*n*e,t),s=vg(r*o).pow_p_5_8,i=ue(r*n*s,t),a=ue(e*i*i,t),c=i,l=ue(i*ed,t),f=a===r,u=a===ue(-r,t),d=a===ue(-r*ed,t);return f&&(i=c),(u||d)&&(i=l),Vf(i,t)&&(i=ue(-i,t)),{isValid:f||u,value:i}}var _g=Zf(Eg,{uvRatio:Ag});function Ig(r){return Qf(_g,Pf,Object.assign({adjustScalarBytes:Sg},r))}var Bn=Ig({});var Fn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Un=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ts=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var td={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ts("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 Fe=td;var rs=32,Kn=64,fc=32;var Kr,rd=(async()=>{try{return await Fe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function nd(){let r=Bn.utils.randomSecretKey(),e=Bn.getPublicKey(r);return{privateKey:Dg(r,e),publicKey:e}}async function Cg(r,e){let t;r.length===Kn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Fe.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Fe.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Tg(r,e){let t=r.subarray(0,fc);return Bn.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function od(r,e){return Kr==null&&(Kr=await rd),Kr?Cg(r,e):Tg(r,e)}async function Lg(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Fe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Fe.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 Pg(r,e,t){return Bn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function sd(r,e,t){return Kr==null&&(Kr=await rd),Kr?Lg(r,e,t):Pg(r,e,t)}function Dg(r,e){let t=new Uint8Array(Kn);for(let n=0;n<fc;n++)t[n]=r[n],t[fc+n]=e[n];return t}function qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var qn=class{type="Ed25519";raw;constructor(e){this.raw=os(e,rs)}toMultihash(){return je.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=sd(this.raw,t,e);return qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},ns=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=os(e,Kn),this.publicKey=new qn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=od(this.raw,e);return qr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function dc(r){return r=os(r,rs),new qn(r)}async function ad(){let{privateKey:r,publicKey:e}=nd();return new ns(r,e)}function os(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new C(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Rg=Math.pow(2,7),kg=Math.pow(2,14),Og=Math.pow(2,21),hc=Math.pow(2,28),pc=Math.pow(2,35),mc=Math.pow(2,42),gc=Math.pow(2,49),j=128,Ae=127;function me(r){if(r<Rg)return 1;if(r<kg)return 2;if(r<Og)return 3;if(r<hc)return 4;if(r<pc)return 5;if(r<mc)return 6;if(r<gc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $r(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Ng(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function yc(r,e){let t=r[e],n=0;if(n+=t&Ae,t<j||(t=r[e+1],n+=(t&Ae)<<7,t<j)||(t=r[e+2],n+=(t&Ae)<<14,t<j)||(t=r[e+3],n+=(t&Ae)<<21,t<j)||(t=r[e+4],n+=(t&Ae)*hc,t<j)||(t=r[e+5],n+=(t&Ae)*pc,t<j)||(t=r[e+6],n+=(t&Ae)*mc,t<j)||(t=r[e+7],n+=(t&Ae)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function Mg(r,e){let t=r.get(e),n=0;if(n+=t&Ae,t<j||(t=r.get(e+1),n+=(t&Ae)<<7,t<j)||(t=r.get(e+2),n+=(t&Ae)<<14,t<j)||(t=r.get(e+3),n+=(t&Ae)<<21,t<j)||(t=r.get(e+4),n+=(t&Ae)*hc,t<j)||(t=r.get(e+5),n+=(t&Ae)*pc,t<j)||(t=r.get(e+6),n+=(t&Ae)*mc,t<j)||(t=r.get(e+7),n+=(t&Ae)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function Ft(r,e,t=0){return e==null&&(e=Se(me(r))),e instanceof Uint8Array?$r(r,e,t):Ng(r,e,t)}function er(r,e=0){return r instanceof Uint8Array?yc(r,e):Mg(r,e)}var bc=new Float32Array([-0]),Ut=new Uint8Array(bc.buffer);function cd(r,e,t){bc[0]=r,e[t]=Ut[0],e[t+1]=Ut[1],e[t+2]=Ut[2],e[t+3]=Ut[3]}function ld(r,e){return Ut[0]=r[e],Ut[1]=r[e+1],Ut[2]=r[e+2],Ut[3]=r[e+3],bc[0]}var wc=new Float64Array([-0]),_e=new Uint8Array(wc.buffer);function ud(r,e,t){wc[0]=r,e[t]=_e[0],e[t+1]=_e[1],e[t+2]=_e[2],e[t+3]=_e[3],e[t+4]=_e[4],e[t+5]=_e[5],e[t+6]=_e[6],e[t+7]=_e[7]}function fd(r,e){return _e[0]=r[e],_e[1]=r[e+1],_e[2]=r[e+2],_e[3]=r[e+3],_e[4]=r[e+4],_e[5]=r[e+5],_e[6]=r[e+6],_e[7]=r[e+7],wc[0]}var Bg=BigInt(Number.MAX_SAFE_INTEGER),Fg=BigInt(Number.MIN_SAFE_INTEGER),Ke=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return tr;if(e<Bg&&e>Fg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>dd&&(o=0n,++n>dd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return tr;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):tr}},tr=new Ke(0,0);tr.toBigInt=function(){return 0n};tr.zzEncode=tr.zzDecode=function(){return this};tr.length=function(){return 1};var dd=4294967296n;function hd(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 pd(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 xc(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 Qe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ss(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ec=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,Qe(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 Qe(this,4);return ss(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return ss(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);let e=ld(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);let e=fd(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 Qe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return pd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(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 Ke(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Qe(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 Qe(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 Qe(this,8);let e=ss(this.buf,this.pos+=4),t=ss(this.buf,this.pos+=4);return new Ke(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=yc(this.buf,this.pos);return this.pos+=me(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function vc(r){return new Ec(r instanceof Uint8Array?r:r.subarray())}function Re(r,e,t){let n=vc(r);return e.decode(n,void 0,t)}function Sc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var rr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ac(){}var Ic=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ug=Sc();function Kg(r){return globalThis.Buffer!=null?Se(r):Ug(r)}var zn=class{len;head;tail;states;constructor(){this.len=0,this.head=new rr(Ac,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new rr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Cc((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(is,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ke.fromBigInt(e);return this._push(is,t.length(),t)}uint64Number(e){return this._push($r,me(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ke.fromBigInt(e).zzEncode();return this._push(is,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push(is,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_c,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,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(cd,4,e)}double(e){return this._push(ud,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(_c,1,0):this.uint32(t)._push($g,t,e)}string(e){let t=hd(e);return t!==0?this.uint32(t)._push(xc,t,e):this._push(_c,1,0)}fork(){return this.states=new Ic(this),this.head=this.tail=new rr(Ac,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 rr(Ac,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=Kg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function _c(r,e,t){e[t]=r&255}function qg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Cc=class extends rr{next;constructor(e,t){super(qg,e,t),this.next=void 0}};function is(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 Vn(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 $g(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(zn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Vg,e,r),this},zn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zg,e,r),this});function Vg(r,e,t){e.set(r,t)}function zg(r,e,t){r.length<40?xc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Tc(){return new zn}function ke(r,e){let t=Tc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Vr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Vr||(Vr={}));function as(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Lc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return as("enum",Vr.VARINT,t,n)}function Oe(r,e){return as("message",Vr.LENGTH_DELIMITED,r,e)}var nr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Hn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));var Pc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Pc||(Pc={}));(function(r){r.codec=()=>Lc(Pc)})(fe||(fe={}));var at;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(at||(at={}));var Dc;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Dc||(Dc={}));function zr(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return Rt(r)}var Gn={};Me(Gn,{MAX_RSA_KEY_SIZE:()=>Rc,generateRSAKeyPair:()=>qc,jwkToJWKKeyPair:()=>xd,jwkToPkcs1:()=>jg,jwkToPkix:()=>Mc,jwkToRSAPrivateKey:()=>Kc,pkcs1MessageToJwk:()=>Oc,pkcs1MessageToRSAPrivateKey:()=>Bc,pkcs1ToJwk:()=>Gg,pkcs1ToRSAPrivateKey:()=>wd,pkixMessageToJwk:()=>Nc,pkixMessageToRSAPublicKey:()=>Uc,pkixToJwk:()=>Xg,pkixToRSAPublicKey:()=>Fc});var Hr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return bd(this.jwk,t,e,n)}},Wn=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return yd(this.jwk,e,t)}};var Rc=8192,kc=18,Hg=1062,Wg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Gg(r){let e=ht(r);return Oc(e)}function Oc(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function jg(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 C("JWK was missing components");return Ye([Pe(Uint8Array.from([0])),Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url")),Pe(L(r.d,"base64url")),Pe(L(r.p,"base64url")),Pe(L(r.q,"base64url")),Pe(L(r.dp,"base64url")),Pe(L(r.dq,"base64url")),Pe(L(r.qi,"base64url"))]).subarray()}function Xg(r){let e=ht(r,{offset:0});return Nc(e)}function Nc(r){let e=ht(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function Mc(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");return Ye([Wg,Tn(Ye([Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url"))]))]).subarray()}function wd(r){let e=ht(r);return Bc(e)}function Bc(r){let e=Oc(r);return Kc(e)}function Fc(r,e){if(r.byteLength>=Hg)throw new _r("Key size is too large");let t=ht(r,{offset:0});return Uc(t,r,e)}function Uc(r,e,t){let n=Nc(r);if(t==null){let o=Or(at.encode({Type:fe.RSA,Data:e}));t=ot(kc,o)}return new Hr(n,t)}function Kc(r){if(vd(r)>Rc)throw new C("Key size is too large");let e=xd(r),t=Or(at.encode({Type:fe.RSA,Data:Mc(e.publicKey)})),n=ot(kc,t);return new Wn(e.privateKey,new Hr(e.publicKey,n))}async function qc(r){if(r>Rc)throw new C("Key size is too large");let e=await Ed(r),t=Or(at.encode({Type:fe.RSA,Data:Mc(e.publicKey)})),n=ot(kc,t);return new Wn(e.privateKey,new Hr(e.publicKey,n))}function xd(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ed(r,e){let t=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Yg(t,e);return{privateKey:n[0],publicKey:n[1]}}async function yd(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Fe.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 bd(r,e,t,n){let o=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Yg(r,e){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");let t=await Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function vd(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return L(r.n,"base64url").length*8}var cs=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Go(e),V(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),mt(o)}update(e){return kr(this),this.iHash.update(e),this}digestInto(e){kr(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=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()}},$c=(r,e,t)=>new cs(r,e).update(t).digest();$c.create=(r,e)=>new cs(r,e);var Sd=(r,e)=>(r+(r>=0?e:-e)/Ad)/e;function Zg(r,e,t){let[[n,o],[s,i]]=e,a=Sd(i*r,t),c=Sd(-o*r,t),l=r-a*n-c*s,f=-a*o-c*i,u=l<xt,d=f<xt;u&&(l=-l),d&&(f=-f);let h=On(Math.ceil(ec(t)/2))+Wr;if(l<xt||l>=h||f<xt||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function zc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Vc(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return wt(t.lowS,"lowS"),wt(t.prehash,"prehash"),t.format!==void 0&&zc(t.format),t}var Hc=class extends Error{constructor(e=""){super(e)}},Kt={Err:Hc,_tlv:{encode:(r,e)=>{let{Err:t}=Kt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Rn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Rn(o.length/2|128):"";return Rn(r)+s+o+e},decode(r,e){let{Err:t}=Kt,n=0;if(r<0||r>256)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 f of l)i=i<<8|f;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}=Kt;if(r<xt)throw new e("integer: negative integers are not allowed");let t=Rn(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}=Kt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Nr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Kt,o=V(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:f}=n.decode(2,c);if(f.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}=Kt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},xt=BigInt(0),Wr=BigInt(1),Ad=BigInt(2),ls=BigInt(3),Qg=BigInt(4);function _d(r,e={}){let t=Jo("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Mt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=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 l=Cd(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,b,w){let{x:y,y:_}=b.toAffine(),T=n.toBytes(y);if(wt(w,"isCompressed"),w){f();let D=!n.isOdd(_);return Be(Id(D),T)}else return Be(Uint8Array.of(4),T,n.toBytes(_))}function d(R){V(R,void 0,"Point");let{publicKey:b,publicKeyUncompressed:w}=l,y=R.length,_=R[0],T=R.subarray(1);if(y===b&&(_===2||_===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let k=E(D),P;try{P=n.sqrt(k)}catch(oe){let re=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+re)}f();let M=n.isOdd(P);return(_&1)===1!==M&&(P=n.neg(P)),{x:D,y:P}}else if(y===w&&_===4){let D=n.BYTES,k=n.fromBytes(T.subarray(0,D)),P=n.fromBytes(T.subarray(D,D*2));if(!m(k,P))throw new Error("bad point: is not on curve");return{x:k,y:P}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${w}`)}let h=e.toBytes||u,p=e.fromBytes||d;function E(R){let b=n.sqr(R),w=n.mul(b,R);return n.add(n.add(w,n.mul(R,s.a)),s.b)}function m(R,b){let w=n.sqr(b),y=E(R);return n.eql(w,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,ls),Qg),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,A)))throw new Error("bad curve params: a or b");function x(R,b,w=!1){if(!n.isValid(b)||w&&n.is0(b))throw new Error(`bad point coordinate ${R}`);return b}function I(R){if(!(R instanceof v))throw new Error("Weierstrass Point expected")}function O(R){if(!c||!c.basises)throw new Error("no endo");return Zg(R,c.basises,o.ORDER)}let $=Mr((R,b)=>{let{X:w,Y:y,Z:_}=R;if(n.eql(_,n.ONE))return{x:w,y};let T=R.is0();b==null&&(b=T?n.ONE:n.inv(_));let D=n.mul(w,b),k=n.mul(y,b),P=n.mul(_,b);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:D,y:k}}),q=Mr(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:w}=R.toAffine();if(!n.isValid(b)||!n.isValid(w))throw new Error("bad point: x or y not field elements");if(!m(b,w))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(R,b,w,y,_){return w=new v(n.mul(w.X,R),w.Y,w.Z),b=Mn(y,b),w=Mn(_,w),b.add(w)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,w,y){this.X=x("x",b),this.Y=x("y",w,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:w,y}=b||{};if(!b||!n.isValid(w)||!n.isValid(y))throw new Error("invalid affine point");if(b instanceof v)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(y)?v.ZERO:new v(w,y,n.ONE)}static fromBytes(b){let w=v.fromAffine(p(V(b,void 0,"point")));return w.assertValidity(),w}static fromHex(b){return v.fromBytes(yt(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,w=!0){return z.createCache(this,b),w||this.multiply(ls),this}assertValidity(){q(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){I(b);let{X:w,Y:y,Z:_}=this,{X:T,Y:D,Z:k}=b,P=n.eql(n.mul(w,k),n.mul(T,_)),M=n.eql(n.mul(y,k),n.mul(D,_));return P&&M}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:w}=s,y=n.mul(w,ls),{X:_,Y:T,Z:D}=this,k=n.ZERO,P=n.ZERO,M=n.ZERO,K=n.mul(_,_),oe=n.mul(T,T),re=n.mul(D,D),G=n.mul(_,T);return G=n.add(G,G),M=n.mul(_,D),M=n.add(M,M),k=n.mul(b,M),P=n.mul(y,re),P=n.add(k,P),k=n.sub(oe,P),P=n.add(oe,P),P=n.mul(k,P),k=n.mul(G,k),M=n.mul(y,M),re=n.mul(b,re),G=n.sub(K,re),G=n.mul(b,G),G=n.add(G,M),M=n.add(K,K),K=n.add(M,K),K=n.add(K,re),K=n.mul(K,G),P=n.add(P,K),re=n.mul(T,D),re=n.add(re,re),K=n.mul(re,G),k=n.sub(k,K),M=n.mul(re,oe),M=n.add(M,M),M=n.add(M,M),new v(k,P,M)}add(b){I(b);let{X:w,Y:y,Z:_}=this,{X:T,Y:D,Z:k}=b,P=n.ZERO,M=n.ZERO,K=n.ZERO,oe=s.a,re=n.mul(s.b,ls),G=n.mul(w,T),se=n.mul(y,D),be=n.mul(_,k),nt=n.add(w,y),ie=n.add(T,D);nt=n.mul(nt,ie),ie=n.add(G,se),nt=n.sub(nt,ie),ie=n.add(w,_);let ve=n.add(T,k);return ie=n.mul(ie,ve),ve=n.add(G,be),ie=n.sub(ie,ve),ve=n.add(y,_),P=n.add(D,k),ve=n.mul(ve,P),P=n.add(se,be),ve=n.sub(ve,P),K=n.mul(oe,ie),P=n.mul(re,be),K=n.add(P,K),P=n.sub(se,K),K=n.add(se,K),M=n.mul(P,K),se=n.add(G,G),se=n.add(se,G),be=n.mul(oe,be),ie=n.mul(re,ie),se=n.add(se,be),be=n.sub(G,be),be=n.mul(oe,be),ie=n.add(ie,be),G=n.mul(se,ie),M=n.add(M,G),G=n.mul(ve,ie),P=n.mul(nt,P),P=n.sub(P,G),G=n.mul(nt,se),K=n.mul(ve,K),K=n.add(K,G),new v(P,M,K)}subtract(b){return this.add(b.negate())}is0(){return this.equals(v.ZERO)}multiply(b){let{endo:w}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,_,T=D=>z.cached(this,D,k=>Jt(v,k));if(w){let{k1neg:D,k1:k,k2neg:P,k2:M}=O(b),{p:K,f:oe}=T(k),{p:re,f:G}=T(M);_=oe.add(G),y=S(w.beta,K,re,D,P)}else{let{p:D,f:k}=T(b);y=D,_=k}return Jt(v,[y,_])[0]}multiplyUnsafe(b){let{endo:w}=e,y=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===xt||y.is0())return v.ZERO;if(b===Wr)return y;if(z.hasCache(this))return this.multiply(b);if(w){let{k1neg:_,k1:T,k2neg:D,k2:k}=O(b),{p1:P,p2:M}=Yf(v,y,T,k);return S(w.beta,P,M,_,D)}else return z.unsafe(y,b)}toAffine(b){return $(this,b)}isTorsionFree(){let{isTorsionFree:b}=e;return i===Wr?!0:b?b(v,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Wr?this:b?b(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return wt(b,"isCompressed"),this.assertValidity(),h(v,this,b)}toHex(b=!0){return gt(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,z=new Ur(v,e.endo?Math.ceil(B/2):B);return v.BASE.precompute(8),v}function Id(r){return Uint8Array.of(r?2:3)}function Cd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Jg(r,e={}){let{Fn:t}=r,n=e.randomBytes||Rt,o=Object.assign(Cd(r.Fp,t),{seed:oc(t.ORDER)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:E,publicKeyUncompressed:m}=o;try{let g=h.length;return p===!0&&g!==E||p===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return sc(V(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:E,publicKeyUncompressed:m}=o;if(!Gt(h)||"_lengths"in t&&t._lengths||p===E)return;let g=V(h,void 0,"key").length;return g===E||g===m}function f(h,p,E=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(E)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=es(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:u,lengths:o})}function Td(r,e,t={}){Go(e),Mt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Rt,o=t.hmac||((w,y)=>$c(e,w,y)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=Jg(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ad<s.ORDER;function m(w){let y=a>>Wr;return w>y}function g(w,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return y}function A(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(w,y){zc(y);let _=h.signature,T=y==="compact"?_:y==="recovered"?_+1:void 0;return V(w,T)}class I{r;s;recovery;constructor(y,_,T){if(this.r=g("r",y),this.s=g("s",_),T!=null){if(A(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(y,_=p.format){x(y,_);let T;if(_==="der"){let{r:M,s:K}=Kt.toSig(V(y));return new I(M,K)}_==="recovered"&&(T=y[0],_="compact",y=y.subarray(1));let D=h.signature/2,k=y.subarray(0,D),P=y.subarray(D,D*2);return new I(i.fromBytes(k),i.fromBytes(P),T)}static fromHex(y,_){return this.fromBytes(yt(y),_)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new I(this.r,this.s,y)}recoverPublicKey(y){let{r:_,s:T}=this,D=this.assertRecovery(),k=D===2||D===3?_+a:_;if(!s.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=s.toBytes(k),M=r.fromBytes(Be(Id((D&1)===0),P)),K=i.inv(k),oe=$(V(y,void 0,"msgHash")),re=i.create(-oe*K),G=i.create(T*K),se=r.BASE.multiplyUnsafe(re).add(M.multiplyUnsafe(G));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return m(this.s)}toBytes(y=p.format){if(zc(y),y==="der")return yt(Kt.hexFromSig(this));let{r:_,s:T}=this,D=i.toBytes(_),k=i.toBytes(T);return y==="recovered"?(A(),Be(Uint8Array.of(this.assertRecovery()),D,k)):Be(D,k)}toHex(y){return gt(this.toBytes(y))}}let O=t.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let _=Nr(y),T=y.length*8-c;return T>0?_>>BigInt(T):_},$=t.bits2int_modN||function(y){return i.create(O(y))},q=On(c);function S(w){return kn("num < 2^"+c,w,xt,q),i.toBytes(w)}function v(w,y){return V(w,void 0,"message"),y?V(e(w),void 0,"prehashed message"):w}function B(w,y,_){let{lowS:T,prehash:D,extraEntropy:k}=Vc(_,p);w=v(w,D);let P=$(w),M=i.fromBytes(y);if(!i.isValidNot0(M))throw new Error("invalid private key");let K=[S(M),S(P)];if(k!=null&&k!==!1){let se=k===!0?n(h.secretKey):k;K.push(V(se,void 0,"extraEntropy"))}let oe=Be(...K),re=P;function G(se){let be=O(se);if(!i.isValidNot0(be))return;let nt=i.inv(be),ie=r.BASE.multiply(be).toAffine(),ve=i.create(ie.x);if(ve===xt)return;let Po=i.create(nt*i.create(re+ve*M));if(Po===xt)return;let Pu=(ie.x===ve?0:2)|Number(ie.y&Wr),Du=Po;return T&&m(Po)&&(Du=i.neg(Po),Pu^=1),new I(ve,Du,E?void 0:Pu)}return{seed:oe,k2sig:G}}function z(w,y,_={}){let{seed:T,k2sig:D}=B(w,y,_);return kf(e.outputLen,i.BYTES,o)(T,D).toBytes(_.format)}function R(w,y,_,T={}){let{lowS:D,prehash:k,format:P}=Vc(T,p);if(_=V(_,void 0,"publicKey"),y=v(y,k),!Gt(w)){let M=w instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}x(w,P);try{let M=I.fromBytes(w,P),K=r.fromBytes(_);if(D&&M.hasHighS())return!1;let{r:oe,s:re}=M,G=$(y),se=i.inv(re),be=i.create(G*se),nt=i.create(oe*se),ie=r.BASE.multiplyUnsafe(be).add(K.multiplyUnsafe(nt));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function b(w,y,_={}){let{prehash:T}=Vc(_,p);return y=v(y,T),I.fromBytes(w,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:z,verify:R,recoverPublicKey:b,Signature:I,hash:e})}var Gc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},e0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ld=BigInt(2);function t0(r){let e=Gc.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,f=l*l*r%e,u=ne(f,t,e)*f%e,d=ne(u,t,e)*f%e,h=ne(d,Ld,e)*l%e,p=ne(h,o,e)*h%e,E=ne(p,s,e)*p%e,m=ne(E,a,e)*E%e,g=ne(m,c,e)*m%e,A=ne(g,a,e)*E%e,x=ne(A,t,e)*f%e,I=ne(x,i,e)*p%e,O=ne(I,n,e)*l%e,$=ne(O,Ld,e);if(!Wc.eql(Wc.sqr($),r))throw new Error("Cannot find square root");return $}var Wc=Br(Gc.p,{sqrt:t0}),r0=_d(Gc,{Fp:Wc,endo:e0}),Je=Td(r0,Or);function Pd(r,e,t){let n=Rr.digest(e instanceof Uint8Array?e:e.subarray());if(qr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Je.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Fn(String(o))});try{return Je.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Fn(String(o))}}function Dd(r,e,t,n){let o=Rr.digest(t instanceof Uint8Array?t:t.subarray());if(qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Je.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Un(String(s))});try{return n?.signal?.throwIfAborted(),Je.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Un(String(s))}}var jn=class{type="secp256k1";raw;_key;constructor(e){this._key=Od(e),this.raw=Rd(this._key)}toMultihash(){return je.digest(He(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return Dd(this._key,t,e,n)}},us=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=kd(e),this.publicKey=new jn(t??Nd(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return Pd(this.raw,e,t)}};function jc(r){return new jn(r)}async function Md(){let r=n0();return new us(r)}function Rd(r){return Je.Point.fromBytes(r).toBytes()}function kd(r){try{return Je.getPublicKey(r,!0),r}catch(e){throw new yn(String(e))}}function Od(r){try{return Je.Point.fromBytes(r),r}catch(e){throw new _r(String(e))}}function Nd(r){try{return Je.getPublicKey(r,!0)}catch(e){throw new yn(String(e))}}function n0(){return Je.utils.randomSecretKey()}async function Bd(r,e){if(r==="Ed25519")return ad();if(r==="secp256k1")return Md();if(r==="RSA")return qc(o0(e));if(r==="ECDSA")return mf(s0(e));throw new Tt}function Gr(r,e){let{Type:t,Data:n}=at.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return Fc(o,e);case fe.Ed25519:return dc(o);case fe.secp256k1:return jc(o);case fe.ECDSA:return $a(o);default:throw new Tt}}function Fd(r){let{Type:e,Data:t}=at.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return dc(n);case fe.secp256k1:return jc(n);case fe.ECDSA:return $a(n);default:throw new Tt}}function He(r){return at.encode({Type:fe[r.type],Data:r.raw})}function o0(r){return r==null?2048:parseInt(r,10)}function s0(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 C("Unsupported curve, should be P-256, P-384 or P-521")}var Ud=Symbol.for("nodejs.util.inspect.custom"),i0=114,Xn=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()})`}[Ko]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(i0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ud](){return`PeerId(${this.toString()})`}},Yn=class extends Xn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Zn=class extends Xn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Qn=class extends Xn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},a0=2336,Jn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=je.digest(L(this.url))}[Ud](){return`PeerId(${this.url})`}[Ko]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(a0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var c0=114,Kd=2336;function ct(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=dt(J.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return eo(le.parse(r));if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=dt(e.decode(r))}return jr(t)}function Xc(r){if(r.type==="Ed25519")return new Zn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Qn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yn({multihash:r.toCID().multihash,publicKey:r});throw new Tt}function qd(r){return Xc(r.publicKey)}function jr(r){if(u0(r))return new Yn({multihash:r});if(l0(r))try{let e=Fd(r);if(e.type==="Ed25519")return new Zn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Qn({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new Jn(new URL(t))}throw new ko("Supplied PeerID Multihash is invalid")}function eo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==c0&&r.code!==Kd)throw new Ro("Supplied PeerID CID is invalid");if(r.code===Kd){let e=U(r.multihash.digest);return new Jn(new URL(e))}return jr(r.multihash)}function l0(r){return r.code===je.code}function u0(r){return r.code===Rr.code}async function $d(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return r}function f0(r,e){if(typeof r=="string")return d0(r);if(typeof r=="number")return m0(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var fs=f0;function d0(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 h0(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 p0(r){let e=Math.abs(r);return e>=315576e5?or(r,e,315576e5,"year"):e>=26298e5?or(r,e,26298e5,"month"):e>=6048e5?or(r,e,6048e5,"week"):e>=864e5?or(r,e,864e5,"day"):e>=36e5?or(r,e,36e5,"hour"):e>=6e4?or(r,e,6e4,"minute"):e>=1e3?or(r,e,1e3,"second"):`${r} ms`}function m0(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?p0(r):h0(r)}function or(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Yc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=fs,t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let d=0;d<f.length;d++)u=(u<<5)-u+f.charCodeAt(d),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f,u){let d,h=null,p,E;function m(...g){if(!m.enabled)return;let A=m,x=Number(new Date),I=x-(d||x);A.diff=I,A.prev=d,A.curr=x,d=x,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let O=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(q,S)=>{if(q==="%%")return"%";O++;let v=t.formatters[S];if(typeof v=="function"){let B=g[O];q=v.call(A,B),g.splice(O,1),O--}return q}),t.formatArgs.call(A,g),u?.onLog!=null&&u.onLog(...g),(A.log||t.log).apply(A,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,E=t.enabled(f)),E),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,u){let d=t(this.namespace+(typeof u>"u"?":":u)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(u=0;u<h;u++)d[u]&&(f=d[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let u,d;for(u=0,d=t.skips.length;u<d;u++)if(t.skips[u].test(f))return!1;for(u=0,d=t.names.length;u<d;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function 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 ds=v0(),g0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function y0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.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 b0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+fs(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 w0=console.debug??console.log??(()=>{});function x0(r){try{r?ds?.setItem("debug",r):ds?.removeItem("debug")}catch{}}function E0(){let r;try{r=ds?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function v0(){try{return localStorage}catch{}}function S0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Vd=Yc({formatArgs:b0,save:x0,load:E0,useColors:y0,setupFormatters:S0,colors:g0,storage:ds,log:w0});var Ue=Vd;Ue.formatters.b=r=>r==null?"undefined":J.baseEncode(r);Ue.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);Ue.formatters.m=r=>r==null?"undefined":La.baseEncode(r);Ue.formatters.p=r=>r==null?"undefined":r.toString();Ue.formatters.c=r=>r==null?"undefined":r.toString();Ue.formatters.k=r=>r==null?"undefined":r.toString();Ue.formatters.a=r=>r==null?"undefined":r.toString();function zd(r,e=""){let t=Hd(r.message),n=Hd(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 L0(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Xd(r,e=""){if(L0(r)){let t=Gd(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
- ${e}${r.errors.map(n=>`${Xd(n,`${e}`)}`).join(`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function A0(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Wd(r,e=""){if(A0(r)){let t=zd(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
+ ${e}${r.errors.map(n=>`${Wd(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return Gd(r,e)}Ue.formatters.e=r=>r==null?"undefined":Xd(r);function P0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function ds(r){return{forComponent(e){return Zd(e,r)}}}function Zd(r,e){let t=P0(`${r}:trace`);return Ue.enabled(`${r}:trace`)&&Ue.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ue(`${r}:trace`,e)),Object.assign(Ue(r,e),{error:Ue(`${r}:error`,e),trace:t,newScope:n=>Zd(`${r}:${n}`,e)})}function Yd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function sr(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 hs(r){let e=dt(J.decode(`z${r}`));return Yr(e)}var We=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 sr(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 sr(this.map.values(),e=>e.key)}values(){return sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ir=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 sr(this.set.entries(),e=>{let t=hs(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=hs(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return sr(this.set.values(),e=>hs(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 Zc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},jd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Qd=new globalThis.TextEncoder;function D0(r,e){let t=Zc[e],n=jd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function R0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Zc[e],o=jd[e],s=r;for(;s.length>0;){let i=Qd.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 jc(r,{size:e=32,utf8Buffer:t}={}){if(!Zc[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 R0(r,e,t);r=Qd.encode(r)}return D0(r,e)}var to={hash:r=>Number(jc(r,{size:32})),hashV:(r,e)=>k0(to.hash(r,e))};function k0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var Qc=64,et=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Qc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(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?j(this.fp,e.fp):!1}};function ar(r,e){return Math.floor(Math.random()*(e-r))+r}var cr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof et))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof et))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 et))throw new TypeError("Invalid Fingerprint");let t=ar(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof et))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var O0=500,ro=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??to,this.seed=e.seed??ar(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new et(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 cr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new cr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[ar(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize));for(let a=0;a<O0;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 cr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new et(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new et(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}},N0={1:.5,2:.84,4:.95,8:.98};function M0(r=.001){return r>.002?2:r>1e-5?4:8}function Jd(r,e=.001){let t=M0(e),n=N0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Qc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ps=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??to,this.seed=e.seed??ar(0,Math.pow(2,10)),this.filterSeries=[new ro({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ro({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function no(r,e=.001,t){return new ps({...Jd(r,e),...t??{}})}function H(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 C(`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 ms=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 f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,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 eh=45,B0=15,Xr=new ms;function gs(r){if(!(r.length>B0))return Xr.new(r).parseWith(()=>Xr.readIPv4Addr())}function ys(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>eh))return Xr.new(r).parseWith(()=>Xr.readIPv6Addr())}function Zr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>eh)return;let t=Xr.new(r).parseWith(()=>Xr.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 th(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 rh(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 Jc(r){switch(r.length){case lr:return r.join(".");case ur:{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 nh(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 oh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var lr=4,ur=16,fS=parseInt("0xFFFF",16),F0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function oo(r,e){e.length===ur&&r.length===lr&&th(e,0,11)&&(e=e.slice(12)),e.length===lr&&r.length===ur&&rh(r,F0,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 sh(r,e){if(typeof e=="string"&&(e=Zr(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 el(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=lr,o=gs(e);if(o==null&&(n=ur,o=ys(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=tl(s,8*n);return{network:oo(o,i),mask:i}}function tl(r,e){if(e!==8*lr&&e!==8*ur)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 jr=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=el(e));else{let n=Zr(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=Zr(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=tl(o,8*n.length);this.network=oo(n,this.mask)}}contains(e){return sh({network:this.network,mask:this.mask},e)}toString(){let e=nh(this.mask),t=e!==-1?String(e):oh(this.mask);return Jc(this.network)+"/"+t}};function ih(r){try{let e=H(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 ah(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function so(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return ah(e.host);default:return!1}}catch{return!1}}function xe(r){try{return H(r),!0}catch{return!1}}function tt(r){return!!gs(r)}function bs(r){return!!ys(r)}var lh=ca(ch(),1),U0=["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"],K0=U0.map(r=>new lh.Netmask(r));function rl(r){for(let e of K0)if(e.contains(r))return!0;return!1}function q0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function $0(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 rl(o)}function V0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function z0(r){let e=r.split(":"),t=e[e.length-1];return rl(t)}function H0(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 Qr(r){if(tt(r))return rl(r);if(q0(r))return $0(r);if(V0(r))return z0(r);if(bs(r))return H0(r)}function Et(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return Qr(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ge(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ws=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}},Jr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ws(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 ws(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var nl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function en(r={}){return W0(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 W0(r,e){e=e??{};let t=e.onEnd,n=new Jr,o,s,i,a=ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=A=>{s=null,n.push(A);try{m(r(n))}catch(x){g(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ge()})}},l=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Jr,s!=null?s({error:m}):(n.push({error:m}),o)),u=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?f(m):l({done:!0})),h=()=>(n=new Jr,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:u,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let A,x;g!=null&&(A=new Promise((I,O)=>{x=()=>{O(new nl)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,A])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(m){return E.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(m){return E.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:m=>E.onEmpty(m)},o}var ol=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},sl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},uh=r=>globalThis.DOMException===void 0?new sl(r):new DOMException(r),fh=r=>{let e=r.reason===void 0?uh("This operation was aborted."):r.reason;return e instanceof Error?e:uh(e)};function il(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(fh(h)),a=()=>{u(fh(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new ol;i=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var G0=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 Y0(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:f}=G0(r),u=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(E){n(),i(E);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);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=il(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function rt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Y0(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ao(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 xs=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}},Es=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},fr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function X0(r){return r.reason}async function qe(r,e,t){if(e==null)return r;let n=t?.translateError??X0;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 vs=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Z0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ss=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Z0(),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 Ge),this.cleanup())}async join(e={}){let t=new vs(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 qe(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tn=class extends Le{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=ao(this.emitEmpty.bind(this),1),this.emitIdle=ao(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 Es;let n=new Ss(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){this.size!==0&&await rt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await rt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await rt(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=en({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 Ge("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 vt(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 rn=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 j0=1.2,Q0=2,J0=5e3,ey=6e4,ty=5e3,As=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??ty;this.success=new rn(t),this.failure=new rn(t),this.next=new rn(t),this.failureMultiplier=e.failureMultiplier??Q0,this.timeoutMultiplier=e.timeoutMultiplier??j0,this.minTimeout=e.minTimeout??J0,this.maxTimeout=e.maxTimeout??ey,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=vt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){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 Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},St=class extends Error{static name="ValidationError";name="ValidationError"},_s=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Is=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function cl(r){return e=>U(e,r)}function ll(r){return e=>L(e,r)}function nn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function dr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function dh(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=L(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=dr(n);return Xe([t,o],t.length+o.length)}function hh(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ze.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=dr(n);return Xe([t,o],t.length+o.length)}function ul(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=U(e,"base32"),o=nn(t);return`${n}:${o}`}var fl=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 Ee("Invalid byte value in IP address");e[n]=o}),e},ph=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=tt(t[n]),i;s&&(i=fl(t[n]),t[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,U(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 Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},mh=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},gh=function(r){if(r.byteLength!==16)throw new Ee("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 Ee(`Invalid IPv6 address "${t}"`)}};function yh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var al=Object.values(_n).map(r=>r.decoder),ry=(function(){let r=al[0].or(al[1]);return al.slice(2).forEach(e=>r=r.or(e)),r})();function bh(r){return ry.decode(r)}function wh(r){return e=>r.encoder.encode(e)}function ny(r){if(parseInt(r).toString()!==r)throw new St("Value must be an integer")}function oy(r){if(r<0)throw new St("Value must be a positive integer, or zero")}function sy(r){return e=>{if(e>r)throw new St(`Value must be smaller than or equal to ${r}`)}}function iy(...r){return e=>{for(let t of r)t(e)}}var co=iy(ny,oy,sy(65535));var ye=-1,dl=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 Is(`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)}))}},At=new dl,Ey=[{code:4,name:"ip4",size:32,valueToBytes:fl,bytesToValue:mh,validate:r=>{if(!tt(r))throw new St(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:dr,bytesToValue:nn,validate:co},{code:273,name:"udp",size:16,valueToBytes:dr,bytesToValue:nn,validate:co},{code:33,name:"dccp",size:16,valueToBytes:dr,bytesToValue:nn,validate:co},{code:41,name:"ip6",size:128,valueToBytes:ph,bytesToValue:gh,stringToValue:yh,validate:r=>{if(!bs(r))throw new St(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:cl("base10"),valueToBytes:ll("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:dr,bytesToValue:nn,validate:co},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:cl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ll("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ul,valueToBytes:dh},{code:445,name:"onion3",size:296,bytesToValue:ul,valueToBytes:hh},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:wh(La),valueToBytes:bh},{code:480,name:"http"},{code:481,name:"http-path",size:ye,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:ye}];Ey.forEach(r=>{At.addProtocol(r)});function xh(r){let e=[],t=0;for(;t<r.length;){let n=er(r,t),o=At.getProtocol(n),s=me(n),i=vy(o,r,t+s),a=0;i>0&&o.size===ye&&(a=me(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+s+a,u=r.subarray(f,f+i);l.value=o.bytesToValue?.(u)??U(u)}e.push(l),t+=c}return e}function Eh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=At.getProtocol(n.code),s=me(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??L(n.value),a=i.byteLength,o.size===ye&&(c=me(a)));let l=new Uint8Array(s+c+a),f=0;$r(n.code,l,f),f+=s,i!=null&&(o.size===ye&&($r(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Xe(t,e)}function vh(r){if(r.charAt(0)!=="/")throw new Ee('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=At.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 Ee(`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 Ee(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function Sh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=At.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function vy(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:er(e,t)}var Sy=Symbol.for("nodejs.util.inspect.custom"),Il=Symbol.for("@multiformats/multiaddr");function Ay(r){if(r==null&&(r="/"),$t(r))return r.getComponents();if(r instanceof Uint8Array)return xh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),vh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ds=class r{[Il]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=Ay(e),t.validate!==!1&&_y(this)}get bytes(){return this.#n==null&&(this.#n=Eh(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=Sh(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 _s(`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 j(this.bytes,e.bytes)}[Sy](){return`Multiaddr(${this.toString()})`}};function _y(r){r.getComponents().forEach(e=>{let t=At.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function $t(r){return!!r?.[Il]}function X(r){return new Ds(r)}var Cl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ge(),this.haveNext=ge()}[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=ge(),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=ge(),await qe(this.readNext.promise,t?.signal,t)}};function Ah(){return new Cl}function Iy(r){return r[Symbol.asyncIterator]!=null}async function Cy(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*Ty(r){let e=new AbortController,t=Ah();Cy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Ly(r){for(let e of r)yield*e}function Py(...r){let e=[];for(let t of r)Iy(t)||e.push(t);return e.length===r.length?Ly(e):Ty(r)}var un=Py;var Dy=4194304,Rs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ll=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Dl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ry(r){return typeof r?.closeRead=="function"}function ky(r){return typeof r?.close=="function"}function Tl(r){return Ry(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:ky(r)?r.status!=="open":!1}function Oy(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Rl(r,e){let t=e?.maxBufferSize??Dy,n=new Q,o,s=!1;if(!Oy(r))throw new C("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(s===!0)throw new Rs("Stream was unwrapped");if(Tl(r)){if(f?.bytes==null)return null;if(n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new fr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await qe(o.promise,f?.signal),Tl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Tl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new fr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(s===!0)throw new Rs("Stream was unwrapped");r.send(f)||await rt(r,"drain",{signal:u?.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 ks(r,e={}){let t=Rl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??er,o=e?.lengthEncoder??Ft;return{async read(i){let a=-1,c=new Q;for(;;){let f=await t.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Ll("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Dl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Pl(`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 fr(`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 fr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Os=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ns=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},lo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ms(r){return r[Symbol.asyncIterator]!=null}function _h(r,e){if(r.byteLength>e)throw new fn("Message length too long")}var Fs=r=>{let e=me(r),t=Se(e);return Ft(r,t),Fs.bytes=e,t};Fs.bytes=0;function Us(r,e){e=e??{};let t=e.lengthEncoder??Fs,n=e?.maxDataLength??4194304;function*o(s){_h(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ms(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Us.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Fs,n=e?.maxDataLength??4194304;return _h(r,n),new Q(t(r.byteLength),r)};var mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var Ol=r=>{let e=er(r);return Ol.bytes=me(e),e};Ol.bytes=0;function kl(r,e){let t=new Q,n=mr.LENGTH,o=-1,s=e?.lengthDecoder??Ol,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(t),o<0)throw new Os("Invalid message length");if(o>a)throw new fn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Ns("Message length length too long");break}throw l}if(n===mr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=mr.LENGTH}}}return Ms(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lo("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lo("Unexpected end of input")})()}kl.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 kl(n,{...e??{},onLength:s=>{t=s}})};var Ks=class extends tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qs=class extends tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var $s=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 Nl}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 xs("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)}},Nl=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 Ml=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ie(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ml({name:e,metrics:t}):n=new Map,n}var Bl=class extends We{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 Fl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Bl({name:e,metrics:t}):n=new We,n}var uo;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(uo||(uo={}));var Vs=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var dn=class r{static createFromProtobuf=e=>{let t=uo.decode(e),n=Gr(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=Ih(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 Vs("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=uo.encode({publicKey:He(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:j(this.marshal(),e.marshal())}async validate(e,t){let n=Ih(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Ih=(r,e,t)=>{let n=L(r),o=Ft(n.byteLength),s=Ft(e.length),i=Ft(t.length);return new Q(o,n,s,e,i,t)};var Ch="libp2p-peer-record",Th=Uint8Array.from([3,1]);var fo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Oe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>ke(s,n.codec()),n.decode=(s,i)=>Re(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new nr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>ke(n,r.codec()),r.decode=(n,o)=>Re(n,r.codec(),o)})(fo||(fo={}));function Lh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var gr=class r{static createFromProtobuf=e=>{let t=fo.decode(e),n=Yr(dt(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Ch;static CODEC=Th;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=fo.encode({peerId:this.peerId.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||!Lh(this.multiaddrs,e.multiaddrs))}};function My(r){return r[Symbol.asyncIterator]!=null}function By(r){if(My(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var ho=By;var $e=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function zs(r,e,t,n){let o=new $e(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(){Kl(t,"abort",u),Kl(r,e,l),Kl(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=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.`))},u=()=>{c(),a(o)};Ul(t,"abort",u),Ul(r,e,l),Ul(r,s,f)})}function Ul(r,e,t){r!=null&&(Ph(r)?r.addEventListener(e,t):r.addListener(e,t))}function Kl(r,e,t){r!=null&&(Ph(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ph(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Hs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ws=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 $e)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Gs=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Fy(),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 $e),this.cleanup())}async join(e={}){let t=new Ws(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 qe(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 ql(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 po=class extends Le{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=ql(this.emitEmpty.bind(this),1),this.emitIdle=ql(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 Hs;let n=new Gs(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 $e)}),this.clear()}async onEmpty(e){this.size!==0&&await zs(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await zs(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await zs(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=en({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 $e("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 Ys="lock:worker:request-read",Xs="lock:worker:abort-read-request",Zs="lock:worker:release-read",js="lock:master:grant-read",Qs="lock:master:error-read",Js="lock:worker:request-write",ei="lock:worker:abort-write-request",ti="lock:worker:release-write",ri="lock:master:grant-write",ni="lock:master:error-write",oi="lock:worker:finalize",si="mortice",Dh={singleProcess:!1};var $l=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===oi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Rh=(r=10)=>Math.random().toString().substring(2,r+2);var ii=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(si)}readLock(e){return this.sendRequest(Ys,Xs,js,Qs,Zs,e)}writeLock(e){return this.sendRequest(Js,ei,ri,ni,ti,e)}finalize(){this.channel.postMessage({type:oi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Rh();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);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",u)})}};var kh=r=>{if(r=Object.assign({},Dh,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(si),n=new Le;return t.addEventListener("message",$l(n,t,"requestReadLock","abortReadLockRequest",Ys,Xs,Qs,Zs,js)),t.addEventListener("message",$l(n,t,"requestWriteLock","abortWriteLockRequest",Js,ei,ni,ti,ri)),n}return new ii(r.name)};var yr=new Map,mo;function Oh(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Uy(r){if(mo==null&&(mo=kh(r),!Oh(mo))){let e=mo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=yr.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=yr.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=yr.get(n);o?.finalize()})}return mo}async function Vl(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new $e)};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 Nh=(r,e)=>{let t=yr.get(r);if(t!=null)return t;let n=Uy(e);if(Oh(n))return t=n,yr.set(r,t),t;let o=new po({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Vl(s,i);s=new po({concurrency:e.concurrency,autoStart:!1});let a=s,c=Vl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Vl(o,i)},finalize:()=>{yr.delete(r)},queue:o},yr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Ky={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function zl(r){let e=Object.assign({},Ky,r);return Nh(e.name,e)}var _t;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Re(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),ci.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=ci.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Re(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ai.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new nr('Decode error - map field "addresses" had too many elements');a.addresses.push(ai.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new nr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Hn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Hn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ke(o,r.codec()),r.decode=(o,s)=>Re(o,r.codec(),s)})(_t||(_t={}));var ai;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(ai||(ai={}));var ci;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(ci||(ci={}));function qy(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Gr(e.publicKey,t);return Yc(n)}function Mh(r,e,t){let n=_t.decode(e);return hn(r,n,t)}function hn(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:qy(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 Bh(r,e){return $y(r.addresses,e.addresses)&&Vy(r.protocols,e.protocols)&&zy(r.publicKey,e.publicKey)&&Hy(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Wy(r.metadata,e.metadata)&&Gy(r.tags,e.tags)}function $y(r,e){return Uh(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!j(t.multiaddr,n.multiaddr)))}function Vy(r,e){return Uh(r,e,(t,n)=>t===n)}function zy(r,e){return Fh(r,e)}function Hy(r,e){return Fh(r,e)}function Wy(r,e){return Kh(r,e,(t,n)=>j(t,n))}function Gy(r,e){return Kh(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Fh(r,e){return r==null&&e==null?!0:r!=null&&e!=null?j(r,e):!1}function Uh(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 Kh(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 It="/",qh=new TextEncoder().encode(It),li=qh[0],br=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==li)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(It))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=qh),this._buf[0]!==li){let e=new Uint8Array(this._buf.byteLength+1);e.fill(li,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===li;)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(It).slice(1)}type(){return Yy(this.baseNamespace())}name(){return Xy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(It)||(e+=It),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(It):new r(e.slice(0,-1).join(It))}child(e){return this.toString()===It?e:e.toString()===It?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(),...Zy(e.map(t=>t.namespaces()))])}};function Yy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Xy(r){let e=r.split(":");return e[e.length-1]}function Zy(r){return[].concat(...r)}var Hl="/peers/";function go(r){if(!Lt(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new br(`${Hl}${e}`)}async function $h(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)),!$t(i.multiaddr))throw new C("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 fi(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new C("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=ui(d,{validate:Vh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ui(d,{validate:zh,map:Hh})}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,p]of d)p==null?a.delete(h):a.set(h,p);a=ui([...a.entries()],{validate:Vh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,E]of d)E==null?h.delete(p):h.set(p,E);c=ui([...h.entries()],{validate:zh,map:Hh})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=He(o.id.publicKey):e.publicKey!=null?f=He(e.publicKey):r.publicKey!=null&&(f=He(r.publicKey));let u={addresses:await $h(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:f,peerRecordEnvelope:l};return u.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>j(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete u.publicKey,u}function ui(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 Vh(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function zh(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function Hh(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 Wh(r){let e=r.toString().split("/")[2],t=le.parse(e,ze);return eo(t)}function Wl(r,e,t){let n=Wh(r);return Mh(n,e,t)}function jy(r,e){return{prefix:Hl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Wl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Wl(n.key,n.value,e),Wl(o.key,o.value,e)))}}var di=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=Fl({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:zl({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(go(e),t)}async load(e,t){let n=go(e),o=await this.datastore.get(n,t),s=_t.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Ht;return hn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await fi(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 fi(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 fi(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(jy(e??{},this.maxAddressAge),e)){let o=Wh(t);if(o.equals(this.peerId))continue;let s=_t.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield hn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=go(e),o=await this.datastore.get(n,t),s=_t.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Ht;return{peerPB:s,peer:hn(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=_t.encode(t);return await this.datastore.put(go(e),s,o),{peer:hn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Bh(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 Gl=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 di(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 ho(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=Lt(t)?t:Lt(t?.expectedPeer)?t.expectedPeer:void 0,s=Lt(t)||t===void 0?n:t,i=await dn.openAndCertify(e,gr.DOMAIN,s),a=eo(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=gr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(f){if(f.name!=="NotFoundError")throw f}if(l?.peerRecordEnvelope!=null){let f=dn.createFromProtobuf(l.peerRecordEnvelope),u=gr.createFromProtobuf(f.payload);if(u.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(f=>({isCertified:!0,multiaddr:f}))},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 Gh(r,e={}){return new Gl(r,e)}var hi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Qy(r){return r[Symbol.asyncIterator]!=null}function Jy(r){if(Qy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yl=Jy;function eb(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 Yh=eb;function tb(r){return r[Symbol.asyncIterator]!=null}function rb(r,e){let t=0;if(tb(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Yh(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 wr=rb;function nb(r){return r[Symbol.asyncIterator]!=null}function ob(r,e){return nb(r)?(async function*(){yield*(await ho(r)).sort(e)})():(function*(){yield*ho(r).sort(e)})()}var Xl=ob;function sb(r){return r[Symbol.asyncIterator]!=null}function ib(r,e){return sb(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 Zl=ib;var pi=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 Yl(this.putMany(e,n)),e=[],await Yl(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=wr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=wr(n,()=>o++>=s)}return e.limit!=null&&(n=Zl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=wr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=wr(n,()=>s++>=o)}return e.limit!=null&&(n=Zl(n,e.limit)),n}};var mi=class extends pi{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 hi;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 br(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new br(n),t?.signal?.throwIfAborted()}};var ee=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)}}),Xh=r=>({match:e=>r.match(e)===!1?e:!1}),W=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ce=(...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}}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function te(...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 ab=N(421),Zh=te(ab),yi=N(54),bi=N(55),wi=N(56),Ql=N(53),_6=te(yi,W(N(421))),I6=te(bi,W(N(421))),C6=te(wi,W(N(421))),T6=te(Ce(Ql,wi,yi,bi),W(N(421))),jh=Z(N(4),W(N(43))),Qh=Z(W(N(42)),N(41),W(N(43))),Jl=Ce(jh,Qh),xr=Ce(Jl,Ql,yi,bi,wi),L6=te(Ce(Jl,Z(Ce(Ql,wi,yi,bi),W(N(421))))),eu=te(jh),tu=te(Qh),P6=te(Jl),ru=Z(xr,N(6)),yo=Z(xr,N(273)),bo=te(Z(ru,W(N(421)))),D6=te(yo),nu=Z(yo,ee(460),W(N(421))),xi=Z(yo,ee(461),W(N(421))),cb=Ce(nu,xi),R6=te(nu),Jh=te(xi),jl=Ce(xr,ru,yo,nu,xi),ep=Ce(Z(jl,ee(477),W(N(421)))),Er=te(ep),tp=Ce(Z(jl,ee(478),W(N(421))),Z(jl,ee(448),W(N(449)),ee(477),W(N(421)))),wo=te(tp),rp=Z(yo,ee(280),W(N(466)),W(N(466)),W(N(421))),ou=te(rp),np=Z(xi,ee(465),W(N(466)),W(N(466)),W(N(421))),su=te(np),gi=Ce(ep,tp,Z(ru,W(N(421))),Z(cb,W(N(421))),Z(xr,W(N(421))),rp,np,N(421)),k6=te(gi),lb=Z(W(gi),ee(290),Xh(ee(281)),W(N(421))),vr=te(lb),ub=Ce(Z(gi,ee(290),ee(281),W(N(421))),Z(gi,ee(281),W(N(421))),Z(ee(281),W(N(421)))),iu=te(ub),fb=Ce(Z(xr,N(6),ee(480),W(N(421))),Z(xr,ee(480),W(N(421)))),O6=te(fb),db=Z(xr,Ce(Z(N(6,"443"),ee(480)),Z(N(6),ee(443)),Z(N(6),ee(448),ee(480)),Z(ee(448),ee(480)),ee(448),ee(443)),W(N(421))),N6=te(db),hb=Ce(Z(N(777),W(N(421)))),M6=te(hb),pb=Ce(Z(N(400),W(N(421)))),B6=te(pb);var op=864e13;var Ei=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ie({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=H(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=Qr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?op-Date.now():0,lastVerified:o?op-Date.now():void 0})})}remove(e){let t=H(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(!xe(o))continue;let s=H(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=H(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=H(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 vi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ie({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=H(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:tt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=H(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(!xe(n))continue;let o=H(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(!xe(e))return!1;let n=H(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(!xe(e))return!1;let n=H(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 mb={maxObservedAddresses:10},Si=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??mb.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&&(Et(e)||ih(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 gb={maxObservedAddresses:10},Ai=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??gb.maxObservedAddresses}get(e,t){if(Et(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:!xe(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(!xe(e))return e.toString();let t=H(e);return`${t.host}-${t.port}-${t.protocol}`}};var sp=6e4,ip={maxObservedAddresses:10,addressVerificationTTL:sp*10,addressVerificationRetry:sp*5},yb=r=>r;function au(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ct(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var _i=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 Si(e,t),this.dnsMappings=new Ei(e,t),this.ipMappings=new vi(e,t),this.transportAddresses=new Ai(e,t),this.announceFilter=t.announceFilter??yb,this.observedAddressFilter=no(1024),this.addressVerificationTTL=t.addressVerificationTTL??ip.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??ip.addressVerificationRetry,this._updatePeerStoreAddresses=ao(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=H(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=au(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=au(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=au(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${tt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${tt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=H(e);if(t.type!=="ip4"||Qr(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Er.exactMatch(s)||wo.exactMatch(s),s=>bo.exactMatch(s),s=>Jh.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(f=>H(f).type==="ip4"&&s(f)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!so(l)).pop();if(a==null)continue;let c=H(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 ap;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(ap||(ap={}));var Ii=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ci=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},pn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},xo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Ti=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Li=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Pi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Eo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Di=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Ri=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ki=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Oi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ni=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Vt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Sr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Mi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Bi=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var cu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=ds())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ko(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")}},bb=["metrics","connectionProtector","dns"],wb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function cp(r={}){let e=new cu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!wb.includes(o)){let i=e.components[o];if(i==null&&!bb.includes(o))throw new Ii(`${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 lp(r){let e={};for(let t of Object.values(r.components))for(let n of xb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Eb(t))if(e[n]!==!0)throw new Ci(`Service "${vb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function xb(r){return Array.isArray(r?.[xn])?r[xn]:[]}function Eb(r){return Array.isArray(r?.[ha])?r[ha]:[]}function vb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function up(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Er.matches(e)?!0:Et(e)),r}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Fi(r){if(Lt(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:ct(n),e.forEach(o=>{if(!$t(o))throw new Ct("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ct(s);if(t?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Zh.exactMatch(n)),{peerId:t,multiaddrs:e}}var Sb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function fp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Sb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function vo(r){let e=H(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new C(`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 C(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new jr(e.host,t)}function lu(r){return!vr.exactMatch(r)}function Ui(r,e,t){if(r==null||e==null)return;let n=e.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=>lu(s)))return n}var Ki=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>vo(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 We;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let f=await this.peerStore.get(l);o.set(l,[...f.tags.values()].reduce((u,d)=>u+d.value,0))}catch(f){f.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",f)}}}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(f=>{if(xe(c.remoteAddr)){let u=H(c.remoteAddr);return f.contains(u.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await fp(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 dp="last-dial-failure",hp="last-dial-success";var pp=100,qi=50;function Ab(r,e){let t=bo.exactMatch(r.multiaddr),n=bo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=wo.exactMatch(r.multiaddr),s=wo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Er.exactMatch(r.multiaddr),a=Er.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=iu.exactMatch(r.multiaddr),l=iu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let f=ou.exactMatch(r.multiaddr),u=ou.exactMatch(e.multiaddr);if(f&&!u)return-1;if(!f&&u)return 1;let d=su.exactMatch(r.multiaddr),h=su.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function _b(r,e){let t=so(r.multiaddr),n=so(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ib(r,e){let t=Et(r.multiaddr),n=Et(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Cb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Tb(r,e){let t=vr.exactMatch(r.multiaddr),n=vr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function mp(r){return r.sort(Ab).sort(Cb).sort(Tb).sort(Ib).sort(_b)}var $i=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var fu=ca(yp(),1);var du=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},bp=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function hu(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((u,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(bp(i));return}if(i&&(c=()=>{d(bp(i))},i.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new du;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}function pu(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 Ao=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=pu(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})}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 _o=class extends fu.default{#e;#r;#n=0;#h;#m=!1;#b=!1;#c;#I=0;#w=0;#l;#u;#a;#i=[];#s=0;#t;#C;#o=0;#g;#f;#R=1n;#y=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ao,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.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#x(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)}#k(e){this.#a?this.#i.push(e):this.#n++}#O(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#E(){return this.#i.length-this.#s}get#N(){return this.#r?!0:this.#a?this.#E()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#A(),this.emit("next")}#F(){this.#u=void 0,this.#P(),this.#L()}#U(e){if(this.#a){if(this.#x(e),this.#E()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#v(o),!0}return!1}if(this.#l===void 0){let t=this.#I-e;if(t<0){if(this.#w>0){let n=e-this.#w;if(n<this.#c)return this.#v(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#v(t),!0}return!1}#v(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#F()},e))}#S(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#T(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#A(){if(this.#t.size===0){if(this.#S(),this.emit("empty"),this.#o===0){if(this.#T(),this.#a&&this.#s>0){let t=Date.now();this.#x(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#U(t);if(this.#N&&this.#M){let o=this.#t.dequeue();this.#r||(this.#k(t),this.#p()),this.emit("active"),o(),n&&this.#L(),e=!0}}return e}#L(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#P()},this.#c),this.#I=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#S(),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){for(;this.#A(););}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.#_()}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}`);this.#t.enqueue(async()=>{this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let i;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#q(),this.#y.delete(s),l}this.#w=Date.now();let a=e({signal:t.signal});if(t.timeout&&(a=hu(Promise.resolve(a),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:l}=t;a=Promise.race([a,new Promise((f,u)=>{i=()=>{u(l.reason)},l.addEventListener("abort",i,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{i&&t.signal?.removeEventListener("abort",i),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}},t),this.emit("add"),this.#A()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#_(),this):this}pause(){this.#f=!0}clear(){this.#t=new this.#C,this.#S(),this.#D(),this.emit("empty"),this.#o===0&&(this.#T(),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}#K(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#D()}))}#q(){this.#r||(this.#O(),this.#p())}#D(){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.#x(o),t=this.#E()}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 zi(r){let e=[Ve.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var mu=60;function Hi(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:Ve[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ve[e.type],TTL:e.TTL??e.ttl??mu,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var Db=4;function gu(r,e={}){let t=new _o({concurrency:e.queryConcurrency??Db});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),zi(o.types).forEach(a=>{s.append("type",Ve[a])}),o.onProgress?.(new de("dns:query",n));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Hi(await a.json());return o.onProgress?.(new de("dns:response",c)),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function wp(){return[gu("https://cloudflare-dns.com/dns-query"),gu("https://dns.google/resolve")]}var vp=ca(Ep(),1);var yu=class{lru;constructor(e){this.lru=(0,vp.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 Hi({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:Ve[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??mu)*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 Sp(r){return new yu(r)}var Rb=1e3,Wi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Sp(e.cacheSize??Rb),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["."]=wp())}async query(e,t={}){let n=zi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("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,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new de("dns:error",l))}}throw new $i(a,`DNS lookup of ${e} ${n} failed`)}};var Ve;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ve||(Ve={}));function Ap(r={}){return new Wi(r)}var bu=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:[Ve.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=Ap()),this.dns)}},Ar=new bu;async function wu(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Bi("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 wu(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Io={maxParallelDials:qi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},Gi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Io.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Io.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Io.dialTimeout,this.connections=t.connections??new We,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Io.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new qs({concurrency:t.maxParallelDials??Io.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Ge.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}=Fi(e);if(n!=null&&t.force!==!0){let i=Ui(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),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 de("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Cr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new de("dial-queue:start-dial"));let a=vt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Su,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 f=[],u=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...u]);let d=await this.calculateMultiaddrs(n,u,{...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}f.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,f.map(h=>h.multiaddr.toString())),e?.onProgress?.(new de("dial-queue:calculated-addresses",f));for(let h of f){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Cr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[hp]:L(Date.now().toString())}})}catch(E){this.log.error("could not update last dial failure key for %p - %e",n,E)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[dp]:L(Date.now().toString())}})}catch(E){this.log.error("could not update last dial failure key for %p - %e",n,E)}if(t.aborted)throw new No(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:X(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Cr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Eo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=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(...u.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(u){u.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,u)}}}let s=(await Promise.all(o.map(async u=>{let d=await wu(u.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(u.multiaddr)?u:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(u),isCertified:d.isCertified}:d)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let d=u.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let u of i){let d=u.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(d,u)}let c=[...a.values()];if(c.length===0)throw new ki("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let f=this.addressSorter==null?mp(l):l.sort(this.addressSorter);if(f.length===0)throw new Eo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:u})=>u.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!vr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var kb=Object.prototype.toString,Ob=r=>kb.call(r)==="[object Error]",Nb=new Set(["network error","Failed to fetch","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 Au(r){if(!(r&&Ob(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")?!0:Nb.has(t)}function Mb(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 Yi(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}.`)}}var _u=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 Bb(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 _p(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Fb({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 _u)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await o.onFailedAttempt(c),_p(n,a)<=0)throw s;let l=await o.shouldConsumeRetry(c),f=_p(n,a);if(f<=0||i<=0)throw s;if(s instanceof TypeError&&!Au(s)){if(l)throw s;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw s;if(!l)return o.signal?.throwIfAborted(),!1;let u=Bb(t,o),d=Math.min(u,f);return o.signal?.throwIfAborted(),d>0&&await new Promise((h,p)=>{let E=()=>{clearTimeout(m),o.signal?.removeEventListener("abort",E),p(o.signal.reason)},m=setTimeout(()=>{o.signal?.removeEventListener("abort",E),h()},d);o.unref&&m.unref?.(),o.signal?.addEventListener("abort",E,{once:!0})}),o.signal?.throwIfAborted(),!0}async function Iu(r,e={}){if(e={...e},Mb(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,Yi("factor",e.factor,{min:0,allowInfinity:!1}),Yi("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Yi("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Yi("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 Fb({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Xi=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 Ks({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);Ip(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Iu(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(da)&&(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=>Ip(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 Ip(r){for(let e of r.tags.keys())if(e.startsWith(da))return!0;return!1}var Su=50,Cu={maxConnections:pp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Zi=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??Cu.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new We,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=>vo(X(n))),this.deny=(t.deny??[]).map(n=>vo(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Cu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new $s({points:t.inboundConnectionThreshold??Cu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Ki({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new Gi(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??qi,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Xi({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 Bu(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 Fu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([rt(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(this.maxConnections<1)throw new C("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 ut("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=Fi(e);if(this.peerId.equals(n))throw new Ir("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Ui(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 de("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Su});if(s.status!=="open")throw new zt("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 Ct("Duplicate multiaddr connection")),c;return a||i.push(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([rt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=H(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(xe(e.remoteAddr)){let s=H(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(xe(e.remoteAddr)){let o=H(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 qb=1e4,$b="1.0.0",Vb="ping",zb="ipfs",Cp=32,Hb=!0,ji=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??zb}/${Vb}/${$b}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??qb,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Hb,this.timeout=new As({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xn]=["@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();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Rl(o);t=Date.now(),await Promise.all([s.write(zr(Cp),{signal:n}),s.read({bytes:Cp,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).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 Qi=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:U(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(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 pn("No content routers available");let n=this,o=new ir;for await(let s of un(...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 pn("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 pn("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 ut;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 ut;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Ji=globalThis.CustomEvent??Event;async function*Tu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ge(),a=ge(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ge(),await i.promise),f)break;let E={done:!1};s.push(E),p().then(m=>{E.done=!0,E.ok=!0,E.value=m,o.dispatchEvent(new Ji("task-complete"))},m=>{E.done=!0,E.err=m,o.dispatchEvent(new Ji("task-complete"))})}c=!0,o.dispatchEvent(new Ji("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ji("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let E=s[p];if(s.splice(p,1),p--,E.ok)yield E.value;else throw f=!0,i.resolve(),E.err;i.resolve()}}for(;;){if(u()||(a=ge(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var ea=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:U(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 xo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ti("Should not try to find self");let n=this,o=un(...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 Ht}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new xo("No peer routers available");let n=this,o=no(1024);for await(let s of Tu((async function*(){let i=un(...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 ta=class extends Le{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=vt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ge(),yield(await rt(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=vt([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=zr(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 qe(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 Lu=32,Pu=64,ra=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=Ie({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 Li(`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 Pi(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Lu,maxOutboundStreams:Pu,...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 C("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?.has(t)!==!1&&(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?.has(t.id)!==!1&&(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=Ie({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ie({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??wn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`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 Mi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("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 ut("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 Di)});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}),f=this.listeners.get(s)??[];f==null&&(f=[],this.listeners.set(s,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let u=f.findIndex(d=>d===l);f.splice(u,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),eu.matches(c)?t.ipv4.attempts++:tu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),eu.matches(c)&&t.ipv4.success++,tu.matches(c)&&t.ipv6.success++},u=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,u),t.errors.set(c.toString(),u),u}))}}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===wn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Ri(`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 zd(r,e)}Ue.formatters.e=r=>r==null?"undefined":Wd(r);function _0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function hs(r){return{forComponent(e){return Gd(e,r)}}}function Gd(r,e){let t=_0(`${r}:trace`);return Ue.enabled(`${r}:trace`)&&Ue.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ue(`${r}:trace`,e)),Object.assign(Ue(r,e),{error:Ue(`${r}:error`,e),trace:t,newScope:n=>Gd(`${r}:${n}`,e)})}function Hd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function sr(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 ps(r){let e=dt(J.decode(`z${r}`));return jr(e)}var We=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 sr(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 sr(this.map.values(),e=>e.key)}values(){return sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ir=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 sr(this.set.entries(),e=>{let t=ps(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ps(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return sr(this.set.values(),e=>ps(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 Zc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},jd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Xd=new globalThis.TextEncoder;function I0(r,e){let t=Zc[e],n=jd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function C0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Zc[e],o=jd[e],s=r;for(;s.length>0;){let i=Xd.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 Qc(r,{size:e=32,utf8Buffer:t}={}){if(!Zc[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 C0(r,e,t);r=Xd.encode(r)}return I0(r,e)}var to={hash:r=>Number(Qc(r,{size:32})),hashV:(r,e)=>T0(to.hash(r,e))};function T0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var Jc=64,et=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Jc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(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?Z(this.fp,e.fp):!1}};function ar(r,e){return Math.floor(Math.random()*(e-r))+r}var cr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof et))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof et))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 et))throw new TypeError("Invalid Fingerprint");let t=ar(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof et))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var L0=500,ro=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??to,this.seed=e.seed??ar(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new et(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 cr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new cr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[ar(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize));for(let a=0;a<L0;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 cr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new et(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new et(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}},P0={1:.5,2:.84,4:.95,8:.98};function D0(r=.001){return r>.002?2:r>1e-5?4:8}function Yd(r,e=.001){let t=D0(e),n=P0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Jc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ms=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??to,this.seed=e.seed??ar(0,Math.pow(2,10)),this.filterSeries=[new ro({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ro({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function no(r,e=.001,t){return new ms({...Yd(r,e),...t??{}})}function H(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 C(`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 gs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,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 Zd=45,R0=15,Xr=new gs;function ys(r){if(!(r.length>R0))return Xr.new(r).parseWith(()=>Xr.readIPv4Addr())}function bs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Zd))return Xr.new(r).parseWith(()=>Xr.readIPv6Addr())}function Yr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Zd)return;let t=Xr.new(r).parseWith(()=>Xr.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 Qd(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 Jd(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 el(r){switch(r.length){case lr:return r.join(".");case ur:{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 eh(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 th(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var lr=4,ur=16,iS=parseInt("0xFFFF",16),k0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function oo(r,e){e.length===ur&&r.length===lr&&Qd(e,0,11)&&(e=e.slice(12)),e.length===lr&&r.length===ur&&Jd(r,k0,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 rh(r,e){if(typeof e=="string"&&(e=Yr(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 tl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=lr,o=ys(e);if(o==null&&(n=ur,o=bs(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=rl(s,8*n);return{network:oo(o,i),mask:i}}function rl(r,e){if(e!==8*lr&&e!==8*ur)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 Zr=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=tl(e));else{let n=Yr(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=Yr(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=rl(o,8*n.length);this.network=oo(n,this.mask)}}contains(e){return rh({network:this.network,mask:this.mask},e)}toString(){let e=eh(this.mask),t=e!==-1?String(e):th(this.mask);return el(this.network)+"/"+t}};function nh(r){try{let e=H(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 oh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function so(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return oh(e.host);default:return!1}}catch{return!1}}function xe(r){try{return H(r),!0}catch{return!1}}function tt(r){return!!ys(r)}function ws(r){return!!bs(r)}var ih=la(sh(),1),O0=["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"],N0=O0.map(r=>new ih.Netmask(r));function nl(r){for(let e of N0)if(e.contains(r))return!0;return!1}function M0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function B0(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 nl(o)}function F0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function U0(r){let e=r.split(":"),t=e[e.length-1];return nl(t)}function K0(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 Qr(r){if(tt(r))return nl(r);if(M0(r))return B0(r);if(F0(r))return U0(r);if(ws(r))return K0(r)}function Et(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return Qr(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ge(){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}},Jr=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 ol=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function en(r={}){return q0(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 q0(r,e){e=e??{};let t=e.onEnd,n=new Jr,o,s,i,a=ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=A=>{s=null,n.push(A);try{m(r(n))}catch(x){g(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ge()})}},l=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Jr,s!=null?s({error:m}):(n.push({error:m}),o)),u=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?f(m):l({done:!0})),h=()=>(n=new Jr,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:u,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let A,x;g!=null&&(A=new Promise((I,O)=>{x=()=>{O(new ol)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,A])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(m){return E.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(m){return E.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:m=>E.onEmpty(m)},o}var sl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ah=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ao(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((u,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(ah(i));return}if(i&&(c=()=>{d(ah(i))},i.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new sl;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var $0=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 V0(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:f}=$0(r),u=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(E){n(),i(E);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);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=ao(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function rt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=V0(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function co(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 Es=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}},vs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},fr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function z0(r){return r.reason}async function qe(r,e,t){if(e==null)return r;let n=t?.translateError??z0;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 Ss=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function H0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var As=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=H0(),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 Ge),this.cleanup())}async join(e={}){let t=new Ss(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 qe(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tn=class extends Le{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=co(this.emitEmpty.bind(this),1),this.emitIdle=co(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 vs;let n=new As(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){this.size!==0&&await rt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await rt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await rt(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=en({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 Ge("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 vt(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 rn=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 W0=1.2,G0=2,j0=5e3,X0=6e4,Y0=5e3,_s=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??Y0;this.success=new rn(t),this.failure=new rn(t),this.next=new rn(t),this.failureMultiplier=e.failureMultiplier??G0,this.timeoutMultiplier=e.timeoutMultiplier??W0,this.minTimeout=e.minTimeout??j0,this.maxTimeout=e.maxTimeout??X0,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=vt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){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 Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},St=class extends Error{static name="ValidationError";name="ValidationError"},Is=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Cs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function al(r){return e=>U(e,r)}function cl(r){return e=>L(e,r)}function nn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function dr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function ch(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=L(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=dr(n);return Xe([t,o],t.length+o.length)}function lh(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ze.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=dr(n);return Xe([t,o],t.length+o.length)}function ll(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=U(e,"base32"),o=nn(t);return`${n}:${o}`}var ul=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 Ee("Invalid byte value in IP address");e[n]=o}),e},uh=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=tt(t[n]),i;s&&(i=ul(t[n]),t[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,U(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 Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},fh=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},dh=function(r){if(r.byteLength!==16)throw new Ee("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 Ee(`Invalid IPv6 address "${t}"`)}};function hh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var il=Object.values(_n).map(r=>r.decoder),Z0=(function(){let r=il[0].or(il[1]);return il.slice(2).forEach(e=>r=r.or(e)),r})();function ph(r){return Z0.decode(r)}function mh(r){return e=>r.encoder.encode(e)}function Q0(r){if(parseInt(r).toString()!==r)throw new St("Value must be an integer")}function J0(r){if(r<0)throw new St("Value must be a positive integer, or zero")}function ey(r){return e=>{if(e>r)throw new St(`Value must be smaller than or equal to ${r}`)}}function ty(...r){return e=>{for(let t of r)t(e)}}var lo=ty(Q0,J0,ey(65535));var ye=-1,fl=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 Cs(`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)}))}},At=new fl,gy=[{code:4,name:"ip4",size:32,valueToBytes:ul,bytesToValue:fh,validate:r=>{if(!tt(r))throw new St(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:dr,bytesToValue:nn,validate:lo},{code:273,name:"udp",size:16,valueToBytes:dr,bytesToValue:nn,validate:lo},{code:33,name:"dccp",size:16,valueToBytes:dr,bytesToValue:nn,validate:lo},{code:41,name:"ip6",size:128,valueToBytes:uh,bytesToValue:dh,stringToValue:hh,validate:r=>{if(!ws(r))throw new St(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:al("base10"),valueToBytes:cl("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:dr,bytesToValue:nn,validate:lo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:al("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?cl("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ll,valueToBytes:ch},{code:445,name:"onion3",size:296,bytesToValue:ll,valueToBytes:lh},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:mh(Pa),valueToBytes:ph},{code:480,name:"http"},{code:481,name:"http-path",size:ye,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:ye}];gy.forEach(r=>{At.addProtocol(r)});function gh(r){let e=[],t=0;for(;t<r.length;){let n=er(r,t),o=At.getProtocol(n),s=me(n),i=yy(o,r,t+s),a=0;i>0&&o.size===ye&&(a=me(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+s+a,u=r.subarray(f,f+i);l.value=o.bytesToValue?.(u)??U(u)}e.push(l),t+=c}return e}function yh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=At.getProtocol(n.code),s=me(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??L(n.value),a=i.byteLength,o.size===ye&&(c=me(a)));let l=new Uint8Array(s+c+a),f=0;$r(n.code,l,f),f+=s,i!=null&&(o.size===ye&&($r(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Xe(t,e)}function bh(r){if(r.charAt(0)!=="/")throw new Ee('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=At.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 Ee(`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 Ee(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function wh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=At.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function yy(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:er(e,t)}var by=Symbol.for("nodejs.util.inspect.custom"),_l=Symbol.for("@multiformats/multiaddr");function wy(r){if(r==null&&(r="/"),$t(r))return r.getComponents();if(r instanceof Uint8Array)return gh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Rs=class r{[_l]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=wy(e),t.validate!==!1&&xy(this)}get bytes(){return this.#n==null&&(this.#n=yh(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=wh(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 Is(`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 Z(this.bytes,e.bytes)}[by](){return`Multiaddr(${this.toString()})`}};function xy(r){r.getComponents().forEach(e=>{let t=At.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function $t(r){return!!r?.[_l]}function X(r){return new Rs(r)}var Il=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ge(),this.haveNext=ge()}[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=ge(),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=ge(),await qe(this.readNext.promise,t?.signal,t)}};function xh(){return new Il}function Ey(r){return r[Symbol.asyncIterator]!=null}async function vy(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*Sy(r){let e=new AbortController,t=xh();vy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Ay(r){for(let e of r)yield*e}function _y(...r){let e=[];for(let t of r)Ey(t)||e.push(t);return e.length===r.length?Ay(e):Sy(r)}var un=_y;var Iy=4194304,ks=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Tl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ll=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Pl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Cy(r){return typeof r?.closeRead=="function"}function Ty(r){return typeof r?.close=="function"}function Cl(r){return Cy(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Ty(r)?r.status!=="open":!1}function Ly(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Dl(r,e){let t=e?.maxBufferSize??Iy,n=new Q,o,s=!1;if(!Ly(r))throw new C("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(s===!0)throw new ks("Stream was unwrapped");if(Cl(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new fr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await qe(o.promise,f?.signal),Cl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Cl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new fr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(s===!0)throw new ks("Stream was unwrapped");r.send(f)||await rt(r,"drain",{signal:u?.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 Os(r,e={}){let t=Dl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??er,o=e?.lengthEncoder??Ft;return{async read(i){let a=-1,c=new Q;for(;;){let f=await t.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Tl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Pl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ll(`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 fr(`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 fr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Ns=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ms=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Bs(r){return r[Symbol.asyncIterator]!=null}function Eh(r,e){if(r.byteLength>e)throw new fn("Message length too long")}var Us=r=>{let e=me(r),t=Se(e);return Ft(r,t),Us.bytes=e,t};Us.bytes=0;function Ks(r,e){e=e??{};let t=e.lengthEncoder??Us,n=e?.maxDataLength??4194304;function*o(s){Eh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Bs(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ks.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Us,n=e?.maxDataLength??4194304;return Eh(r,n),new Q(t(r.byteLength),r)};var mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var kl=r=>{let e=er(r);return kl.bytes=me(e),e};kl.bytes=0;function Rl(r,e){let t=new Q,n=mr.LENGTH,o=-1,s=e?.lengthDecoder??kl,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(t),o<0)throw new Ns("Invalid message length");if(o>a)throw new fn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Ms("Message length length too long");break}throw l}if(n===mr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=mr.LENGTH}}}return Bs(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})()}Rl.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Rl(n,{...e??{},onLength:s=>{t=s}})};var qs=class extends tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var $s=class extends tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Vs=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 Ol}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 Es("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)}},Ol=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 Nl=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 Ie(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Nl({name:e,metrics:t}):n=new Map,n}var Ml=class extends We{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 Bl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ml({name:e,metrics:t}):n=new We,n}var fo;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(fo||(fo={}));var zs=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var dn=class r{static createFromProtobuf=e=>{let t=fo.decode(e),n=Gr(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=vh(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 zs("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=fo.encode({publicKey:He(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Z(this.marshal(),e.marshal())}async validate(e,t){let n=vh(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},vh=(r,e,t)=>{let n=L(r),o=Ft(n.byteLength),s=Ft(e.length),i=Ft(t.length);return new Q(o,n,s,e,i,t)};var Sh="libp2p-peer-record",Ah=Uint8Array.from([3,1]);var ho;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Oe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>ke(s,n.codec()),n.decode=(s,i)=>Re(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new nr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>ke(n,r.codec()),r.decode=(n,o)=>Re(n,r.codec(),o)})(ho||(ho={}));function _h(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 gr=class r{static createFromProtobuf=e=>{let t=ho.decode(e),n=jr(dt(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Sh;static CODEC=Ah;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=ho.encode({peerId:this.peerId.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||!_h(this.multiaddrs,e.multiaddrs))}};function Dy(r){return r[Symbol.asyncIterator]!=null}function Ry(r){if(Dy(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var po=Ry;var $e=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Hs(r,e,t,n){let o=new $e(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(){Ul(t,"abort",u),Ul(r,e,l),Ul(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=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.`))},u=()=>{c(),a(o)};Fl(t,"abort",u),Fl(r,e,l),Fl(r,s,f)})}function Fl(r,e,t){r!=null&&(Ih(r)?r.addEventListener(e,t):r.addListener(e,t))}function Ul(r,e,t){r!=null&&(Ih(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ih(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Ws=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Gs=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 $e)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ky(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var js=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=ky(),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 $e),this.cleanup())}async join(e={}){let t=new Gs(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 qe(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 Kl(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 mo=class extends Le{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=Kl(this.emitEmpty.bind(this),1),this.emitIdle=Kl(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 Ws;let n=new js(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 $e)}),this.clear()}async onEmpty(e){this.size!==0&&await Hs(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Hs(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Hs(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=en({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 $e("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 Xs="lock:worker:request-read",Ys="lock:worker:abort-read-request",Zs="lock:worker:release-read",Qs="lock:master:grant-read",Js="lock:master:error-read",ei="lock:worker:request-write",ti="lock:worker:abort-write-request",ri="lock:worker:release-write",ni="lock:master:grant-write",oi="lock:master:error-write",si="lock:worker:finalize",ii="mortice",Ch={singleProcess:!1};var ql=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===si&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Th=(r=10)=>Math.random().toString().substring(2,r+2);var ai=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ii)}readLock(e){return this.sendRequest(Xs,Ys,Qs,Js,Zs,e)}writeLock(e){return this.sendRequest(ei,ti,ni,oi,ri,e)}finalize(){this.channel.postMessage({type:si,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Th();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);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",u)})}};var Lh=r=>{if(r=Object.assign({},Ch,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ii),n=new Le;return t.addEventListener("message",ql(n,t,"requestReadLock","abortReadLockRequest",Xs,Ys,Js,Zs,Qs)),t.addEventListener("message",ql(n,t,"requestWriteLock","abortWriteLockRequest",ei,ti,oi,ri,ni)),n}return new ai(r.name)};var yr=new Map,go;function Ph(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Oy(r){if(go==null&&(go=Lh(r),!Ph(go))){let e=go;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=yr.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=yr.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=yr.get(n);o?.finalize()})}return go}async function $l(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new $e)};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 Dh=(r,e)=>{let t=yr.get(r);if(t!=null)return t;let n=Oy(e);if(Ph(n))return t=n,yr.set(r,t),t;let o=new mo({concurrency:1}),s;return t={async readLock(i){if(s!=null)return $l(s,i);s=new mo({concurrency:e.concurrency,autoStart:!1});let a=s,c=$l(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,$l(o,i)},finalize:()=>{yr.delete(r)},queue:o},yr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Ny={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Vl(r){let e=Object.assign({},Ny,r);return Dh(e.name,e)}var _t;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Re(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),li.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=li.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Re(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ci.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new nr('Decode error - map field "addresses" had too many elements');a.addresses.push(ci.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new nr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Hn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Hn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ke(o,r.codec()),r.decode=(o,s)=>Re(o,r.codec(),s)})(_t||(_t={}));var ci;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(ci||(ci={}));var li;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(li||(li={}));function My(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Gr(e.publicKey,t);return Xc(n)}function Rh(r,e,t){let n=_t.decode(e);return hn(r,n,t)}function hn(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:My(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 kh(r,e){return By(r.addresses,e.addresses)&&Fy(r.protocols,e.protocols)&&Uy(r.publicKey,e.publicKey)&&Ky(r.peerRecordEnvelope,e.peerRecordEnvelope)&&qy(r.metadata,e.metadata)&&$y(r.tags,e.tags)}function By(r,e){return Nh(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Z(t.multiaddr,n.multiaddr)))}function Fy(r,e){return Nh(r,e,(t,n)=>t===n)}function Uy(r,e){return Oh(r,e)}function Ky(r,e){return Oh(r,e)}function qy(r,e){return Mh(r,e,(t,n)=>Z(t,n))}function $y(r,e){return Mh(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Oh(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Z(r,e):!1}function Nh(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 Mh(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 It="/",Bh=new TextEncoder().encode(It),ui=Bh[0],br=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ui)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(It))}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=Bh),this._buf[0]!==ui){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ui,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ui;)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(It).slice(1)}type(){return Vy(this.baseNamespace())}name(){return zy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(It)||(e+=It),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(It):new r(e.slice(0,-1).join(It))}child(e){return this.toString()===It?e:e.toString()===It?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(),...Hy(e.map(t=>t.namespaces()))])}};function Vy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function zy(r){let e=r.split(":");return e[e.length-1]}function Hy(r){return[].concat(...r)}var zl="/peers/";function yo(r){if(!Lt(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new br(`${zl}${e}`)}async function Fh(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)),!$t(i.multiaddr))throw new C("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 di(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new C("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=fi(d,{validate:Uh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=fi(d,{validate:Kh,map:qh})}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,p]of d)p==null?a.delete(h):a.set(h,p);a=fi([...a.entries()],{validate:Uh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,E]of d)E==null?h.delete(p):h.set(p,E);c=fi([...h.entries()],{validate:Kh,map:qh})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=He(o.id.publicKey):e.publicKey!=null?f=He(e.publicKey):r.publicKey!=null&&(f=He(r.publicKey));let u={addresses:await Fh(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:f,peerRecordEnvelope:l};return u.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Z(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete u.publicKey,u}function fi(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 Uh(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function Kh(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function qh(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 $h(r){let e=r.toString().split("/")[2],t=le.parse(e,ze);return eo(t)}function Hl(r,e,t){let n=$h(r);return Rh(n,e,t)}function Wy(r,e){return{prefix:zl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Hl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Hl(n.key,n.value,e),Hl(o.key,o.value,e)))}}var hi=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=Bl({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:Vl({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(yo(e),t)}async load(e,t){let n=yo(e),o=await this.datastore.get(n,t),s=_t.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Ht;return hn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await di(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 di(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 di(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(Wy(e??{},this.maxAddressAge),e)){let o=$h(t);if(o.equals(this.peerId))continue;let s=_t.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield hn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=yo(e),o=await this.datastore.get(n,t),s=_t.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Ht;return{peerPB:s,peer:hn(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=_t.encode(t);return await this.datastore.put(yo(e),s,o),{peer:hn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!kh(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 Wl=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 hi(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 po(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=Lt(t)?t:Lt(t?.expectedPeer)?t.expectedPeer:void 0,s=Lt(t)||t===void 0?n:t,i=await dn.openAndCertify(e,gr.DOMAIN,s),a=eo(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=gr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(f){if(f.name!=="NotFoundError")throw f}if(l?.peerRecordEnvelope!=null){let f=dn.createFromProtobuf(l.peerRecordEnvelope),u=gr.createFromProtobuf(f.payload);if(u.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(f=>({isCertified:!0,multiaddr:f}))},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 Vh(r,e={}){return new Wl(r,e)}var pi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Gy(r){return r[Symbol.asyncIterator]!=null}function jy(r){if(Gy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gl=jy;function Xy(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 zh=Xy;function Yy(r){return r[Symbol.asyncIterator]!=null}function Zy(r,e){let t=0;if(Yy(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=zh(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 wr=Zy;function Qy(r){return r[Symbol.asyncIterator]!=null}function Jy(r,e){return Qy(r)?(async function*(){yield*(await po(r)).sort(e)})():(function*(){yield*po(r).sort(e)})()}var jl=Jy;function eb(r){return r[Symbol.asyncIterator]!=null}function tb(r,e){return eb(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 Xl=tb;var mi=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 Gl(this.putMany(e,n)),e=[],await Gl(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=wr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=wr(n,()=>o++>=s)}return e.limit!=null&&(n=Xl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=wr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=wr(n,()=>s++>=o)}return e.limit!=null&&(n=Xl(n,e.limit)),n}};var gi=class extends mi{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 pi;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 br(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new br(n),t?.signal?.throwIfAborted()}};var ee=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)}}),Hh=r=>({match:e=>r.match(e)===!1?e:!1}),W=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ce=(...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}}),Y=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function te(...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 rb=N(421),Wh=te(rb),bi=N(54),wi=N(55),xi=N(56),Zl=N(53),x6=te(bi,W(N(421))),E6=te(wi,W(N(421))),v6=te(xi,W(N(421))),S6=te(Ce(Zl,xi,bi,wi),W(N(421))),Gh=Y(N(4),W(N(43))),jh=Y(W(N(42)),N(41),W(N(43))),Ql=Ce(Gh,jh),xr=Ce(Ql,Zl,bi,wi,xi),A6=te(Ce(Ql,Y(Ce(Zl,xi,bi,wi),W(N(421))))),Jl=te(Gh),eu=te(jh),_6=te(Ql),tu=Y(xr,N(6)),bo=Y(xr,N(273)),wo=te(Y(tu,W(N(421)))),I6=te(bo),ru=Y(bo,ee(460),W(N(421))),Ei=Y(bo,ee(461),W(N(421))),nb=Ce(ru,Ei),C6=te(ru),Xh=te(Ei),Yl=Ce(xr,tu,bo,ru,Ei),Yh=Ce(Y(Yl,ee(477),W(N(421)))),Er=te(Yh),Zh=Ce(Y(Yl,ee(478),W(N(421))),Y(Yl,ee(448),W(N(449)),ee(477),W(N(421)))),xo=te(Zh),Qh=Y(bo,ee(280),W(N(466)),W(N(466)),W(N(421))),nu=te(Qh),Jh=Y(Ei,ee(465),W(N(466)),W(N(466)),W(N(421))),ou=te(Jh),yi=Ce(Yh,Zh,Y(tu,W(N(421))),Y(nb,W(N(421))),Y(xr,W(N(421))),Qh,Jh,N(421)),T6=te(yi),ob=Y(W(yi),ee(290),Hh(ee(281)),W(N(421))),vr=te(ob),sb=Ce(Y(yi,ee(290),ee(281),W(N(421))),Y(yi,ee(281),W(N(421))),Y(ee(281),W(N(421)))),su=te(sb),ib=Ce(Y(xr,N(6),ee(480),W(N(421))),Y(xr,ee(480),W(N(421)))),L6=te(ib),ab=Y(xr,Ce(Y(N(6,"443"),ee(480)),Y(N(6),ee(443)),Y(N(6),ee(448),ee(480)),Y(ee(448),ee(480)),ee(448),ee(443)),W(N(421))),P6=te(ab),cb=Ce(Y(N(777),W(N(421)))),D6=te(cb),lb=Ce(Y(N(400),W(N(421)))),R6=te(lb);var ep=864e13;var vi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ie({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=H(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=Qr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?ep-Date.now():0,lastVerified:o?ep-Date.now():void 0})})}remove(e){let t=H(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(!xe(o))continue;let s=H(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=H(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=H(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 Si=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ie({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=H(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:tt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=H(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(!xe(n))continue;let o=H(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(!xe(e))return!1;let n=H(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(!xe(e))return!1;let n=H(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 ub={maxObservedAddresses:10},Ai=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??ub.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&&(Et(e)||nh(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 fb={maxObservedAddresses:10},_i=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??fb.maxObservedAddresses}get(e,t){if(Et(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:!xe(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(!xe(e))return e.toString();let t=H(e);return`${t.host}-${t.port}-${t.protocol}`}};var tp=6e4,rp={maxObservedAddresses:10,addressVerificationTTL:tp*10,addressVerificationRetry:tp*5},db=r=>r;function iu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ct(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var Ii=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 Ai(e,t),this.dnsMappings=new vi(e,t),this.ipMappings=new Si(e,t),this.transportAddresses=new _i(e,t),this.announceFilter=t.announceFilter??db,this.observedAddressFilter=no(1024),this.addressVerificationTTL=t.addressVerificationTTL??rp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??rp.addressVerificationRetry,this._updatePeerStoreAddresses=co(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=H(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=iu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=iu(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=iu(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${tt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${tt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=H(e);if(t.type!=="ip4"||Qr(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Er.exactMatch(s)||xo.exactMatch(s),s=>wo.exactMatch(s),s=>Xh.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(f=>H(f).type==="ip4"&&s(f)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!so(l)).pop();if(a==null)continue;let c=H(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 np;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(np||(np={}));var Ci=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ti=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},pn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Eo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Li=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Pi=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Di=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},vo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Ri=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},ki=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Oi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ni=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Mi=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Vt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Sr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Bi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Fi=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var au=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=hs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>qo(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")}},hb=["metrics","connectionProtector","dns"],pb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function op(r={}){let e=new au(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!pb.includes(o)){let i=e.components[o];if(i==null&&!hb.includes(o))throw new Ci(`${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 sp(r){let e={};for(let t of Object.values(r.components))for(let n of mb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of gb(t))if(e[n]!==!0)throw new Ti(`Service "${yb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function mb(r){return Array.isArray(r?.[xn])?r[xn]:[]}function gb(r){return Array.isArray(r?.[pa])?r[pa]:[]}function yb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function ip(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Er.matches(e)?!0:Et(e)),r}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Ui(r){if(Lt(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:ct(n),e.forEach(o=>{if(!$t(o))throw new Ct("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ct(s);if(t?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Wh.exactMatch(n)),{peerId:t,multiaddrs:e}}var bb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function ap(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??bb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function So(r){let e=H(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new C(`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 C(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Zr(e.host,t)}function cu(r){return!vr.exactMatch(r)}function Ki(r,e,t){if(r==null||e==null)return;let n=e.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=>cu(s)))return n}var qi=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>So(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 We;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let f=await this.peerStore.get(l);o.set(l,[...f.tags.values()].reduce((u,d)=>u+d.value,0))}catch(f){f.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",f)}}}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(f=>{if(xe(c.remoteAddr)){let u=H(c.remoteAddr);return f.contains(u.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await ap(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 cp="last-dial-failure",lp="last-dial-success";var up=100,$i=50;function wb(r,e){let t=wo.exactMatch(r.multiaddr),n=wo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=xo.exactMatch(r.multiaddr),s=xo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Er.exactMatch(r.multiaddr),a=Er.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=su.exactMatch(r.multiaddr),l=su.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let f=nu.exactMatch(r.multiaddr),u=nu.exactMatch(e.multiaddr);if(f&&!u)return-1;if(!f&&u)return 1;let d=ou.exactMatch(r.multiaddr),h=ou.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function xb(r,e){let t=so(r.multiaddr),n=so(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Eb(r,e){let t=Et(r.multiaddr),n=Et(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Sb(r,e){let t=vr.exactMatch(r.multiaddr),n=vr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function fp(r){return r.sort(wb).sort(vb).sort(Sb).sort(Eb).sort(xb)}var Vi=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var uu=la(hp(),1);function fu(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 _o=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=fu(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})}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 Io=class extends uu.default{#e;#r;#n=0;#h;#m=!1;#b=!1;#c;#I=0;#w=0;#l;#u;#a;#i=[];#s=0;#t;#C;#o=0;#g;#f;#R=1n;#y=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:_o,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.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#x(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)}#k(e){this.#a?this.#i.push(e):this.#n++}#O(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#E(){return this.#i.length-this.#s}get#N(){return this.#r?!0:this.#a?this.#E()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#A(),this.emit("next")}#F(){this.#u=void 0,this.#P(),this.#L()}#U(e){if(this.#a){if(this.#x(e),this.#E()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#v(o),!0}return!1}if(this.#l===void 0){let t=this.#I-e;if(t<0){if(this.#w>0){let n=e-this.#w;if(n<this.#c)return this.#v(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#v(t),!0}return!1}#v(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#F()},e))}#S(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#T(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#A(){if(this.#t.size===0){if(this.#S(),this.emit("empty"),this.#o===0){if(this.#T(),this.#a&&this.#s>0){let t=Date.now();this.#x(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#U(t);if(this.#N&&this.#M){let o=this.#t.dequeue();this.#r||(this.#k(t),this.#p()),this.emit("active"),o(),n&&this.#L(),e=!0}}return e}#L(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#P()},this.#c),this.#I=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#S(),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){for(;this.#A(););}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.#_()}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}`);this.#t.enqueue(async()=>{this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let i;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#q(),this.#y.delete(s),l}this.#w=Date.now();let a=e({signal:t.signal});if(t.timeout&&(a=ao(Promise.resolve(a),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:l}=t;a=Promise.race([a,new Promise((f,u)=>{i=()=>{u(l.reason)},l.addEventListener("abort",i,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{i&&t.signal?.removeEventListener("abort",i),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}},t),this.emit("add"),this.#A()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#_(),this):this}pause(){this.#f=!0}clear(){this.#t=new this.#C,this.#S(),this.#D(),this.emit("empty"),this.#o===0&&(this.#T(),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}#K(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#D()}))}#q(){this.#r||(this.#O(),this.#p())}#D(){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.#x(o),t=this.#E()}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 Hi(r){let e=[Ve.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var du=60;function Wi(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:Ve[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ve[e.type],TTL:e.TTL??e.ttl??du,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var Ib=4;function hu(r,e={}){let t=new Io({concurrency:e.queryConcurrency??Ib});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Hi(o.types).forEach(c=>{i.append("type",Ve[c])}),o.onProgress?.(new de("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=Wi(await c.json());return o.onProgress?.(new de("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function pp(){return[hu("https://cloudflare-dns.com/dns-query"),hu("https://dns.google/resolve")]}var yp=la(gp(),1);var pu=class{lru;constructor(e){this.lru=(0,yp.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 Wi({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:Ve[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??du)*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 bp(r){return new pu(r)}var Cb=1e3,Gi=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=bp(e.cacheSize??Cb),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["."]=pp())}async query(e,t={}){let n=Hi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("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 f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new de("dns:error",l))}}throw new Vi(a,`DNS lookup of ${e} ${n} failed`)}};var Ve;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ve||(Ve={}));function wp(r={}){return new Gi(r)}var mu=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:[Ve.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=wp()),this.dns)}},Ar=new mu;async function gu(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Fi("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 gu(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Co={maxParallelDials:$i,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},ji=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Co.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Co.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Co.dialTimeout,this.connections=t.connections??new We,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Co.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new $s({concurrency:t.maxParallelDials??Co.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Ge.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}=Ui(e);if(n!=null&&t.force!==!0){let i=Ki(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),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 de("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Cr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new de("dial-queue:start-dial"));let a=vt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??xu,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 f=[],u=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...u]);let d=await this.calculateMultiaddrs(n,u,{...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}f.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,f.map(h=>h.multiaddr.toString())),e?.onProgress?.(new de("dial-queue:calculated-addresses",f));for(let h of f){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Cr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[lp]:L(Date.now().toString())}})}catch(E){this.log.error("could not update last dial failure key for %p - %e",n,E)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[cp]:L(Date.now().toString())}})}catch(E){this.log.error("could not update last dial failure key for %p - %e",n,E)}if(t.aborted)throw new Mo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:X(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Cr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new vo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=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(...u.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(u){u.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,u)}}}let s=(await Promise.all(o.map(async u=>{let d=await gu(u.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(u.multiaddr)?u:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(u),isCertified:d.isCertified}:d)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let d=u.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let u of i){let d=u.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(d,u)}let c=[...a.values()];if(c.length===0)throw new Oi("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let f=this.addressSorter==null?fp(l):l.sort(this.addressSorter);if(f.length===0)throw new vo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:u})=>u.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!vr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Tb=Object.prototype.toString,Lb=r=>Tb.call(r)==="[object Error]",Pb=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 Eu(r){if(!(r&&Lb(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:Pb.has(t)}function Db(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 Xi(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}.`)}}var vu=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 Rb(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 xp(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function kb({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 vu)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await o.onFailedAttempt(c),xp(n,a)<=0)throw s;let l=await o.shouldConsumeRetry(c),f=xp(n,a);if(f<=0||i<=0)throw s;if(s instanceof TypeError&&!Eu(s)){if(l)throw s;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw s;if(!l)return o.signal?.throwIfAborted(),!1;let u=Rb(t,o),d=Math.min(u,f);return o.signal?.throwIfAborted(),d>0&&await new Promise((h,p)=>{let E=()=>{clearTimeout(m),o.signal?.removeEventListener("abort",E),p(o.signal.reason)},m=setTimeout(()=>{o.signal?.removeEventListener("abort",E),h()},d);o.unref&&m.unref?.(),o.signal?.addEventListener("abort",E,{once:!0})}),o.signal?.throwIfAborted(),!0}async function Su(r,e={}){if(e={...e},Db(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,Xi("factor",e.factor,{min:0,allowInfinity:!1}),Xi("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Xi("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Xi("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 kb({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Yi=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 qs({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);Ep(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Su(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(ha)&&(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=>Ep(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 Ep(r){for(let e of r.tags.keys())if(e.startsWith(ha))return!0;return!1}var xu=50,Au={maxConnections:up,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Zi=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??Au.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new We,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=>So(X(n))),this.deny=(t.deny??[]).map(n=>So(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Au.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Vs({points:t.inboundConnectionThreshold??Au.inboundConnectionThreshold,duration:1}),this.connectionPruner=new qi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new ji(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??$i,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Yi({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 Ou(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 Nu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([rt(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(this.maxConnections<1)throw new C("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 ut("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=Ui(e);if(this.peerId.equals(n))throw new Ir("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Ki(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 de("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??xu});if(s.status!=="open")throw new zt("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 Ct("Duplicate multiaddr connection")),c;return a||i.push(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([rt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=H(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(xe(e.remoteAddr)){let s=H(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(xe(e.remoteAddr)){let o=H(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 Mb=1e4,Bb="1.0.0",Fb="ping",Ub="ipfs",vp=32,Kb=!0,Qi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Ub}/${Fb}/${Bb}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Mb,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Kb,this.timeout=new _s({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xn]=["@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();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Dl(o);t=Date.now(),await Promise.all([s.write(zr(vp),{signal:n}),s.read({bytes:vp,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).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 Ji=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:U(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(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 pn("No content routers available");let n=this,o=new ir;for await(let s of un(...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 pn("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 pn("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 ut;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 ut;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var ea=globalThis.CustomEvent??Event;async function*_u(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ge(),a=ge(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ge(),await i.promise),f)break;let E={done:!1};s.push(E),p().then(m=>{E.done=!0,E.ok=!0,E.value=m,o.dispatchEvent(new ea("task-complete"))},m=>{E.done=!0,E.err=m,o.dispatchEvent(new ea("task-complete"))})}c=!0,o.dispatchEvent(new ea("task-complete"))}catch(p){l=p,o.dispatchEvent(new ea("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let E=s[p];if(s.splice(p,1),p--,E.ok)yield E.value;else throw f=!0,i.resolve(),E.err;i.resolve()}}for(;;){if(u()||(a=ge(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var ta=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:U(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 Eo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Li("Should not try to find self");let n=this,o=un(...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 Ht}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Eo("No peer routers available");let n=this,o=no(1024);for await(let s of _u((async function*(){let i=un(...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 Le{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=vt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ge(),yield(await rt(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=vt([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=zr(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 qe(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 Iu=32,Cu=64,na=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=Ie({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 Pi(`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 Di(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Iu,maxOutboundStreams:Cu,...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 C("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?.has(t)!==!1&&(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?.has(t.id)!==!1&&(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 oa=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=Ie({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ie({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??wn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`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 Bi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("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 ut("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 Ri)});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}),f=this.listeners.get(s)??[];f==null&&(f=[],this.listeners.set(s,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let u=f.findIndex(d=>d===l);f.splice(u,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Jl.matches(c)?t.ipv4.attempts++:eu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Jl.matches(c)&&t.ipv4.success++,eu.matches(c)&&t.ipv6.success++},u=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,u),t.errors.set(c.toString(),u),u}))}}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===wn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new ki(`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}: ${`${Wb(i)}`.split(`
14
+ ${s}: ${`${qb(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 Wb(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var lt="/multistream/1.0.0";var Gb=L(`
18
- `);async function Co(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Gb[0])throw new Oo("Missing newline");return U(n).trimEnd()}async function mn(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=ks(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"]',lt,i);let c=L(`${lt}
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 qb(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var lt="/multistream/1.0.0";var $b=L(`
18
+ `);async function To(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==$b[0])throw new No("Missing newline");return U(n).trimEnd()}async function mn(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=Os(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"]',lt,i);let c=L(`${lt}
19
19
  `),l=L(`${i}
20
- `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await Co(o,t),n.trace('read "%s"',a),a!==lt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(L(`${i}
21
- `),t);if(n.trace("reading protocol response"),a=await Co(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new ko(`Protocol selection failed - could not negotiate ${e}`)}async function gn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=ks(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Co(o,t);if(n.trace('read "%s"',s),s===lt){n.trace('respond with "%s" for "%s"',lt,s),await o.write(L(`${lt}
20
+ `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await To(o,t),n.trace('read "%s"',a),a!==lt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(L(`${i}
21
+ `),t);if(n.trace("reading protocol response"),a=await To(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Oo(`Protocol selection failed - could not negotiate ${e}`)}async function gn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Os(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await To(o,t);if(n.trace('read "%s"',s),s===lt){n.trace('respond with "%s" for "%s"',lt,s),await o.write(L(`${lt}
22
22
  `),t),n.trace('responded with "%s" for "%s"',lt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(L(`${s}
23
- `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Q(...e.map(a=>Us.single(L(`${a}
23
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Q(...e.map(a=>Ks.single(L(`${a}
24
24
  `))),L(`
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(L(`na
26
- `),t),n('responded with "na" for "%s"',s)}}var Ru=class extends Le{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=lu(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 Fo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Mu]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Vt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new zt(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new zt(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new bn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[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 a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await mn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Zb(n.protocol,this.components.registrar,t),s=Dp(n.protocol,"outbound",this);if(s>o){let a=new Bo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}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 gn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Xb(t.protocol,this.components.registrar);if(Dp(t.protocol,"inbound",this)>o)throw new Mo(`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 bn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,f,u)=>{await i(l,f),u(l,f)}),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,f)=>{e=l,t=f,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 Rp(r,e){return new Ru(r,e)}function Xb(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 Lu}function Zb(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??Pu}function Dp(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var oa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ie({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ie({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 Oi(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=vt([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 Ni("Connection denied");await qe(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=ct(n),await qe(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 u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(jb(n)){if(n.remotePeer==null)throw new Ct(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=ct(u)),n?.onProgress?.(new de(`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 u=new Ir("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=Rp(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 gn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Sr(`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 Sr(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 mn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Sr(`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 Sr(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 mn(e,o,n),i=t.get(s);if(i==null)throw new Vt(`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 Vt(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 gn(e,o,n),i=t.get(s);if(i==null)throw new Vt(`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 jb(r){return r.skipEncryption===!0}var sa="3.1.3",ia="js-libp2p";function Op(r,e){return`${r??ia}/${e??sa} browser/${globalThis.navigator.userAgent}`}var To=class extends Le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Le,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??ds(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??ia,s=e.nodeInfo?.version??sa,i=this.components=cp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Op(o,s)},logger:this.logger,events:t,datastore:e.datastore??new mi,connectionGater:up(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Gh(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new oa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,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 Zi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ji(this.components,e.connectionMonitor)),this.configureComponent("registrar",new ra(this.components)),this.configureComponent("addressManager",new _i(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ea(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Qi(this.components,{routers:c})),this.configureComponent("randomWalk",new ta(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[la]!=null&&(this.log("registering service %s for content routing",l),c.push(u[la])),u[fa]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[fa])),u[ua]!=null&&(this.log("registering service %s for peer discovery",l),u[ua].addEventListener?.("peer",d=>{this.#e(d)}))}lp(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 ir;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 C("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new C("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={}){$t(e)&&(e=ct(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=Xe([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Gr(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 Qb(r={}){r.privateKey??=await Kd("Ed25519");let e=new To({...await Hd(r),peerId:zd(r.privateKey)});return r.start!==!1&&await e.start(),e}var Jb=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function ew(r){return r==null?!1:r instanceof To?!0:Jb.every(e=>typeof r[e]=="function")}return Kp(tw);})();
26
+ `),t),n('responded with "na" for "%s"',s)}}var Lu=class extends Le{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=cu(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 Uo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[ku]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Vt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new zt(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new zt(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new bn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[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 a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await mn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Hb(n.protocol,this.components.registrar,t),s=Ip(n.protocol,"outbound",this);if(s>o){let a=new Fo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}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 gn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=zb(t.protocol,this.components.registrar);if(Ip(t.protocol,"inbound",this)>o)throw new Bo(`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 bn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,f,u)=>{await i(l,f),u(l,f)}),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,f)=>{e=l,t=f,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 Cp(r,e){return new Lu(r,e)}function zb(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 Iu}function Hb(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??Cu}function Ip(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var sa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ie({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ie({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 Ni(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=vt([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 Mi("Connection denied");await qe(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=ct(n),await qe(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 u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(Wb(n)){if(n.remotePeer==null)throw new Ct(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=ct(u)),n?.onProgress?.(new de(`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 u=new Ir("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=Cp(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 gn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Sr(`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 Sr(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 mn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Sr(`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 Sr(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 mn(e,o,n),i=t.get(s);if(i==null)throw new Vt(`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 Vt(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 gn(e,o,n),i=t.get(s);if(i==null)throw new Vt(`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 Wb(r){return r.skipEncryption===!0}var ia="3.1.4",aa="js-libp2p";function Lp(r,e){return`${r??aa}/${e??ia} browser/${globalThis.navigator.userAgent}`}var Lo=class extends Le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Le,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??hs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??aa,s=e.nodeInfo?.version??ia,i=this.components=op({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Lp(o,s)},logger:this.logger,events:t,datastore:e.datastore??new gi,connectionGater:ip(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Vh(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new sa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new oa(this.components,e.transportManager)),this.configureComponent("connectionManager",new Zi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Qi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new na(this.components)),this.configureComponent("addressManager",new Ii(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ta(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ji(this.components,{routers:c})),this.configureComponent("randomWalk",new ra(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[ua]!=null&&(this.log("registering service %s for content routing",l),c.push(u[ua])),u[da]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[da])),u[fa]!=null&&(this.log("registering service %s for peer discovery",l),u[fa].addEventListener?.("peer",d=>{this.#e(d)}))}sp(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 ir;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 C("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new C("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={}){$t(e)&&(e=ct(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=Xe([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Gr(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 Gb(r={}){r.privateKey??=await Bd("Ed25519");let e=new Lo({...await $d(r),peerId:qd(r.privateKey)});return r.start!==!1&&await e.start(),e}var jb=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Xb(r){return r==null?!1:r instanceof Lo?!0:jb.every(e=>typeof r[e]=="function")}return Np(Yb);})();
27
27
  /*! Bundled license information:
28
28
 
29
29
  @noble/hashes/utils.js: