libp2p 3.3.2-29797a5bb → 3.3.2-5b8813abc

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 d0=Object.create;var ws=Object.defineProperty;var h0=Object.getOwnPropertyDescriptor;var p0=Object.getOwnPropertyNames;var m0=Object.getPrototypeOf,g0=Object.prototype.hasOwnProperty;var Gn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ee=(r,e)=>{for(var t in e)ws(r,t,{get:e[t],enumerable:!0})},vd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of p0(e))!g0.call(r,o)&&o!==t&&ws(r,o,{get:()=>e[o],enumerable:!(n=h0(e,o))||n.enumerable});return r};var dc=(r,e,t)=>(t=r!=null?d0(m0(r)):{},vd(e||!r||!r.__esModule?ws(t,"default",{value:r,enumerable:!0}):t,r)),y0=r=>vd(ws({},"__esModule",{value:!0}),r);var Ml=Gn(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.Netmask4Impl=void 0;An.ip2long=Sn;An.long2ip=bt;function bt(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Ox=48,Nx=97,Mx=65;function Fx(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Ox)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Nx)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Mx)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function Sn(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Fx(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var Nl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Sn(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Sn(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=bt(this.netLong),this.mask=bt(this.maskLong),this.hostmask=bt(~this.maskLong),this.first=this.bitmask<=30?bt(this.netLong+1):this.base,this.last=this.bitmask<=30?bt(this.netLong+this.size-2):bt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?bt(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(Sn(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(bt(this.netLong+this.size*e),this.mask)}forEach(e){let t=Sn(this.first),n=Sn(this.last),o=0;for(;t<=n;)e(bt(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};An.Netmask4Impl=Nl});var Sm=Gn(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.Netmask6Impl=void 0;_n.ip6bigint=Bl;_n.bigint2ip6=Ir;var Bx=Ml(),Fl=(1n<<128n)-1n;function Bl(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,Bx.ip2long)(n),s=r.substring(0,t+1)+"0:0";return vm(s)&~0xffffffffn|BigInt(o)}return vm(r)}function vm(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function Ir(r){if(r<0n||r>Fl)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var Ul=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Fl>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Bl(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Ir(this.netBigint),this.mask=Ir(this.maskBigint),this.hostmask=Ir(~this.maskBigint&Fl),this.first=this.base,this.last=Ir(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(Bl(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Ir(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(Ir(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};_n.Netmask6Impl=Ul});var Am=Gn(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.long2ip=tr.ip2long=tr.Netmask=void 0;var xi=Ml();Object.defineProperty(tr,"ip2long",{enumerable:!0,get:function(){return xi.ip2long}});Object.defineProperty(tr,"long2ip",{enumerable:!0,get:function(){return xi.long2ip}});var Ux=Sm(),Kl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new Ux.Netmask6Impl(e,t):this._impl=new xi.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof xi.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};tr.Netmask=Kl});var Hg=Gn((xP,Xf)=>{"use strict";var Iv=Object.prototype.hasOwnProperty,Me="~";function ps(){}Object.create&&(ps.prototype=Object.create(null),new ps().__proto__||(Me=!1));function Tv(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Vg(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Tv(t,n||r,o),i=Me?Me+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 ja(r,e){--r._eventsCount===0?r._events=new ps:delete r._events[e]}function Le(){this._events=new ps,this._eventsCount=0}Le.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Iv.call(t,n)&&e.push(Me?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Le.prototype.listeners=function(e){var t=Me?Me+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Le.prototype.listenerCount=function(e){var t=Me?Me+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Le.prototype.emit=function(e,t,n,o,s,i){var a=Me?Me+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[f].fn.apply(c[f].context,l)}}return!0};Le.prototype.on=function(e,t,n){return Vg(this,e,t,n,!1)};Le.prototype.once=function(e,t,n){return Vg(this,e,t,n,!0)};Le.prototype.removeListener=function(e,t,n,o){var s=Me?Me+e:e;if(!this._events[s])return this;if(!t)return ja(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&ja(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:ja(this,s)}return this};Le.prototype.removeAllListeners=function(e){var t;return e?(t=Me?Me+e:e,this._events[t]&&ja(this,t)):(this._events=new ps,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=Me;Le.EventEmitter=Le;typeof Xf<"u"&&(Xf.exports=Le)});var Jg=Gn((GP,Qg)=>{Qg.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 r1={};ee(r1,{createLibp2p:()=>Jv,dnsaddrResolver:()=>Kr,isLibp2p:()=>t1});var Sd=Symbol.for("@libp2p/connection");var hc=Symbol.for("@libp2p/content-routing");var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var k=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 sr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var ir=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},zr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Bt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},xs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Es=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},vs=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Ss=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var As=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Et=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Vr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Xn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},_s=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Cs=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ut=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Is=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var pc=Symbol.for("@libp2p/peer-discovery");var Ts=Symbol.for("@libp2p/peer-id");function Kt(r){return!!r?.[Ts]}var mc=Symbol.for("@libp2p/peer-routing");var gc="keep-alive";function Ls(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ad(...r){let e=[];for(let t of r)Ls(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 _d(...r){let e=[];for(let t of r)Ls(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 Zn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Zn||(Zn={}));function b0(r){return typeof r?.handleEvent=="function"}function w0(r){return(r!==!0&&r!==!1&&r?.once)??!1}var De=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=w0(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}b0(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Qn=Symbol.for("@libp2p/service-capabilities"),yc=Symbol.for("@libp2p/service-dependencies");var vc={};ee(vc,{base58btc:()=>te,base58flickr:()=>C0});var K1=new Uint8Array(0);function Cd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function vt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Id(r){return new TextEncoder().encode(r)}function Td(r){return new TextDecoder().decode(r)}function x0(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var v=(w-y)*l+1>>>0,T=new Uint8Array(v);y!==w;){for(var I=p[y],N=0,L=v-1;(I!==0||N<m)&&L!==-1;L--,N++)I+=256*T[L]>>>0,T[L]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");m=N,y++}for(var _=v-m;_!==v&&T[_]===0;)_++;for(var B=c.repeat(g);_<v;++_)B+=r.charAt(T[_]);return B}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,v=new Uint8Array(w);p[g];){var T=t[p.charCodeAt(g)];if(T===255)return;for(var I=0,N=w-1;(T!==0||I<y)&&N!==-1;N--,I++)T+=a*v[N]>>>0,v[N]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=I,g++}if(p[g]!==" "){for(var L=w-y;L!==w&&v[L]===0;)L++;for(var _=new Uint8Array(m+(w-L)),B=m;L!==w;)_[B++]=v[L++];return _}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var E0=x0,v0=E0,Dd=v0;var bc=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")}},wc=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 Pd(this,e)}},xc=class{decoders;constructor(e){this.decoders=e}or(e){return Pd(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 Pd(r,e){return new xc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ec=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 bc(e,t,n),this.decoder=new wc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Hr({name:r,prefix:e,encode:t,decode:n}){return new Ec(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Dd(t,r);return Hr({prefix:e,name:r,encode:n,decode:s=>vt(o(s))})}function S0(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 A0(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 _0(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=_0(n);return Hr({prefix:e,name:r,encode(s){return A0(s,n,t)},decode(s){return S0(s,o,t,r)}})}var te=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),C0=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sc={};ee(Sc,{base32:()=>je,base32hex:()=>D0,base32hexpad:()=>k0,base32hexpadupper:()=>R0,base32hexupper:()=>P0,base32pad:()=>T0,base32padupper:()=>L0,base32upper:()=>I0,base32z:()=>O0});var je=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),I0=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T0=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),L0=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),D0=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),P0=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),k0=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),R0=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),O0=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ac={};ee(Ac,{base36:()=>Jn,base36upper:()=>N0});var Jn=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),N0=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var M0=Od,kd=128,F0=127,B0=~F0,U0=Math.pow(2,31);function Od(r,e,t){e=e||[],t=t||0;for(var n=t;r>=U0;)e[t++]=r&255|kd,r/=128;for(;r&B0;)e[t++]=r&255|kd,r>>>=7;return e[t]=r|0,Od.bytes=t-n+1,e}var K0=_c,q0=128,Rd=127;function _c(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw _c.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Rd)<<o:(i&Rd)*Math.pow(2,o),o+=7}while(i>=q0);return _c.bytes=s-n,t}var $0=Math.pow(2,7),z0=Math.pow(2,14),V0=Math.pow(2,21),H0=Math.pow(2,28),W0=Math.pow(2,35),j0=Math.pow(2,42),G0=Math.pow(2,49),Y0=Math.pow(2,56),X0=Math.pow(2,63),Z0=function(r){return r<$0?1:r<z0?2:r<V0?3:r<H0?4:r<W0?5:r<j0?6:r<G0?7:r<Y0?8:r<X0?9:10},Q0={encode:M0,decode:K0,encodingLength:Z0},J0=Q0,eo=J0;function to(r,e=0){return[eo.decode(r,e),eo.decode.bytes]}function Wr(r,e,t=0){return eo.encode(r,e,t),e}function jr(r){return eo.encodingLength(r)}function ft(r,e){let t=e.byteLength,n=jr(r),o=n+jr(t),s=new Uint8Array(o+t);return Wr(r,s,0),Wr(t,s,n),s.set(e,o),new Gr(r,t,e,s)}function St(r){let e=vt(r),[t,n]=to(e),[o,s]=to(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Gr(t,o,i,e)}function Nd(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Cd(r.bytes,t.bytes)}}var Gr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Md(r,e){let{bytes:t,version:n}=r;return n===0?ty(t,Cc(r),e??te.encoder):ry(t,Cc(r),e??je.encoder)}var Fd=new WeakMap;function Cc(r){let e=Fd.get(r);if(e==null){let t=new Map;return Fd.set(r,t),t}return e}var fe=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!==ro)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ny)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ft(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Nd(e.multihash,n.multihash)}toString(e){return Md(this,e)}toJSON(){return{"/":Md(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??Bd(n,o,s.bytes))}else if(t[oy]===!0){let{version:n,multihash:o,code:s}=t,i=St(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!==ro)throw new Error(`Version 0 CID must use dag-pb (code: ${ro}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Bd(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ro,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=vt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Gr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=to(e.subarray(t));return t+=d,f},o=n(),s=ro;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=ey(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 Cc(s).set(n,e),s}};function ey(r,e){switch(r[0]){case"Q":{let t=e??te;return[te.prefix,t.decode(`${te.prefix}${r}`)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}case je.prefix:{let t=e??je;return[je.prefix,t.decode(r)]}case Jn.prefix:{let t=e??Jn;return[Jn.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 ty(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function ry(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 ro=112,ny=18;function Bd(r,e,t){let n=jr(r),o=n+jr(e),s=new Uint8Array(o+t.byteLength);return Wr(r,s,0),Wr(e,s,n),s.set(t,o),s}var oy=Symbol.for("@ipld/js-cid/CID");var Ic={};ee(Ic,{identity:()=>Je});var Ud=0,sy="identity",Kd=vt;function iy(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 ft(Ud,Kd(r))}var Je={code:Ud,name:sy,encode:Kd,digest:iy};function re(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 ay(r){return r.buffer instanceof ArrayBuffer}function Ge(r){return ay(r)?r:r.slice()}async function qd(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 $d(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,Ge(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function zd(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,Ge(e),Ge(t.subarray()));return n?.signal?.throwIfAborted(),s}function At(r=0){return new Uint8Array(r)}function no(r=0){return new Uint8Array(r)}function Tc(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=no(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Vd(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}var Wd=Symbol.for("@achingbrain/uint8arraylist");function Hd(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ps(r){return!!r?.[Wd]}var Q=class r{bufs;length;[Wd]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ps(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ps(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Hd(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Hd(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ps(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Tc(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Tc(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ps(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=no(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=no(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Vd(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 Rc={};ee(Rc,{base10:()=>my});var w2=new Uint8Array(0);function jd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ar(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ar(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Gd(r){return new TextEncoder().encode(r)}function Yd(r){return new TextDecoder().decode(r)}function cy(r){return r?.buffer instanceof ArrayBuffer}function ar(r){return cy(r)?r:r.slice()}function uy(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var v=(w-y)*l+1>>>0,T=new Uint8Array(v);y!==w;){for(var I=p[y],N=0,L=v-1;(I!==0||N<m)&&L!==-1;L--,N++)I+=256*T[L]>>>0,T[L]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");m=N,y++}for(var _=v-m;_!==v&&T[_]===0;)_++;for(var B=c.repeat(g);_<v;++_)B+=r.charAt(T[_]);return B}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,v=new Uint8Array(w);p[g];){var T=t[p.charCodeAt(g)];if(T===255)return;for(var I=0,N=w-1;(T!==0||I<y)&&N!==-1;N--,I++)T+=a*v[N]>>>0,v[N]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=I,g++}if(p[g]!==" "){for(var L=w-y;L!==w&&v[L]===0;)L++;for(var _=new Uint8Array(m+(w-L)),B=m;L!==w;)_[B++]=v[L++];return _}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var ly=uy,fy=ly,Zd=fy;var Lc=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")}},Dc=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 Qd(this,e)}},Pc=class{decoders;constructor(e){this.decoders=e}or(e){return Qd(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 Qd(r,e){return new Pc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kc=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 Lc(e,t,n),this.decoder=new Dc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Yr({name:r,prefix:e,encode:t,decode:n}){return new kc(r,e,t,n)}function zt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Zd(t,r);return Yr({prefix:e,name:r,encode:n,decode:s=>_t(o(s))})}function dy(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 hy(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 py(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=py(n);return Yr({prefix:e,name:r,encode(s){return hy(s,n,t)},decode(s){return dy(s,o,t,r)}})}var my=zt({prefix:"9",name:"base10",alphabet:"0123456789"});var Oc={};ee(Oc,{base16:()=>gy,base16upper:()=>yy});var gy=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yy=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Nc={};ee(Nc,{base2:()=>by});var by=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Mc={};ee(Mc,{base256emoji:()=>Sy});var Jd=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}"),wy=Jd.reduce((r,e,t)=>(r[t]=e,r),[]),xy=Jd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Ey(r){return r.reduce((e,t)=>(e+=wy[t],e),"")}function vy(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=xy[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Sy=Yr({prefix:"\u{1F680}",name:"base256emoji",encode:Ey,decode:vy});var Fc={};ee(Fc,{base32:()=>Xr,base32hex:()=>Iy,base32hexpad:()=>Ly,base32hexpadupper:()=>Dy,base32hexupper:()=>Ty,base32pad:()=>_y,base32padupper:()=>Cy,base32upper:()=>Ay,base32z:()=>Py});var Xr=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ay=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_y=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cy=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Iy=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ty=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ly=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Dy=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Py=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bc={};ee(Bc,{base36:()=>oo,base36upper:()=>ky});var oo=zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ky=zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Uc={};ee(Uc,{base58btc:()=>dt,base58flickr:()=>Ry});var dt=zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ry=zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Kc={};ee(Kc,{base64:()=>Oy,base64pad:()=>Ny,base64url:()=>My,base64urlpad:()=>Fy});var Oy=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ny=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),My=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fy=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qc={};ee(qc,{base8:()=>By});var By=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $c={};ee($c,{identity:()=>Uy});var Uy=Yr({prefix:"\0",name:"identity",encode:r=>Yd(r),decode:r=>Gd(r)});var N2=new TextEncoder,M2=new TextDecoder;var Vc={};ee(Vc,{identity:()=>cb});var $y=rh,eh=128,zy=127,Vy=~zy,Hy=Math.pow(2,31);function rh(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Hy;)e[t++]=r&255|eh,r/=128;for(;r&Vy;)e[t++]=r&255|eh,r>>>=7;return e[t]=r|0,rh.bytes=t-n+1,e}var Wy=zc,jy=128,th=127;function zc(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw zc.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&th)<<o:(i&th)*Math.pow(2,o),o+=7}while(i>=jy);return zc.bytes=s-n,t}var Gy=Math.pow(2,7),Yy=Math.pow(2,14),Xy=Math.pow(2,21),Zy=Math.pow(2,28),Qy=Math.pow(2,35),Jy=Math.pow(2,42),eb=Math.pow(2,49),tb=Math.pow(2,56),rb=Math.pow(2,63),nb=function(r){return r<Gy?1:r<Yy?2:r<Xy?3:r<Zy?4:r<Qy?5:r<Jy?6:r<eb?7:r<tb?8:r<rb?9:10},ob={encode:$y,decode:Wy,encodingLength:nb},sb=ob,so=sb;function io(r,e=0){return[so.decode(r,e),so.decode.bytes]}function Zr(r,e,t=0){return so.encode(r,e,t),e}function Qr(r){return so.encodingLength(r)}function en(r,e){let t=e.byteLength,n=Qr(r),o=n+Qr(t),s=new Uint8Array(o+t);return Zr(r,s,0),Zr(t,s,n),s.set(e,o),new Jr(r,t,e,s)}function nh(r){let e=_t(r),[t,n]=io(e),[o,s]=io(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Jr(t,o,i,e)}function oh(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&jd(r.bytes,t.bytes)}}var Jr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ar(n),this.bytes=ar(o)}};var sh=0,ib="identity",ih=_t;function ab(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 en(sh,ih(r))}var cb={code:sh,name:ib,encode:ih,digest:ab};var jc={};ee(jc,{sha256:()=>lb,sha512:()=>fb});var ub=20;function Wc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Hc(r,e,t,n,o)}var Hc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??ub,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?ah(n,this.code,t?.truncate):n.then(o=>ah(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ah(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 en(e,r)}function uh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var lb=Wc({name:"sha2-256",code:18,encode:uh("SHA-256")}),fb=Wc({name:"sha2-512",code:19,encode:uh("SHA-512")});function lh(r,e){let{bytes:t,version:n}=r;return n===0?hb(t,Gc(r),e??dt.encoder):pb(t,Gc(r),e??Xr.encoder)}var fh=new WeakMap;function Gc(r){let e=fh.get(r);if(e==null){let t=new Map;return fh.set(r,t),t}return e}var Rs=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ar(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==co)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==mb)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=en(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&&oh(e.multihash,n.multihash)}toString(e){return lh(this,e)}toJSON(){return{"/":lh(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??dh(n,o,s.bytes))}else if(t[gb]===!0){let{version:n,multihash:o,code:s}=t,i=nh(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!==co)throw new Error(`Version 0 CID must use dag-pb (code: ${co}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=dh(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,co,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=_t(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 Jr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=io(e.subarray(t));return t+=d,f},o=n(),s=co;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=db(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 Gc(s).set(n,e),s}};function db(r,e){switch(r[0]){case"Q":{let t=e??dt;return[dt.prefix,t.decode(`${dt.prefix}${r}`)]}case dt.prefix:{let t=e??dt;return[dt.prefix,t.decode(r)]}case Xr.prefix:{let t=e??Xr;return[Xr.prefix,t.decode(r)]}case oo.prefix:{let t=e??oo;return[oo.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 hb(r,e,t){let{prefix:n}=t;if(n!==dt.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 pb(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 co=112,mb=18;function dh(r,e,t){let n=Qr(r),o=n+Qr(e),s=new Uint8Array(o+t.byteLength);return Zr(r,s,0),Zr(e,s,n),s.set(t,o),s}var gb=Symbol.for("@ipld/js-cid/CID");var Yc={...$c,...Nc,...qc,...Rc,...Oc,...Fc,...Bc,...Uc,...Kc,...Mc},oS={...jc,...Vc};function qe(r=0){return new Uint8Array(r)}function Os(r=0){return new Uint8Array(r)}function ph(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var hh=ph("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xc=ph("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=Os(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),yb={utf8:hh,"utf-8":hh,hex:Yc.base16,latin1:Xc,ascii:Xc,binary:Xc,...Yc},Ns=yb;function M(r,e="utf8"){let t=Ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function H(r,e="utf8"){let t=Ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bb=parseInt("11111",2),Zc=parseInt("10000000",2),wb=parseInt("01111111",2),mh={0:uo,1:uo,2:xb,3:Sb,4:Ab,5:vb,6:Eb,16:uo,22:uo,48:uo};function Ct(r,e={offset:0}){let t=r[e.offset]&bb;if(e.offset++,mh[t]!=null)return mh[t](r,e);throw new Error("No decoder for tag "+t)}function lo(r,e){let t=0;if((r[e.offset]&Zc)===Zc){let n=r[e.offset]&wb,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 uo(r,e){lo(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ct(r,e);if(n===null)break;t.push(n)}return t}function xb(r,e){let t=lo(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 Eb(r,e){let t=lo(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 u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function vb(r,e){return e.offset++,null}function Sb(r,e){let t=lo(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 Ab(r,e){let t=lo(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function _b(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 Ms(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=_b(r.byteLength);return new Q(Uint8Array.from([e.byteLength|Zc]),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]),Ms(e),e)}function fo(r){let e=Uint8Array.from([0]),t=new Q(e,r);return new Q(Uint8Array.from([3]),Ms(t),t)}function gh(r){return new Q(Uint8Array.from([4]),Ms(r),r)}function et(r,e=48){let t=new Q;for(let n of r)t.append(n);return new Q(Uint8Array.from([e]),Ms(t),t)}var Cb=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ib=Uint8Array.from([6,5,43,129,4,0,34]),Tb=Uint8Array.from([6,5,43,129,4,0,35]),Lb={ext:!0,kty:"EC",crv:"P-256"},Db={ext:!0,kty:"EC",crv:"P-384"},Pb={ext:!0,kty:"EC",crv:"P-521"},Qc=32,Jc=48,eu=66;function tu(r){let e=Ct(r);return yh(e)}function yh(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Qc*2+1)return n=H(e.subarray(t,t+Qc),"base64url"),o=H(e.subarray(t+Qc),"base64url"),new cr({...Lb,key_ops:["verify"],x:n,y:o});if(e.byteLength===Jc*2+1)return n=H(e.subarray(t,t+Jc),"base64url"),o=H(e.subarray(t+Jc),"base64url"),new cr({...Db,key_ops:["verify"],x:n,y:o});if(e.byteLength===eu*2+1)return n=H(e.subarray(t,t+eu),"base64url"),o=H(e.subarray(t+eu),"base64url"),new cr({...Pb,key_ops:["verify"],x:n,y:o});throw new k(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function bh(r){return et([Pe(Uint8Array.from([1])),gh(M(r.d??"","base64url")),et([xh(r.crv)],160),et([fo(new Q(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function wh(r){return et([Pe(Uint8Array.from([1])),et([xh(r.crv)],160),et([fo(new Q(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function xh(r){if(r==="P-256")return Cb;if(r==="P-384")return Ib;if(r==="P-521")return Tb;throw new k(`Invalid curve ${r}`)}async function Eh(r="P-256"){let e=await qd(r);return new Fs(e.privateKey)}var cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=wh(this.jwk)),this._raw}toMultihash(){return Je.digest(Ye(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}async verify(e,t,n){return zd(this.jwk,t,e,n)}},Fs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new cr({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=bh(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}async sign(e,t){return $d(this.jwk,e,t)}};function ru(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Vt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function $e(r,e,t=""){let n=ru(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}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function Bs(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Vt(r.outputLen),Vt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tn(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 Us(r,e){$e(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Tt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ks(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function tt(r,e){return r<<32-e|r>>>e}var Sh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kb=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function qs(r){if($e(r),Sh)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=kb[r[t]];return e}var It={_0:48,_9:57,A:65,F:70,a:97,f:102};function vh(r){if(r>=It._0&&r<=It._9)return r-It._0;if(r>=It.A&&r<=It.F)return r-(It.A-10);if(r>=It.a&&r<=It.f)return r-(It.a-10)}function ho(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sh)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=vh(r.charCodeAt(s)),a=vh(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function nu(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$e(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 ou(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function $s(r=32){Vt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var su=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ah(r,e,t){return r&e^~r&t}function _h(r,e,t){return r&e^r&t^e&t}var po=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ks(this.buffer)}update(e){tn(this),$e(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=Ks(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){tn(this),Us(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Tt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ks(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zs=BigInt(4294967295),Ch=BigInt(32);function Rb(r,e=!1){return e?{h:Number(r&zs),l:Number(r>>Ch&zs)}:{h:Number(r>>Ch&zs)|0,l:Number(r&zs)|0}}function Ih(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}=Rb(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var iu=(r,e,t)=>r>>>t,au=(r,e,t)=>r<<32-t|e>>>t,ur=(r,e,t)=>r>>>t|e<<32-t,lr=(r,e,t)=>r<<32-t|e>>>t,mo=(r,e,t)=>r<<64-t|e>>>t-32,go=(r,e,t)=>r>>>t-32|e<<64-t;function ht(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Th=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Lh=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Dh=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ph=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,kh=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Rh=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Nb=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]),Ht=new Uint32Array(64),cu=class extends po{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Ht[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Ht[f-15],h=Ht[f-2],p=tt(d,7)^tt(d,18)^d>>>3,g=tt(h,17)^tt(h,19)^h>>>10;Ht[f]=g+Ht[f-7]+p+Ht[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=tt(a,6)^tt(a,11)^tt(a,25),h=l+d+Ah(a,c,u)+Nb[f]+Ht[f]|0,g=(tt(n,2)^tt(n,13)^tt(n,22))+_h(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Tt(Ht)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Tt(this.buffer)}},uu=class extends cu{A=Lt[0]|0;B=Lt[1]|0;C=Lt[2]|0;D=Lt[3]|0;E=Lt[4]|0;F=Lt[5]|0;G=Lt[6]|0;H=Lt[7]|0;constructor(){super(32)}};var Oh=Ih(["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))),Mb=Oh[0],Fb=Oh[1],Wt=new Uint32Array(80),jt=new Uint32Array(80),lu=class extends po{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:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,t){for(let v=0;v<16;v++,t+=4)Wt[v]=e.getUint32(t),jt[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let T=Wt[v-15]|0,I=jt[v-15]|0,N=ur(T,I,1)^ur(T,I,8)^iu(T,I,7),L=lr(T,I,1)^lr(T,I,8)^au(T,I,7),_=Wt[v-2]|0,B=jt[v-2]|0,Y=ur(_,B,19)^mo(_,B,61)^iu(_,B,6),K=lr(_,B,19)^go(_,B,61)^au(_,B,6),b=Dh(L,K,jt[v-7],jt[v-16]),x=Ph(b,N,Y,Wt[v-7],Wt[v-16]);Wt[v]=x|0,jt[v]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:y,Hl:w}=this;for(let v=0;v<80;v++){let T=ur(f,d,14)^ur(f,d,18)^mo(f,d,41),I=lr(f,d,14)^lr(f,d,18)^go(f,d,41),N=f&h^~f&g,L=d&p^~d&m,_=kh(w,I,L,Fb[v],jt[v]),B=Rh(_,y,T,N,Mb[v],Wt[v]),Y=_|0,K=ur(n,o,28)^mo(n,o,34)^mo(n,o,39),b=lr(n,o,28)^go(n,o,34)^go(n,o,39),x=n&s^n&a^s&a,A=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ht(u|0,l|0,B|0,Y|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let S=Th(Y,b,A);n=Lh(S,B,K,x),o=S|0}({h:n,l:o}=ht(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ht(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ht(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ht(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ht(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ht(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=ht(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,u,l,f,d,h,p,g,m,y,w)}roundClean(){Tt(Wt,jt)}destroy(){this.destroyed=!0,Tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},fu=class extends lu{Ah=Ee[0]|0;Al=Ee[1]|0;Bh=Ee[2]|0;Bl=Ee[3]|0;Ch=Ee[4]|0;Cl=Ee[5]|0;Dh=Ee[6]|0;Dl=Ee[7]|0;Eh=Ee[8]|0;El=Ee[9]|0;Fh=Ee[10]|0;Fl=Ee[11]|0;Gh=Ee[12]|0;Gl=Ee[13]|0;Hh=Ee[14]|0;Hl=Ee[15]|0;constructor(){super(64)}};var rn=ou(()=>new uu,su(1));var Vs=ou(()=>new fu,su(3));var V=(r,e,t)=>$e(r,e,t),hu=Vt,nn=qs,pe=(...r)=>nu(...r),on=r=>ho(r),fr=ru,yo=r=>$s(r),Ws=BigInt(0),du=BigInt(1);function rt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function js(r){if(typeof r=="bigint"){if(!Hs(r))throw new RangeError("positive bigint expected, got "+r)}else hu(r);return r}function nt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function bo(r){let e=js(r).toString(16);return e.length&1?"0"+e:e}function Nh(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Ws:BigInt("0x"+r)}function dr(r){return Nh(qs(r))}function pt(r){return Nh(qs(wo($e(r)).reverse()))}function Gs(r,e){if(Vt(e),e===0)throw new RangeError("zero length");r=js(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return ho(t.padStart(e*2,"0"))}function pu(r,e){return Gs(r,e).reverse()}function Mh(r,e){if(r=V(r),e=V(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function wo(r){return Uint8Array.from(V(r))}function Ys(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Hs=r=>typeof r=="bigint"&&Ws<=r;function Bb(r,e,t){return Hs(r)&&Hs(e)&&Hs(t)&&e<=r&&r<t}function sn(r,e,t,n){if(!Bb(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function an(r){if(r<Ws)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Ws;r>>=du,e+=1);return e}var xo=r=>(du<<BigInt(r))-du;function Fh(r,e,t){if(Vt(r,"hashLen"),Vt(e,"qByteLen"),typeof t!="function")throw new TypeError("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),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...m)=>t(u,pe(c,...m)),h=(m=o)=>{u=d(s,m),c=d(),m.length!==0&&(u=d(i,m),c=d())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,y=[];for(;m<e;){c=d();let w=c.slice();y.push(w),m+=c.length}return pe(...y)};return(m,y)=>{f(),h(m);let w;for(;(w=y(p()))===void 0;)h();return f(),w}}function ot(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var mu=()=>{throw new Error("not implemented")};var ve=BigInt(0),ue=BigInt(1),hr=BigInt(2),qh=BigInt(3),$h=BigInt(4),zh=BigInt(5),Ub=BigInt(7),Vh=BigInt(8),Kb=BigInt(9),Hh=BigInt(16);function de(r,e){if(e<=ve)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ve?t:e+t}function se(r,e,t){if(e<ve)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >ve;)n*=n,n%=t;return n}function Bh(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=de(r,e),n=e,o=ve,s=ue,i=ue,a=ve;for(;t!==ve;){let u=n/t,l=n-t*u,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==ue)throw new Error("invert: does not exist");return de(o,e)}function gu(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Wh(r,e){let t=r,n=(t.ORDER+ue)/$h,o=t.pow(e,n);return gu(t,o,e),o}function qb(r,e){let t=r,n=(t.ORDER-zh)/Vh,o=t.mul(e,hr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,hr),s),c=t.mul(i,t.sub(a,t.ONE));return gu(t,c,e),c}function $b(r){let e=cn(r),t=jh(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Ub)/Hh;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),h=u.mul(l,s),p=u.eql(u.sqr(f),c),g=u.eql(u.sqr(d),c);l=u.cmov(l,f,p),f=u.cmov(h,d,g);let m=u.eql(u.sqr(f),c),y=u.cmov(l,f,m);return gu(u,y,c),y})}function jh(r){if(r<qh)throw new Error("sqrt is not defined for small field");let e=r-ue,t=0;for(;e%hr===ve;)e/=hr,t++;let n=hr,o=cn(r);for(;Uh(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Wh;let s=o.pow(n,e),i=(e+ue)/hr;return function(c,u){let l=c;if(l.is0(u))return u;if(Uh(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),p=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let g=1,m=l.sqr(h);for(;!l.eql(m,l.ONE);)if(g++,m=l.sqr(m),g===f)throw new Error("Cannot find square root");let y=ue<<BigInt(f-g-1),w=l.pow(d,y);f=g,d=l.sqr(w),h=l.mul(h,d),p=l.mul(p,w)}return p}}function zb(r){return r%$h===qh?Wh:r%Vh===zh?qb:r%Hh===Kb?$b(r):jh(r)}var Dt=(r,e)=>(de(r,e)&ue)===ue,Vb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yu(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Vb.reduce((n,o)=>(n[o]="function",n),e);if(ot(r,t),nt(r.BYTES,"BYTES"),nt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ue)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Hb(r,e,t){let n=r;if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return n.ONE;if(t===ue)return e;let o=n.ONE,s=e;for(;t>ve;)t&ue&&(o=n.mul(o,s)),s=n.sqr(s),t>>=ue;return o}function Eo(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function Uh(r,e){let t=r,n=(t.ORDER-ue)/hr,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Wb(r,e){if(e!==void 0&&hu(e),r<=ve)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=an(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Kh=new WeakMap,Xs=class{ORDER;BITS;BYTES;isLE;ZERO=ve;ONE=ue;_lengths;_mod;constructor(e,t={}){if(e<=ue)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Wb(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ve<=e&&e<this.ORDER}is0(e){return e===ve}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ue)===ue}neg(e){return de(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return de(e*e,this.ORDER)}add(e,t){return de(e+t,this.ORDER)}sub(e,t){return de(e-t,this.ORDER)}mul(e,t){return de(e*t,this.ORDER)}pow(e,t){return Hb(this,e,t)}div(e,t){return de(e*Bh(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 Bh(e,this.ORDER)}sqrt(e){let t=Kh.get(this);return t||Kh.set(this,t=zb(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?pu(e,this.BYTES):Gs(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?pt(e):dr(e);if(a&&(c=de(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Eo(this,e)}cmov(e,t,n){return rt(n,"condition"),n?t:e}};Object.freeze(Xs.prototype);function cn(r,e={}){return new Xs(r,e)}function Gh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ue)throw new Error("field order must be greater than 1");let e=an(r-ue);return Math.ceil(e/8)}function bu(r){let e=Gh(r);return e+Math.ceil(e/2)}function wu(r,e,t=!1){V(r);let n=r.length,o=Gh(e),s=Math.max(bu(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?pt(r):dr(r),a=de(i,e-ue)+ue;return t?pu(a,o):Gs(a,o)}var un=BigInt(0),pr=BigInt(1);function vo(r,e){let t=e.negate();return r?t:e}function mr(r,e){let t=Eo(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Qh(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function xu(r,e){Qh(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=xo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Yh(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+=pr);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var Eu=new WeakMap,Jh=new WeakMap;function vu(r){return Jh.get(r)||1}function Xh(r){if(r!==un)throw new Error("invalid wNAF")}var ln=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>un;)t&pr&&(n=n.add(o)),o=o.double(),t>>=pr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=xu(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)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=xu(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=Yh(n,a,i);n=c,l?s=s.add(vo(d,t[h])):o=o.add(vo(f,t[u]))}return Xh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=xu(e,this.bits);for(let i=0;i<s.windows&&n!==un;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Yh(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return Xh(n),o}getPrecomputes(e,t,n){let o=Eu.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Eu.set(t,o))),o}cached(e,t,n){let o=vu(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=vu(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Qh(t,this.bits),Jh.set(e,t),Eu.delete(e)}hasCache(e){return vu(e)!==1}};function ep(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>un||n>un;)t&pr&&(s=s.add(o)),n&pr&&(i=i.add(o)),o=o.double(),t>>=pr,n>>=pr;return{p1:s,p2:i}}function Zh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return yu(e),e}else return cn(r,{isLE:t})}function Zs(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 u=e[c];if(!(typeof u=="bigint"&&u>un))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Zh(e.p,t.Fp,n),s=Zh(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 Qs(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Gt=BigInt(0),ye=BigInt(1),Su=BigInt(2),jb=BigInt(8);function Gb(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 tp(r,e={}){let t=e,n=Zs("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;ot(t,{},{uvRatio:"function"});let c=Su<<BigInt(s.BYTES*8)-ye,u=g=>o.create(g),l=t.uvRatio===void 0?(g,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,m))}}catch{return{isValid:!1,value:Gt}}}:t.uvRatio;if(!Gb(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,m,y=!1){let w=y?ye:Gt;return sn("coordinate "+g,m,w,c),m}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ye,u(i.Gx*i.Gy));static ZERO=new h(Gt,ye,ye,Gt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,y,w,v){this.X=f("x",m),this.Y=f("y",y),this.Z=f("z",w,!0),this.T=f("t",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:y,y:w}=m||{};return f("x",y),f("y",w),new h(y,w,ye,u(y*w))}static fromBytes(m,y=!1){let w=o.BYTES,{a:v,d:T}=i;m=wo(V(m,w,"point")),rt(y,"zip215");let I=wo(m),N=m[w-1];I[w-1]=N&-129;let L=pt(I),_=y?c:o.ORDER;sn("point.y",L,Gt,_);let B=u(L*L),Y=u(B-ye),K=u(T*B-v),{isValid:b,value:x}=l(Y,K);if(!b)throw new Error("bad point: invalid y coordinate");let A=(x&ye)===ye,S=(N&128)!==0;if(!y&&x===Gt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==A&&(x=u(-x)),h.fromAffine({x,y:L})}static fromHex(m,y=!1){return h.fromBytes(on(m),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return p.createCache(this,m),y||this.multiply(Su),this}assertValidity(){let m=this,{a:y,d:w}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:v,Y:T,Z:I,T:N}=m,L=u(v*v),_=u(T*T),B=u(I*I),Y=u(B*B),K=u(L*y),b=u(B*u(K+_)),x=u(Y+u(w*u(L*_)));if(b!==x)throw new Error("bad point: equation left != right (1)");let A=u(v*T),S=u(I*N);if(A!==S)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:y,Y:w,Z:v}=this,{X:T,Y:I,Z:N}=m,L=u(y*N),_=u(T*v),B=u(w*N),Y=u(I*v);return L===_&&B===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:m}=i,{X:y,Y:w,Z:v}=this,T=u(y*y),I=u(w*w),N=u(Su*u(v*v)),L=u(m*T),_=y+w,B=u(u(_*_)-T-I),Y=L+I,K=Y-N,b=L-I,x=u(B*K),A=u(Y*b),S=u(B*b),E=u(K*Y);return new h(x,A,E,S)}add(m){d(m);let{a:y,d:w}=i,{X:v,Y:T,Z:I,T:N}=this,{X:L,Y:_,Z:B,T:Y}=m,K=u(v*L),b=u(T*_),x=u(N*w*Y),A=u(I*B),S=u((v+T)*(L+_)-K-b),E=A-x,C=A+x,P=u(b-y*K),D=u(S*E),R=u(C*P),F=u(S*P),z=u(E*C);return new h(D,R,z,F)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:w}=p.cached(this,m,v=>mr(h,v));return mr(h,[y,w])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===Gt?h.ZERO:this.is0()||m===ye?this:p.unsafe(this,m,y=>mr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(m){let y=this,w=m,{X:v,Y:T,Z:I}=y,N=y.is0();w==null&&(w=N?jb:o.inv(I));let L=u(v*w),_=u(T*w),B=o.mul(I,w);if(N)return{x:Gt,y:ye};if(B!==ye)throw new Error("invZ was invalid");return{x:L,y:_}}clearCofactor(){return a===ye?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y}=this.toAffine(),w=o.toBytes(y);return w[w.length-1]|=m&ye?128:0,w}toHex(){return nn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new ln(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Js=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){mu()}static fromHex(e){mu()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return nn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function rp(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;ot(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(nt(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?yo:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,x,A)=>{if(rt(A,"phflag"),x.length||A)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(pt(b))}function g(b){let x=L.secretKey;V(b,L.secretKey,"secretKey");let A=V(n(b),2*x,"hashedSecretKey"),S=d(A.slice(0,x)),E=A.slice(x,2*x),C=p(S);return{head:S,prefix:E,scalar:C}}function m(b){let{head:x,prefix:A,scalar:S}=g(b),E=i.multiply(S),C=E.toBytes();return{head:x,prefix:A,scalar:S,point:E,pointBytes:C}}function y(b){return m(b).pointBytes}function w(b=Uint8Array.of(),...x){let A=pe(...x);return p(n(h(A,V(b,void 0,"context"),!!s)))}function v(b,x,A={}){b=V(b,void 0,"message"),s&&(b=s(b));let{prefix:S,scalar:E,pointBytes:C}=m(x),P=w(A.context,S,b),D=i.multiply(P).toBytes(),R=w(A.context,D,C,b),F=c.create(P+R*E);if(!c.isValid(F))throw new Error("sign failed: invalid s");let z=pe(D,c.toBytes(F));return V(z,L.signature,"result")}let T={zip215:o.zip215};function I(b,x,A,S=T){let{context:E}=S,C=S.zip215===void 0?!!T.zip215:S.zip215,P=L.signature;b=V(b,P,"signature"),x=V(x,void 0,"message"),A=V(A,L.publicKey,"publicKey"),C!==void 0&&rt(C,"zip215"),s&&(x=s(x));let D=P/2,R=b.subarray(0,D),F=pt(b.subarray(D,P)),z,G,q;try{z=r.fromBytes(A,C),G=r.fromBytes(R,C),q=i.multiplyUnsafe(F)}catch{return!1}if(!C&&z.isSmallOrder())return!1;let he=w(E,R,A,x);return G.add(z.multiplyUnsafe(he)).subtract(q).clearCofactor().is0()}let N=a.BYTES,L={secretKey:N,publicKey:N,signature:2*N,seed:N};function _(b){return b=b===void 0?f(L.seed):b,V(b,L.seed,"seed")}function B(b){return fr(b)&&b.length===L.secretKey}function Y(b,x){try{return!!r.fromBytes(b,x===void 0?T.zip215:x)}catch{return!1}}let K={getExtendedPublicKey:m,randomSecretKey:_,isValidSecretKey:B,isValidPublicKey:Y,toMontgomery(b){let{y:x}=r.fromBytes(b),A=L.publicKey,S=A===32;if(!S&&A!==57)throw new Error("only defined for 25519 and 448");let E=S?a.div(ye+x,ye-x):a.div(x-ye,x+ye);return a.toBytes(E)},toMontgomerySecret(b){let x=L.secretKey;V(b,x);let A=n(b.subarray(0,x));return d(A).subarray(0,x)}};return Object.freeze(L),Object.freeze(K),Object.freeze({keygen:Qs(_,y),getPublicKey:y,sign:v,verify:I,utils:K,Point:r,lengths:L})}function So(r,e){if(nt(r),nt(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Yb(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Xb(r){if(!fr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Ys(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Au(r,e,t,n){V(r),nt(t),e=Xb(e),e.length>255&&(e=n(pe(Ys("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=pe(e,So(e.length,1)),c=new Uint8Array(s),u=So(t,2),l=new Array(i),f=n(pe(c,r,u,So(0,1),a));l[0]=n(pe(f,So(1,1),a));for(let h=1;h<i;h++){let p=[Yb(f,l[h-1]),So(h+1,1),a];l[h]=n(pe(...p))}return pe(...l).slice(0,t)}var np="HashToScalar-";var Zb=BigInt(0),Pt=BigInt(1),op=BigInt(2);var Qb=BigInt(5),Jb=BigInt(8),fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Tu={p:fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ew(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=fn,a=r*r%s*r%s,c=se(a,op,s)*a%s,u=se(c,Pt,s)*r%s,l=se(u,Qb,s)*u%s,f=se(l,e,s)*l%s,d=se(f,t,s)*f%s,h=se(d,n,s)*d%s,p=se(h,o,s)*h%s,g=se(p,o,s)*h%s,m=se(g,e,s)*l%s;return{pow_p_5_8:se(m,op,s)*r%s,b2:a}}function tw(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var _u=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Lu(r,e){let t=fn,n=de(e*e*e,t),o=de(n*n*e,t),s=ew(r*o).pow_p_5_8,i=de(r*n*s,t),a=de(e*i*i,t),c=i,u=de(i*_u,t),l=a===r,f=a===de(-r,t),d=a===de(-r*_u,t);return l&&(i=c),(f||d)&&(i=u),Dt(i,t)&&(i=de(-i,t)),{isValid:l||f,value:i}}var Xt=tp(Tu,{uvRatio:Lu}),Yt=Xt.Fp,ap=Xt.Fn;function rw(r){return rp(Xt,Vs,Object.assign({adjustScalarBytes:tw,zip215:!0},r))}var Ao=rw({});var Cu=_u,nw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ow=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),sw=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),iw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),sp=r=>Lu(Pt,r),aw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Iu=r=>Yt.create(pt(r)&aw);function ip(r){let{d:e}=Tu,t=fn,n=y=>Yt.create(y),o=n(Cu*r*r),s=n((o+Pt)*sw),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=Lu(s,a),l=n(u*r);Dt(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let f=n(i*(o-Pt)*iw-a),d=u*u,h=n((u+u)*a),p=n(f*nw),g=n(Pt-d),m=n(Pt+d);return new Xt(n(h*m),n(g*p),n(p*m),n(h*g))}var Zt=class r extends Js{static BASE=new r(Xt.BASE);static ZERO=new r(Xt.ZERO);static Fp=Yt;static Fn=ap;constructor(e){super(e)}static fromAffine(e){return new r(Xt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){$e(e,32);let{a:t,d:n}=Tu,o=fn,s=T=>Yt.create(T),i=Iu(e);if(!Mh(Yt.toBytes(i),e)||Dt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Pt+t*a),u=s(Pt-t*a),l=s(c*c),f=s(u*u),d=s(t*n*l-f),{isValid:h,value:p}=sp(s(d*f)),g=s(p*u),m=s(p*g*d),y=s((i+i)*g);Dt(y,o)&&(y=s(-y));let w=s(c*m),v=s(y*w);if(!h||Dt(v,o)||w===Zb)throw new Error("invalid ristretto255 encoding 2");return new r(new Xt(y,w,Pt,v))}static fromHex(e){return r.fromBytes(ho(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=fn,i=m=>Yt.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=sp(i(a*u)),f=i(l*a),d=i(l*c),h=i(f*d*o),p;if(Dt(o*h,s)){let m=i(t*Cu),y=i(e*Cu);e=m,t=y,p=i(f*ow)}else p=d;Dt(e*h,s)&&(t=i(-t));let g=i((n-t)*p);return Dt(g,s)&&(g=i(-g)),Yt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>Yt.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Zt.BASE);Object.freeze(Zt.ZERO);Object.freeze(Zt.prototype);Object.freeze(Zt);var cw=Object.freeze({Point:Zt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Au(r,t,64,Vs);return cw.deriveToCurve(n)},hashToScalar(r,e={DST:np}){let t=Au(r,e.DST,64,Vs);return ap.create(pt(t))},deriveToCurve(r){$e(r,64);let e=Iu(r.subarray(0,32)),t=ip(e),n=Iu(r.subarray(32,64)),o=ip(n);return new Zt(t.add(o))}});var _o=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Co=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ei=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Be={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ei("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 ti=32,Io=64,Du=32;var dn,cp=(async()=>{try{return await Be.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function up(){let r=Ao.utils.randomSecretKey(),e=Ao.getPublicKey(r);return{privateKey:hw(r,e),publicKey:e}}async function uw(r,e){let t;r.length===Io?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:H(r.subarray(32),"base64url"),d:H(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Be.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Be.get().subtle.sign({name:"Ed25519"},o,Ge(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function lw(r,e){let t=r.subarray(0,Du);return Ao.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function lp(r,e){return dn==null&&(dn=await cp),dn?uw(r,e):lw(r,e)}async function fw(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Be.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Be.get().subtle.verify({name:"Ed25519"},n,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function dw(r,e,t){return Ao.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function fp(r,e,t){return dn==null&&(dn=await cp),dn?fw(r,e,t):dw(r,e,t)}function hw(r,e){let t=new Uint8Array(Io);for(let n=0;n<Du;n++)t[n]=r[n],t[Du+n]=e[n];return t}function pw(r){return r?.buffer instanceof ArrayBuffer}function hp(r){if(pw(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Pu(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Os(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return hp(t)}function hn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var To=class{type="Ed25519";raw;constructor(e){this.raw=ni(e,ti)}toMultihash(){return Je.digest(Ye(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=fp(this.raw,t,e);return hn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},ri=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ni(e,Io),this.publicKey=new To(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=lp(this.raw,e);return hn(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function ku(r){return r=ni(r,ti),new To(r)}async function pp(){let{privateKey:r,publicKey:e}=up();return new ri(r,e)}function ni(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new k(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function mp(r=0){return new Uint8Array(r)}var mw=Math.pow(2,7),gw=Math.pow(2,14),yw=Math.pow(2,21),Ru=Math.pow(2,28),Ou=Math.pow(2,35),Nu=Math.pow(2,42),Mu=Math.pow(2,49),X=128,_e=127;function be(r){if(r<mw)return 1;if(r<gw)return 2;if(r<yw)return 3;if(r<Ru)return 4;if(r<Ou)return 5;if(r<Nu)return 6;if(r<Mu)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pn(r,e,t=0){switch(be(r)){case 8:e[t++]=r&255|X,r/=128;case 7:e[t++]=r&255|X,r/=128;case 6:e[t++]=r&255|X,r/=128;case 5:e[t++]=r&255|X,r/=128;case 4:e[t++]=r&255|X,r>>>=7;case 3:e[t++]=r&255|X,r>>>=7;case 2:e[t++]=r&255|X,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function bw(r,e,t=0){switch(be(r)){case 8:e.set(t++,r&255|X),r/=128;case 7:e.set(t++,r&255|X),r/=128;case 6:e.set(t++,r&255|X),r/=128;case 5:e.set(t++,r&255|X),r/=128;case 4:e.set(t++,r&255|X),r>>>=7;case 3:e.set(t++,r&255|X),r>>>=7;case 2:e.set(t++,r&255|X),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fu(r,e){let t=r[e],n=0;if(n+=t&_e,t<X||(t=r[e+1],n+=(t&_e)<<7,t<X)||(t=r[e+2],n+=(t&_e)<<14,t<X)||(t=r[e+3],n+=(t&_e)<<21,t<X)||(t=r[e+4],n+=(t&_e)*Ru,t<X)||(t=r[e+5],n+=(t&_e)*Ou,t<X)||(t=r[e+6],n+=(t&_e)*Nu,t<X)||(t=r[e+7],n+=(t&_e)*Mu,t<X))return n;throw new RangeError("Could not decode varint")}function ww(r,e){let t=r.get(e),n=0;if(n+=t&_e,t<X||(t=r.get(e+1),n+=(t&_e)<<7,t<X)||(t=r.get(e+2),n+=(t&_e)<<14,t<X)||(t=r.get(e+3),n+=(t&_e)<<21,t<X)||(t=r.get(e+4),n+=(t&_e)*Ru,t<X)||(t=r.get(e+5),n+=(t&_e)*Ou,t<X)||(t=r.get(e+6),n+=(t&_e)*Nu,t<X)||(t=r.get(e+7),n+=(t&_e)*Mu,t<X))return n;throw new RangeError("Could not decode varint")}function Qt(r,e,t=0){return e==null&&(e=mp(be(r))),e instanceof Uint8Array?pn(r,e,t):bw(r,e,t)}function gr(r,e=0){return r instanceof Uint8Array?Fu(r,e):ww(r,e)}var Bu=new Float32Array([-0]),Jt=new Uint8Array(Bu.buffer);function gp(r,e,t){Bu[0]=r,e[t]=Jt[0],e[t+1]=Jt[1],e[t+2]=Jt[2],e[t+3]=Jt[3]}function yp(r,e){return Jt[0]=r[e],Jt[1]=r[e+1],Jt[2]=r[e+2],Jt[3]=r[e+3],Bu[0]}var Uu=new Float64Array([-0]),Ce=new Uint8Array(Uu.buffer);function bp(r,e,t){Uu[0]=r,e[t]=Ce[0],e[t+1]=Ce[1],e[t+2]=Ce[2],e[t+3]=Ce[3],e[t+4]=Ce[4],e[t+5]=Ce[5],e[t+6]=Ce[6],e[t+7]=Ce[7]}function wp(r,e){return Ce[0]=r[e],Ce[1]=r[e+1],Ce[2]=r[e+2],Ce[3]=r[e+3],Ce[4]=r[e+4],Ce[5]=r[e+5],Ce[6]=r[e+6],Ce[7]=r[e+7],Uu[0]}var xw=BigInt(Number.MAX_SAFE_INTEGER),Ew=BigInt(Number.MIN_SAFE_INTEGER),ze=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 yr;if(e<xw&&e>Ew)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>xp&&(o=0n,++n>xp&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return yr;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):yr}},yr=new ze(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var xp=4294967296n;function Ep(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 vp(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 Ku(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 st(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function oi(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var qu=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,st(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 st(this,4);return oi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw st(this,4);return oi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw st(this,4);let e=yp(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw st(this,4);let e=wp(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 st(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return vp(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw st(this,e);this.pos+=e}else do if(this.pos>=this.len)throw st(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 ze(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 st(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 st(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 st(this,8);let e=oi(this.buf,this.pos+=4),t=oi(this.buf,this.pos+=4);return new ze(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=Fu(this.buf,this.pos);return this.pos+=be(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 Do(r){return new qu(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=Do(r);return e.decode(n,void 0,t)}function br(r=0){return new Uint8Array(r)}var $u={};ee($u,{base10:()=>vw});var vw=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var zu={};ee(zu,{base16:()=>Sw,base16upper:()=>Aw});var Sw=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Aw=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vu={};ee(Vu,{base2:()=>_w});var _w=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hu={};ee(Hu,{base256emoji:()=>Dw});var Ap=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}"),Cw=Ap.reduce((r,e,t)=>(r[t]=e,r),[]),Iw=Ap.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Tw(r){return r.reduce((e,t)=>(e+=Cw[t],e),"")}function Lw(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Iw[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Dw=Hr({prefix:"\u{1F680}",name:"base256emoji",encode:Tw,decode:Lw});var Gu={};ee(Gu,{base64:()=>Wu,base64pad:()=>Pw,base64url:()=>ju,base64urlpad:()=>kw});var Wu=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pw=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ju=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kw=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Yu={};ee(Yu,{base8:()=>Rw});var Rw=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Xu={};ee(Xu,{identity:()=>Ow});var Ow=Hr({prefix:"\0",name:"identity",encode:r=>Td(r),decode:r=>Id(r)});var QA=new TextEncoder,JA=new TextDecoder;var Ju={};ee(Ju,{sha256:()=>mn,sha512:()=>Bw});var Fw=20;function Qu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Zu(r,e,t,n,o)}var Zu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Fw,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?_p(n,this.code,t?.truncate):n.then(o=>_p(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _p(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 ft(e,r)}function Ip(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var mn=Qu({name:"sha2-256",code:18,encode:Ip("SHA-256")}),Bw=Qu({name:"sha2-512",code:19,encode:Ip("SHA-512")});var Ue={...Xu,...Vu,...Yu,...$u,...zu,...Sc,...Ac,...vc,...Gu,...Hu},f_={...Ju,...Ic};function Lp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Tp=Lp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),el=Lp("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=br(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Uw={utf8:Tp,"utf-8":Tp,hex:Ue.base16,latin1:el,ascii:el,binary:el,...Ue},Dp=Uw;function Pp(r,e="utf8"){let t=Dp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function tl(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return br(i);o+i>e&&(n=br(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var wr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function rl(){}var ol=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Kw=tl();function qw(r){return globalThis.Buffer!=null?br(r):Kw(r)}var ko=class{len;head;tail;states;constructor(){this.len=0,this.head=new wr(rl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new sl((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(si,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ze.fromBigInt(e);return this._push(si,t.length(),t)}uint64Number(e){return this._push(pn,be(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=ze.fromBigInt(e).zzEncode();return this._push(si,t.length(),t)}sint64Number(e){let t=ze.fromNumber(e).zzEncode();return this._push(si,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nl,1,e?1:0)}fixed32(e){return this._push(Po,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ze.fromBigInt(e);return this._push(Po,4,t.lo)._push(Po,4,t.hi)}fixed64Number(e){let t=ze.fromNumber(e);return this._push(Po,4,t.lo)._push(Po,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(gp,4,e)}double(e){return this._push(bp,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(nl,1,0):this.uint32(t)._push(zw,t,e)}string(e){let t=Ep(e);return t!==0?this.uint32(t)._push(Ku,t,e):this._push(nl,1,0)}fork(){return this.states=new ol(this),this.head=this.tail=new wr(rl,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 wr(rl,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=qw(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function nl(r,e,t){e[t]=r&255}function $w(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var sl=class extends wr{next;constructor(e,t){super($w,e,t),this.next=void 0}};function si(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 Po(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 zw(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ko.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Vw,e,r),this},ko.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Hw,e,r),this});function Vw(r,e,t){e.set(r,t)}function Hw(r,e,t){r.length<40?Ku(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Pp(r),t)}function il(){return new ko}function Re(r,e){let t=il();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Oe(r,e,t){let n=Do(r);yield*e.stream(n,void 0,"$",t)}var ii={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ai(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function al(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return ai("enum",ii.VARINT,t,n,o)}function Ne(r,e,t){return ai("message",ii.LENGTH_DELIMITED,r,e,t)}var Xe=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ro=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ie;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ie||(ie={}));var cl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(cl||(cl={}));(function(r){r.codec=()=>al(cl)})(ie||(ie={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(mt||(mt={}));var ul;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(ul||(ul={}));function gn(r){if(isNaN(r)||r<=0)throw new k("random bytes length must be a Number bigger than 0");return $s(r)}var No={};ee(No,{MAX_RSA_KEY_SIZE:()=>ll,generateRSAKeyPair:()=>wl,jwkToJWKKeyPair:()=>Mp,jwkToPkcs1:()=>Yw,jwkToPkix:()=>pl,jwkToRSAPrivateKey:()=>bl,pkcs1MessageToJwk:()=>dl,pkcs1MessageToRSAPrivateKey:()=>ml,pkcs1ToJwk:()=>Gw,pkcs1ToRSAPrivateKey:()=>Np,pkixMessageToJwk:()=>hl,pkixMessageToRSAPublicKey:()=>yl,pkixToJwk:()=>Xw,pkixToRSAPublicKey:()=>gl});var yn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=No.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return fe.createV1(114,this._multihash)}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}verify(e,t,n){return Op(this.jwk,t,e,n)}},Oo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=No.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}sign(e,t){return Rp(this.jwk,e,t)}};var ll=8192,fl=18,Ww=1062,jw=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Gw(r){let e=Ct(r);return dl(e)}function dl(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function Yw(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 k("JWK was missing components");return et([Pe(Uint8Array.from([0])),Pe(M(r.n,"base64url")),Pe(M(r.e,"base64url")),Pe(M(r.d,"base64url")),Pe(M(r.p,"base64url")),Pe(M(r.q,"base64url")),Pe(M(r.dp,"base64url")),Pe(M(r.dq,"base64url")),Pe(M(r.qi,"base64url"))]).subarray()}function Xw(r){let e=Ct(r,{offset:0});return hl(e)}function hl(r){let e=Ct(r[1],{offset:0});return{kty:"RSA",n:H(e[0],"base64url"),e:H(e[1],"base64url")}}function pl(r){if(r.n==null||r.e==null)throw new k("JWK was missing components");return et([jw,fo(et([Pe(M(r.n,"base64url")),Pe(M(r.e,"base64url"))]))]).subarray()}function Np(r){let e=Ct(r);return ml(e)}function ml(r){let e=dl(r);return bl(e)}function gl(r,e){if(r.byteLength>=Ww)throw new $r("Key size is too large");let t=Ct(r,{offset:0});return yl(t,r,e)}function yl(r,e,t){let n=hl(r);if(t==null){let o=rn(mt.encode({Type:ie.RSA,Data:e}));t=ft(fl,o)}return new yn(n,t)}function bl(r){if(Bp(r)>ll)throw new k("Key size is too large");let e=Mp(r),t=rn(mt.encode({Type:ie.RSA,Data:pl(e.publicKey)})),n=ft(fl,t);return new Oo(e.privateKey,new yn(e.publicKey,n))}async function wl(r){if(r>ll)throw new k("Key size is too large");let e=await Fp(r),t=rn(mt.encode({Type:ie.RSA,Data:pl(e.publicKey)})),n=ft(fl,t);return new Oo(e.privateKey,new yn(e.publicKey,n))}function Mp(r){if(r==null)throw new k("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Fp(r,e){let t=await Be.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 Zw(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Rp(r,e,t){let n=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Be.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ge(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Op(r,e,t,n){let o=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Be.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function Zw(r,e){if(r.privateKey==null||r.publicKey==null)throw new k("Private and public key are required");let t=await Promise.all([Be.get().subtle.exportKey("jwk",r.privateKey),Be.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Bp(r){if(r.kty!=="RSA")throw new k("invalid key type");if(r.n==null)throw new k("invalid key modulus");return M(r.n,"base64url").length*8}var ci=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Bs(e),$e(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),Tt(o)}update(e){return tn(this),this.iHash.update(e),this}digestInto(e){tn(this),Us(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Up=(()=>{let r=((e,t,n)=>new ci(e,t).update(n).digest());return r.create=(e,t)=>new ci(e,t),r})();var Kp=(r,e)=>(r+(r>=0?e:-e)/qp)/e;function Qw(r,e,t){sn("scalar",r,gt,t);let[[n,o],[s,i]]=e,a=Kp(i*r,t),c=Kp(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<gt,d=l<gt;f&&(u=-u),d&&(l=-l);let h=xo(Math.ceil(an(t)/2))+er;if(u<gt||u>=h||l<gt||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function El(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function xl(r,e){ot(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return rt(t.lowS,"lowS"),rt(t.prehash,"prehash"),t.format!==void 0&&El(t.format),t}var vl=class extends Error{constructor(e=""){super(e)}},it={Err:vl,_tlv:{encode:(r,e)=>{let{Err:t}=it;if(nt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=bo(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?bo(o.length/2|128):"";return bo(r)+s+o+e},decode(r,e){let{Err:t}=it;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=it;if(js(r),r<gt)throw new e("integer: negative integers are not allowed");let t=bo(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}=it;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return dr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=it,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:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=it,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(it._tlv);Object.freeze(it._int);Object.freeze(it);var gt=BigInt(0),er=BigInt(1),qp=BigInt(2),ui=BigInt(3),Jw=BigInt(4);function $p(r,e={}){let t=Zs("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;ot(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=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=Vp(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(K,b,x){if(u&&b.is0())return Uint8Array.of(0);let{x:A,y:S}=b.toAffine(),E=n.toBytes(A);if(rt(x,"isCompressed"),x){f();let C=!n.isOdd(S);return pe(zp(C),E)}else return pe(Uint8Array.of(4),E,n.toBytes(S))}function h(K){V(K,void 0,"Point");let{publicKey:b,publicKeyUncompressed:x}=l,A=K.length,S=K[0],E=K.subarray(1);if(u&&A===1&&S===0)return{x:n.ZERO,y:n.ZERO};if(A===b&&(S===2||S===3)){let C=n.fromBytes(E);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let P=m(C),D;try{D=n.sqrt(P)}catch(z){let G=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();let R=n.isOdd(D);return(S&1)===1!==R&&(D=n.neg(D)),{x:C,y:D}}else if(A===x&&S===4){let C=n.BYTES,P=n.fromBytes(E.subarray(0,C)),D=n.fromBytes(E.subarray(C,C*2));if(!y(P,D))throw new Error("bad point: is not on curve");return{x:P,y:D}}else throw new Error(`bad point: got length ${A}, expected compressed=${b} or uncompressed=${x}`)}let p=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function m(K){let b=n.sqr(K),x=n.mul(b,K);return n.add(n.add(x,n.mul(K,s.a)),s.b)}function y(K,b){let x=n.sqr(b),A=m(K);return n.eql(x,A)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,ui),Jw),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,v)))throw new Error("bad curve params: a or b");function T(K,b,x=!1){if(!n.isValid(b)||x&&n.is0(b))throw new Error(`bad point coordinate ${K}`);return b}function I(K){if(!(K instanceof _))throw new Error("Weierstrass Point expected")}function N(K){if(!c||!c.basises)throw new Error("no endo");return Qw(K,c.basises,o.ORDER)}function L(K,b,x,A,S){return x=new _(n.mul(x.X,K),x.Y,x.Z),b=vo(A,b),x=vo(S,x),b.add(x)}class _{static BASE=new _(s.Gx,s.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,x,A){this.X=T("x",b),this.Y=T("y",x,!0),this.Z=T("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x,y:A}=b||{};if(!b||!n.isValid(x)||!n.isValid(A))throw new Error("invalid affine point");if(b instanceof _)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(A)?_.ZERO:new _(x,A,n.ONE)}static fromBytes(b){let x=_.fromAffine(g(V(b,void 0,"point")));return x.assertValidity(),x}static fromHex(b){return _.fromBytes(on(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,x=!0){return Y.createCache(this,b),x||this.multiply(ui),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x,y:A}=b.toAffine();if(!n.isValid(x)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(x,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){I(b);let{X:x,Y:A,Z:S}=this,{X:E,Y:C,Z:P}=b,D=n.eql(n.mul(x,P),n.mul(E,S)),R=n.eql(n.mul(A,P),n.mul(C,S));return D&&R}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:x}=s,A=n.mul(x,ui),{X:S,Y:E,Z:C}=this,P=n.ZERO,D=n.ZERO,R=n.ZERO,F=n.mul(S,S),z=n.mul(E,E),G=n.mul(C,C),q=n.mul(S,E);return q=n.add(q,q),R=n.mul(S,C),R=n.add(R,R),P=n.mul(b,R),D=n.mul(A,G),D=n.add(P,D),P=n.sub(z,D),D=n.add(z,D),D=n.mul(P,D),P=n.mul(q,P),R=n.mul(A,R),G=n.mul(b,G),q=n.sub(F,G),q=n.mul(b,q),q=n.add(q,R),R=n.add(F,F),F=n.add(R,F),F=n.add(F,G),F=n.mul(F,q),D=n.add(D,F),G=n.mul(E,C),G=n.add(G,G),F=n.mul(G,q),P=n.sub(P,F),R=n.mul(G,z),R=n.add(R,R),R=n.add(R,R),new _(P,D,R)}add(b){I(b);let{X:x,Y:A,Z:S}=this,{X:E,Y:C,Z:P}=b,D=n.ZERO,R=n.ZERO,F=n.ZERO,z=s.a,G=n.mul(s.b,ui),q=n.mul(x,E),he=n.mul(A,C),me=n.mul(S,P),ge=n.add(x,A),le=n.add(E,C);ge=n.mul(ge,le),le=n.add(q,he),ge=n.sub(ge,le),le=n.add(x,S);let Fe=n.add(E,P);return le=n.mul(le,Fe),Fe=n.add(q,me),le=n.sub(le,Fe),Fe=n.add(A,S),D=n.add(C,P),Fe=n.mul(Fe,D),D=n.add(he,me),Fe=n.sub(Fe,D),F=n.mul(z,le),D=n.mul(G,me),F=n.add(D,F),D=n.sub(he,F),F=n.add(he,F),R=n.mul(D,F),he=n.add(q,q),he=n.add(he,q),me=n.mul(z,me),le=n.mul(G,le),he=n.add(he,me),me=n.sub(q,me),me=n.mul(z,me),le=n.add(le,me),q=n.mul(he,le),R=n.add(R,q),q=n.mul(Fe,le),D=n.mul(ge,D),D=n.sub(D,q),q=n.mul(ge,he),F=n.mul(Fe,F),F=n.add(F,q),new _(D,R,F)}subtract(b){return I(b),this.add(b.negate())}is0(){return this.equals(_.ZERO)}multiply(b){let{endo:x}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let A,S,E=C=>Y.cached(this,C,P=>mr(_,P));if(x){let{k1neg:C,k1:P,k2neg:D,k2:R}=N(b),{p:F,f:z}=E(P),{p:G,f:q}=E(R);S=z.add(q),A=L(x.beta,F,G,C,D)}else{let{p:C,f:P}=E(b);A=C,S=P}return mr(_,[A,S])[0]}multiplyUnsafe(b){let{endo:x}=e,A=this,S=b;if(!o.isValid(S))throw new RangeError("invalid scalar: out of range");if(S===gt||A.is0())return _.ZERO;if(S===er)return A;if(Y.hasCache(this))return this.multiply(S);if(x){let{k1neg:E,k1:C,k2neg:P,k2:D}=N(S),{p1:R,p2:F}=ep(_,A,C,D);return L(x.beta,R,F,E,P)}else return Y.unsafe(A,S)}toAffine(b){let x=this,A=b,{X:S,Y:E,Z:C}=x;if(n.eql(C,n.ONE))return{x:S,y:E};let P=x.is0();A==null&&(A=P?n.ONE:n.inv(C));let D=n.mul(S,A),R=n.mul(E,A),F=n.mul(C,A);if(P)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:D,y:R}}isTorsionFree(){let{isTorsionFree:b}=e;return i===er?!0:b?b(_,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===er?this:b?b(_,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===er?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return rt(b,"isCompressed"),this.assertValidity(),p(_,this,b)}toHex(b=!0){return nn(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,Y=new ln(_,e.endo?Math.ceil(B/2):B);return B>=8&&_.BASE.precompute(8),Object.freeze(_.prototype),Object.freeze(_),_}function zp(r){return Uint8Array.of(r?2:3)}function Vp(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ex(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?yo:e.randomBytes,o=Object.assign(Vp(r.Fp,t),{seed:Math.max(bu(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:m}=o;try{let y=h.length;return p===!0&&y!==g||p===!1&&y!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,wu(V(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function u(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:m}=o,y=t._lengths;if(!fr(h))return;let w=V(h,void 0,"key").length,v=w===g||w===m,T=w===p||!!y?.includes(w);if(!(v&&T))return v}function l(h,p,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Qs(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function Hp(r,e,t={}){let n=e;Bs(n),ot(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?yo:t.randomBytes,s=t.hmac===void 0?(S,E)=>Up(n,S,E):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p}=ex(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*qp+er<i.ORDER;function y(S){let E=c>>er;return S>E}function w(S,E){if(!a.isValidNot0(E))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return E}function v(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(S,E){El(E);let C=p.signature,P=E==="compact"?C:E==="recovered"?C+1:void 0;return V(S,P)}class I{r;s;recovery;constructor(E,C,P){if(this.r=w("r",E),this.s=w("s",C),P!=null){if(v(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(E,C=g.format){T(E,C);let P;if(C==="der"){let{r:z,s:G}=it.toSig(V(E));return new I(z,G)}C==="recovered"&&(P=E[0],C="compact",E=E.subarray(1));let D=p.signature/2,R=E.subarray(0,D),F=E.subarray(D,D*2);return new I(a.fromBytes(R),a.fromBytes(F),P)}static fromHex(E,C){return this.fromBytes(on(E),C)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new I(this.r,this.s,E)}recoverPublicKey(E){let{r:C,s:P}=this,D=this.assertRecovery(),R=D===2||D===3?C+c:C;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(R),z=r.fromBytes(pe(zp((D&1)===0),F)),G=a.inv(R),q=L(V(E,void 0,"msgHash")),he=a.create(-q*G),me=a.create(P*G),ge=r.BASE.multiplyUnsafe(he).add(z.multiplyUnsafe(me));if(ge.is0())throw new Error("invalid recovery: point at infinify");return ge.assertValidity(),ge}hasHighS(){return y(this.s)}toBytes(E=g.format){if(El(E),E==="der")return on(it.hexFromSig(this));let{r:C,s:P}=this,D=a.toBytes(C),R=a.toBytes(P);return E==="recovered"?(v(),pe(Uint8Array.of(this.assertRecovery()),D,R)):pe(D,R)}toHex(E){return nn(this.toBytes(E))}}Object.freeze(I.prototype),Object.freeze(I);let N=t.bits2int===void 0?function(E){if(E.length>8192)throw new Error("input is too large");let C=dr(E),P=E.length*8-u;return P>0?C>>BigInt(P):C}:t.bits2int,L=t.bits2int_modN===void 0?function(E){return a.create(N(E))}:t.bits2int_modN,_=xo(u);function B(S){return sn("num < 2^"+u,S,gt,_),a.toBytes(S)}function Y(S,E){return V(S,void 0,"message"),E?V(n(S),void 0,"prehashed message"):S}function K(S,E,C){let{lowS:P,prehash:D,extraEntropy:R}=xl(C,g);S=Y(S,D);let F=L(S),z=a.fromBytes(E);if(!a.isValidNot0(z))throw new Error("invalid private key");let G=[B(z),B(F)];if(R!=null&&R!==!1){let ge=R===!0?o(p.secretKey):R;G.push(V(ge,void 0,"extraEntropy"))}let q=pe(...G),he=F;function me(ge){let le=N(ge);if(!a.isValidNot0(le))return;let Fe=a.inv(le),qr=r.BASE.multiply(le).toAffine(),jn=a.create(qr.x);if(jn===gt)return;let bs=a.create(Fe*a.create(he+jn*z));if(bs===gt)return;let xd=(qr.x===jn?0:2)|Number(qr.y&er),Ed=bs;return P&&y(bs)&&(Ed=a.neg(bs),xd^=1),new I(jn,Ed,m?void 0:xd)}return{seed:q,k2sig:me}}function b(S,E,C={}){let{seed:P,k2sig:D}=K(S,E,C);return Fh(n.outputLen,a.BYTES,s)(P,D).toBytes(C.format)}function x(S,E,C,P={}){let{lowS:D,prehash:R,format:F}=xl(P,g);if(C=V(C,void 0,"publicKey"),E=Y(E,R),!fr(S)){let z=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}T(S,F);try{let z=I.fromBytes(S,F),G=r.fromBytes(C);if(D&&z.hasHighS())return!1;let{r:q,s:he}=z,me=L(E),ge=a.inv(he),le=a.create(me*ge),Fe=a.create(q*ge),qr=r.BASE.multiplyUnsafe(le).add(G.multiplyUnsafe(Fe));return qr.is0()?!1:a.create(qr.x)===q}catch{return!1}}function A(S,E,C={}){let{prehash:P}=xl(C,g);return E=Y(E,P),I.fromBytes(S,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:b,verify:x,recoverPublicKey:A,Signature:I,hash:n})}var Al={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},tx={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Wp=BigInt(2);function rx(r){let e=Al.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=se(l,t,e)*l%e,d=se(f,t,e)*l%e,h=se(d,Wp,e)*u%e,p=se(h,o,e)*h%e,g=se(p,s,e)*p%e,m=se(g,a,e)*g%e,y=se(m,c,e)*m%e,w=se(y,a,e)*g%e,v=se(w,t,e)*l%e,T=se(v,i,e)*p%e,I=se(T,n,e)*u%e,N=se(I,Wp,e);if(!Sl.eql(Sl.sqr(N),r))throw new Error("Cannot find square root");return N}var Sl=cn(Al.p,{sqrt:rx}),nx=$p(Al,{Fp:Sl,endo:tx}),at=Hp(nx,rn);function jp(r,e,t){let n=mn.digest(e instanceof Uint8Array?e:e.subarray());if(hn(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),at.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _o(String(o))});try{return at.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _o(String(o))}}function Gp(r,e,t,n){let o=mn.digest(t instanceof Uint8Array?t:t.subarray());if(hn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),at.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Co(String(s))});try{return n?.signal?.throwIfAborted(),at.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Co(String(s))}}var Mo=class{type="secp256k1";raw;_key;constructor(e){this._key=Zp(e),this.raw=Yp(this._key)}toMultihash(){return Je.digest(Ye(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}verify(e,t,n){return Gp(this._key,t,e,n)}},li=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Xp(e),this.publicKey=new Mo(t??Qp(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:re(this.raw,e.raw)}sign(e,t){return jp(this.raw,e,t)}};function _l(r){return new Mo(r)}async function Jp(){let r=ox();return new li(r)}function Yp(r){return at.Point.fromBytes(r).toBytes()}function Xp(r){try{return at.getPublicKey(r,!0),r}catch(e){throw new Yn(String(e))}}function Zp(r){try{return at.Point.fromBytes(r),r}catch(e){throw new $r(String(e))}}function Qp(r){try{return at.getPublicKey(r,!0)}catch(e){throw new Yn(String(e))}}function ox(){return at.utils.randomSecretKey()}async function em(r,e){if(r==="Ed25519")return pp();if(r==="secp256k1")return Jp();if(r==="RSA")return wl(sx(e));if(r==="ECDSA")return Eh(ix(e));throw new Ut}function bn(r,e){let{Type:t,Data:n}=mt.decode(r),o=n??new Uint8Array;switch(t){case ie.RSA:return gl(o,e);case ie.Ed25519:return ku(o);case ie.secp256k1:return _l(o);case ie.ECDSA:return tu(o);default:throw new Ut}}function tm(r){let{Type:e,Data:t}=mt.decode(r.digest),n=t??new Uint8Array;switch(e){case ie.Ed25519:return ku(n);case ie.secp256k1:return _l(n);case ie.ECDSA:return tu(n);default:throw new Ut}}function Ye(r){return mt.encode({Type:ie[r.type],Data:r.raw})}function sx(r){return r==null?2048:parseInt(r,10)}function ix(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 k("Unsupported curve, should be P-256, P-384 or P-521")}var rm=Symbol.for("nodejs.util.inspect.custom"),ax=114,Fo=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()})`}[Ts]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return fe.createV1(ax,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return re(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return re(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[rm](){return`PeerId(${this.toString()})`}},Bo=class extends Fo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Uo=class extends Fo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ko=class extends Fo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},cx=2336,qo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Je.digest(M(this.url))}[rm](){return`PeerId(${this.url})`}[Ts]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return fe.createV1(cx,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var ux=114,nm=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=St(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return $o(fe.parse(r));if(e==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=St(e.decode(r))}return wn(t)}function Cl(r){if(r.type==="Ed25519")return new Uo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ko({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Bo({multihash:r.toCID().multihash,publicKey:r});throw new Ut}function om(r){return Cl(r.publicKey)}function wn(r){if(fx(r))return new Bo({multihash:r});if(lx(r))try{let e=tm(r);if(e.type==="Ed25519")return new Uo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ko({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new qo(new URL(t))}throw new Es("Supplied PeerID Multihash is invalid")}function $o(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ux&&r.code!==nm)throw new xs("Supplied PeerID CID is invalid");if(r.code===nm){let e=H(r.multihash.digest);return new qo(new URL(e))}return wn(r.multihash)}function lx(r){return r.code===Je.code}function fx(r){return r.code===mn.code}async function sm(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new k("Private network is enforced, but no protector was provided");return r}function fi(r,e){if(typeof r=="string")return dx(r);if(typeof r=="number")return mx(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function dx(r){if(typeof r!="string"||r.length===0||r.length>100)throw new 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 new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function hx(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 px(r){let e=Math.abs(r);return e>=315576e5?xr(r,e,315576e5,"year"):e>=26298e5?xr(r,e,26298e5,"month"):e>=6048e5?xr(r,e,6048e5,"week"):e>=864e5?xr(r,e,864e5,"day"):e>=36e5?xr(r,e,36e5,"hour"):e>=6e4?xr(r,e,6e4,"minute"):e>=1e3?xr(r,e,1e3,"second"):`${r} ms`}function mx(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?px(r):hx(r)}function xr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Il(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=fi,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,p,g;function m(...y){if(!m.enabled)return;let w=m,v=Number(new Date),T=v-(d||v);w.diff=T,w.prev=d,w.curr=v,d=v,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let I=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(L,_)=>{if(L==="%%")return"%";I++;let B=t.formatters[_];if(typeof B=="function"){let Y=y[I];L=B.call(w,Y),y.splice(I,1),I--}return L}),t.formatArgs.call(w,y),f?.onLog!=null&&f.onLog(...y),(w.log||t.log).apply(w,y)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),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,g=t.enabled(l)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var di=vx(),gx=["#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 yx(){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 bx(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+fi(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 wx=console.debug??console.log??(()=>{});function xx(r){try{r?di?.setItem("debug",r):di?.removeItem("debug")}catch{}}function Ex(){let r;try{r=di?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function vx(){try{return localStorage}catch{}}function Sx(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var im=Il({formatArgs:bx,save:xx,load:Ex,useColors:yx,setupFormatters:Sx,colors:gx,storage:di,log:wx});var Ke=im;Ke.formatters.b=r=>r==null?"undefined":te.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":je.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":Wu.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();function am(r,e=""){let t=cm(r.message),n=cm(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var Libp2P=(()=>{var Kb=Object.create;var ei=Object.defineProperty;var zb=Object.getOwnPropertyDescriptor;var qb=Object.getOwnPropertyNames;var $b=Object.getPrototypeOf,Vb=Object.prototype.hasOwnProperty;var xo=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),U=(r,e)=>{for(var t in e)ei(r,t,{get:e[t],enumerable:!0})},np=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of qb(e))!Vb.call(r,o)&&o!==t&&ei(r,o,{get:()=>e[o],enumerable:!(n=zb(e,o))||n.enumerable});return r};var Yc=(r,e,t)=>(t=r!=null?Kb($b(r)):{},np(e||!r||!r.__esModule?ei(t,"default",{value:r,enumerable:!0}):t,r)),Hb=r=>np(ei({},"__esModule",{value:!0}),r);var gf=xo(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.Netmask4Impl=void 0;Nn.ip2long=On;Nn.long2ip=At;function At(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var i1=48,a1=97,c1=65;function u1(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-i1)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-a1)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-c1)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function On(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=u1(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var mf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=On(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(On(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=At(this.netLong),this.mask=At(this.maskLong),this.hostmask=At(~this.maskLong),this.first=this.bitmask<=30?At(this.netLong+1):this.base,this.last=this.bitmask<=30?At(this.netLong+this.size-2):At(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?At(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(On(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(At(this.netLong+this.size*e),this.mask)}forEach(e){let t=On(this.first),n=On(this.last),o=0;for(;t<=n;)e(At(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};Nn.Netmask4Impl=mf});var c0=xo(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Netmask6Impl=void 0;Mn.ip6bigint=bf;Mn.bigint2ip6=Kr;var l1=gf(),yf=(1n<<128n)-1n;function bf(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,l1.ip2long)(n),s=r.substring(0,t+1)+"0:0";return a0(s)&~0xffffffffn|BigInt(o)}return a0(r)}function a0(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function Kr(r){if(r<0n||r>yf)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var wf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=yf>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=bf(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Kr(this.netBigint),this.mask=Kr(this.maskBigint),this.hostmask=Kr(~this.maskBigint&yf),this.first=this.base,this.last=Kr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(bf(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Kr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(Kr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Mn.Netmask6Impl=wf});var u0=xo(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.long2ip=hr.ip2long=hr.Netmask=void 0;var ea=gf();Object.defineProperty(hr,"ip2long",{enumerable:!0,get:function(){return ea.ip2long}});Object.defineProperty(hr,"long2ip",{enumerable:!0,get:function(){return ea.long2ip}});var f1=c0(),xf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new f1.Netmask6Impl(e,t):this._impl=new ea.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof ea.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};hr.Netmask=xf});var Jy=xo((NN,lh)=>{"use strict";var MA=Object.prototype.hasOwnProperty,$e="~";function Vs(){}Object.create&&(Vs.prototype=Object.create(null),new Vs().__proto__||($e=!1));function BA(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Qy(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new BA(t,n||r,o),i=$e?$e+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 Lc(r,e){--r._eventsCount===0?r._events=new Vs:delete r._events[e]}function Fe(){this._events=new Vs,this._eventsCount=0}Fe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)MA.call(t,n)&&e.push($e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Fe.prototype.listeners=function(e){var t=$e?$e+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};Fe.prototype.listenerCount=function(e){var t=$e?$e+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Fe.prototype.emit=function(e,t,n,o,s,i){var a=$e?$e+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[f].fn.apply(c[f].context,l)}}return!0};Fe.prototype.on=function(e,t,n){return Qy(this,e,t,n,!1)};Fe.prototype.once=function(e,t,n){return Qy(this,e,t,n,!0)};Fe.prototype.removeListener=function(e,t,n,o){var s=$e?$e+e:e;if(!this._events[s])return this;if(!t)return Lc(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Lc(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Lc(this,s)}return this};Fe.prototype.removeAllListeners=function(e){var t;return e?(t=$e?$e+e:e,this._events[t]&&Lc(this,t)):(this._events=new Vs,this._eventsCount=0),this};Fe.prototype.off=Fe.prototype.removeListener;Fe.prototype.addListener=Fe.prototype.on;Fe.prefixed=$e;Fe.EventEmitter=Fe;typeof lh<"u"&&(lh.exports=Fe)});var Ib=xo((ZM,Cb)=>{Cb.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 xC={};U(xC,{createLibp2p:()=>yC,dnsaddrResolver:()=>Jr,isLibp2p:()=>wC});var op=Symbol.for("@libp2p/connection");var Zc=Symbol.for("@libp2p/content-routing");var ot=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},tn=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Eo=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var wr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var xr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},rn=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Xt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},ti=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ri=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ni=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},oi=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var si=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Lt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var nn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var vo=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ii=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},ai=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Yt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ci=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Qc=Symbol.for("@libp2p/peer-discovery");var ui=Symbol.for("@libp2p/peer-id");function Zt(r){return!!r?.[ui]}var Jc=Symbol.for("@libp2p/peer-routing");var eu="keep-alive";function li(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function sp(...r){let e=[];for(let t of r)li(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 ip(...r){let e=[];for(let t of r)li(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 So;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(So||(So={}));function jb(r){return typeof r?.handleEvent=="function"}function Gb(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Oe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Gb(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}jb(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Ao=Symbol.for("@libp2p/service-capabilities"),tu=Symbol.for("@libp2p/service-dependencies");var iu={};U(iu,{base58btc:()=>ne,base58flickr:()=>tw});var o6=new Uint8Array(0);function ap(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 Dt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Er(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Er(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function cp(r){return new TextEncoder().encode(r)}function up(r){return new TextDecoder().decode(r)}function Wb(r){return r?.buffer instanceof ArrayBuffer}function Er(r){return Wb(r)?r:r.slice()}function Xb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var F=c.repeat(g);v<x;++v)F+=r.charAt(_[v]);return F}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),F=m;I!==w;)v[F++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Yb=Xb,Zb=Yb,fp=Zb;var ru=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")}},nu=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 dp(this,e)}},ou=class{decoders;constructor(e){this.decoders=e}or(e){return dp(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 dp(r,e){return new ou({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var su=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 ru(e,t,n),this.decoder=new nu(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function on({name:r,prefix:e,encode:t,decode:n}){return new su(r,e,t,n)}function Qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=fp(t,r);return on({prefix:e,name:r,encode:n,decode:s=>Dt(o(s))})}function Qb(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 Jb(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 ew(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ue({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ew(n);return on({prefix:e,name:r,encode(s){return Jb(s,n,t)},decode(s){return Qb(s,o,t,r)}})}var ne=Qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tw=Qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var au={};U(au,{base32:()=>et,base32hex:()=>sw,base32hexpad:()=>aw,base32hexpadupper:()=>cw,base32hexupper:()=>iw,base32pad:()=>nw,base32padupper:()=>ow,base32upper:()=>rw,base32z:()=>uw});var et=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rw=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nw=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ow=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),sw=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iw=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),aw=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),cw=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uw=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cu={};U(cu,{base36:()=>_o,base36upper:()=>lw});var _o=Qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lw=Qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fw=mp,hp=128,dw=127,hw=~dw,pw=Math.pow(2,31);function mp(r,e,t){e=e||[],t=t||0;for(var n=t;r>=pw;)e[t++]=r&255|hp,r/=128;for(;r&hw;)e[t++]=r&255|hp,r>>>=7;return e[t]=r|0,mp.bytes=t-n+1,e}var mw=uu,gw=128,pp=127;function uu(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw uu.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&pp)<<o:(i&pp)*Math.pow(2,o),o+=7}while(i>=gw);return uu.bytes=s-n,t}var yw=Math.pow(2,7),bw=Math.pow(2,14),ww=Math.pow(2,21),xw=Math.pow(2,28),Ew=Math.pow(2,35),vw=Math.pow(2,42),Sw=Math.pow(2,49),Aw=Math.pow(2,56),_w=Math.pow(2,63),Cw=function(r){return r<yw?1:r<bw?2:r<ww?3:r<xw?4:r<Ew?5:r<vw?6:r<Sw?7:r<Aw?8:r<_w?9:10},Iw={encode:fw,decode:mw,encodingLength:Cw},Tw=Iw,Co=Tw;function Io(r,e=0){return[Co.decode(r,e),Co.decode.bytes]}function sn(r,e,t=0){return Co.encode(r,e,t),e}function an(r){return Co.encodingLength(r)}function yt(r,e){let t=e.byteLength,n=an(r),o=n+an(t),s=new Uint8Array(o+t);return sn(r,s,0),sn(t,s,n),s.set(e,o),new cn(r,t,e,s)}function Pt(r){let e=Dt(r),[t,n]=Io(e),[o,s]=Io(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cn(t,o,i,e)}function gp(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ap(r.bytes,t.bytes)}}var cn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Er(n),this.bytes=Er(o)}};function yp(r,e){let{bytes:t,version:n}=r;return n===0?Dw(t,lu(r),e??ne.encoder):Pw(t,lu(r),e??et.encoder)}var bp=new WeakMap;function lu(r){let e=bp.get(r);if(e==null){let t=new Map;return bp.set(r,t),t}return e}var me=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Er(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==To)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==kw)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=yt(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&&gp(e.multihash,n.multihash)}toString(e){return yp(this,e)}toJSON(){return{"/":yp(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??wp(n,o,s.bytes))}else if(t[Rw]===!0){let{version:n,multihash:o,code:s}=t,i=Pt(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!==To)throw new Error(`Version 0 CID must use dag-pb (code: ${To}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=wp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,To,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=Dt(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 cn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Io(e.subarray(t));return t+=d,f},o=n(),s=To;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Lw(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 lu(s).set(n,e),s}};function Lw(r,e){switch(r[0]){case"Q":{let t=e??ne;return[ne.prefix,t.decode(`${ne.prefix}${r}`)]}case ne.prefix:{let t=e??ne;return[ne.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case _o.prefix:{let t=e??_o;return[_o.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 Dw(r,e,t){let{prefix:n}=t;if(n!==ne.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 Pw(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 To=112,kw=18;function wp(r,e,t){let n=an(r),o=n+an(e),s=new Uint8Array(o+t.byteLength);return sn(r,s,0),sn(e,s,n),s.set(t,o),s}var Rw=Symbol.for("@ipld/js-cid/CID");var fu={};U(fu,{identity:()=>st});var xp=0,Fw="identity",Ep=Dt;function Ow(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 yt(xp,Ep(r))}var st={code:xp,name:Fw,encode:Ep,digest:Ow};function ee(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 Nw(r){return r.buffer instanceof ArrayBuffer}function Ne(r){return Nw(r)?r:r.slice()}async function vp(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 Sp(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,Ne(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ap(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,Ne(e),Ne(t.subarray()));return n?.signal?.throwIfAborted(),s}function kt(r=0){return new Uint8Array(r)}function Lo(r=0){return new Uint8Array(r)}function du(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Lo(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function _p(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}var Ip=Symbol.for("@achingbrain/uint8arraylist");function Cp(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 di(r){return!!r?.[Ip]}var te=class r{bufs;length;[Ip]=!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(di(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(di(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=Cp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Cp(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(di(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 du(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:du(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){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(!di(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Lo(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=kt(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=kt(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=kt(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=Lo(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=kt(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=kt(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=kt(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=kt(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=kt(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(!_p(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 hu={};U(hu,{base10:()=>Mw});var Mw=Qt({prefix:"9",name:"base10",alphabet:"0123456789"});var pu={};U(pu,{base16:()=>Bw,base16upper:()=>Uw});var Bw=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Uw=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var mu={};U(mu,{base2:()=>Kw});var Kw=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var gu={};U(gu,{base256emoji:()=>Hw});var Tp=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}"),zw=Tp.reduce((r,e,t)=>(r[t]=e,r),[]),qw=Tp.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function $w(r){return r.reduce((e,t)=>(e+=zw[t],e),"")}function Vw(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=qw[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Hw=on({prefix:"\u{1F680}",name:"base256emoji",encode:$w,decode:Vw});var wu={};U(wu,{base64:()=>yu,base64pad:()=>jw,base64url:()=>bu,base64urlpad:()=>Gw});var yu=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jw=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bu=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Gw=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xu={};U(xu,{base8:()=>Ww});var Ww=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Eu={};U(Eu,{identity:()=>Xw});var Xw=on({prefix:"\0",name:"identity",encode:r=>up(r),decode:r=>cp(r)});var H6=new TextEncoder,j6=new TextDecoder;var Au={};U(Au,{sha256:()=>un,sha512:()=>Jw});var Qw=20;function Su({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new vu(r,e,t,n,o)}var vu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Qw,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?Lp(n,this.code,t?.truncate):n.then(o=>Lp(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Lp(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 yt(e,r)}function Pp(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var un=Su({name:"sha2-256",code:18,encode:Pp("SHA-256")}),Jw=Su({name:"sha2-512",code:19,encode:Pp("SHA-512")});var Do={...Eu,...mu,...xu,...hu,...pu,...au,...cu,...iu,...wu,...gu},oI={...Au,...fu};function He(r=0){return new Uint8Array(r)}function vr(r=0){return new Uint8Array(r)}function Rp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var kp=Rp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_u=Rp("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=vr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ex={utf8:kp,"utf-8":kp,hex:Do.base16,latin1:_u,ascii:_u,binary:_u,...Do},hi=ex;function N(r,e="utf8"){let t=hi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function z(r,e="utf8"){let t=hi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var tx=parseInt("11111",2),Cu=parseInt("10000000",2),rx=parseInt("01111111",2),Fp={0:Po,1:Po,2:nx,3:ix,4:ax,5:sx,6:ox,16:Po,22:Po,48:Po};function Rt(r,e={offset:0}){let t=r[e.offset]&tx;if(e.offset++,Fp[t]!=null)return Fp[t](r,e);throw new Error("No decoder for tag "+t)}function ko(r,e){let t=0;if((r[e.offset]&Cu)===Cu){let n=r[e.offset]&rx,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 Po(r,e){ko(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Rt(r,e);if(n===null)break;t.push(n)}return t}function nx(r,e){let t=ko(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 ox(r,e){let t=ko(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 u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function sx(r,e){return e.offset++,null}function ix(r,e){let t=ko(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 ax(r,e){let t=ko(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function cx(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new te;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function pi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=cx(r.byteLength);return new te(Uint8Array.from([e.byteLength|Cu]),e)}function Me(r){let e=new te,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new te(Uint8Array.from([2]),pi(e),e)}function Ro(r){let e=Uint8Array.from([0]),t=new te(e,r);return new te(Uint8Array.from([3]),pi(t),t)}function Op(r){return new te(Uint8Array.from([4]),pi(r),r)}function it(r,e=48){let t=new te;for(let n of r)t.append(n);return new te(Uint8Array.from([e]),pi(t),t)}var ux=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),lx=Uint8Array.from([6,5,43,129,4,0,34]),fx=Uint8Array.from([6,5,43,129,4,0,35]),dx={ext:!0,kty:"EC",crv:"P-256"},hx={ext:!0,kty:"EC",crv:"P-384"},px={ext:!0,kty:"EC",crv:"P-521"},Iu=32,Tu=48,Lu=66;function Du(r){let e=Rt(r);return Np(e)}function Np(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Iu*2+1)return n=z(e.subarray(t,t+Iu),"base64url"),o=z(e.subarray(t+Iu),"base64url"),new Sr({...dx,key_ops:["verify"],x:n,y:o});if(e.byteLength===Tu*2+1)return n=z(e.subarray(t,t+Tu),"base64url"),o=z(e.subarray(t+Tu),"base64url"),new Sr({...hx,key_ops:["verify"],x:n,y:o});if(e.byteLength===Lu*2+1)return n=z(e.subarray(t,t+Lu),"base64url"),o=z(e.subarray(t+Lu),"base64url"),new Sr({...px,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Mp(r){return it([Me(Uint8Array.from([1])),Op(N(r.d??"","base64url")),it([Up(r.crv)],160),it([Ro(new te(Uint8Array.from([4]),N(r.x??"","base64url"),N(r.y??"","base64url")))],161)]).subarray()}function Bp(r){return it([Me(Uint8Array.from([1])),it([Up(r.crv)],160),it([Ro(new te(Uint8Array.from([4]),N(r.x??"","base64url"),N(r.y??"","base64url")))],161)]).subarray()}function Up(r){if(r==="P-256")return ux;if(r==="P-384")return lx;if(r==="P-521")return fx;throw new R(`Invalid curve ${r}`)}async function Kp(r="P-256"){let e=await vp(r);return new mi(e.privateKey)}var Sr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bp(this.jwk)),this._raw}toMultihash(){return st.digest(tt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return Ap(this.jwk,t,e,n)}},mi=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Sr({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=Mp(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async sign(e,t){return Sp(this.jwk,e,t)}};function Pu(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function er(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Xe(r,e,t=""){let n=Pu(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}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function gi(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(er(r.outputLen),er(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ln(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 yi(r,e){Xe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ot(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function bi(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function at(r,e){return r<<32-e|r>>>e}var qp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",mx=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function wi(r){if(Xe(r),qp)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=mx[r[t]];return e}var Ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function zp(r){if(r>=Ft._0&&r<=Ft._9)return r-Ft._0;if(r>=Ft.A&&r<=Ft.F)return r-(Ft.A-10);if(r>=Ft.a&&r<=Ft.f)return r-(Ft.a-10)}function Fo(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(qp)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=zp(r.charCodeAt(s)),a=zp(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ku(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xe(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 Ru(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function xi(r=32){er(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Fu=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function $p(r,e,t){return r&e^~r&t}function Vp(r,e,t){return r&e^r&t^e&t}var Oo=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=bi(this.buffer)}update(e){ln(this),Xe(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=bi(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){ln(this),yi(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ot(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=bi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Nt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ei=BigInt(4294967295),Hp=BigInt(32);function gx(r,e=!1){return e?{h:Number(r&Ei),l:Number(r>>Hp&Ei)}:{h:Number(r>>Hp&Ei)|0,l:Number(r&Ei)|0}}function jp(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}=gx(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ou=(r,e,t)=>r>>>t,Nu=(r,e,t)=>r<<32-t|e>>>t,Ar=(r,e,t)=>r>>>t|e<<32-t,_r=(r,e,t)=>r<<32-t|e>>>t,No=(r,e,t)=>r<<64-t|e>>>t-32,Mo=(r,e,t)=>r>>>t-32|e<<64-t;function bt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Gp=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Wp=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Xp=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Yp=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Zp=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Qp=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var bx=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]),tr=new Uint32Array(64),Mu=class extends Oo{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)tr[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=tr[f-15],h=tr[f-2],p=at(d,7)^at(d,18)^d>>>3,g=at(h,17)^at(h,19)^h>>>10;tr[f]=g+tr[f-7]+p+tr[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=at(a,6)^at(a,11)^at(a,25),h=l+d+$p(a,c,u)+bx[f]+tr[f]|0,g=(at(n,2)^at(n,13)^at(n,22))+Vp(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Ot(tr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ot(this.buffer)}},Bu=class extends Mu{A=Nt[0]|0;B=Nt[1]|0;C=Nt[2]|0;D=Nt[3]|0;E=Nt[4]|0;F=Nt[5]|0;G=Nt[6]|0;H=Nt[7]|0;constructor(){super(32)}};var Jp=jp(["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))),wx=Jp[0],xx=Jp[1],rr=new Uint32Array(80),nr=new Uint32Array(80),Uu=class extends Oo{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:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,t){for(let x=0;x<16;x++,t+=4)rr[x]=e.getUint32(t),nr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=rr[x-15]|0,A=nr[x-15]|0,D=Ar(_,A,1)^Ar(_,A,8)^Ou(_,A,7),I=_r(_,A,1)^_r(_,A,8)^Nu(_,A,7),v=rr[x-2]|0,F=nr[x-2]|0,Y=Ar(v,F,19)^No(v,F,61)^Ou(v,F,6),q=_r(v,F,19)^Mo(v,F,61)^Nu(v,F,6),b=Xp(I,q,nr[x-7],nr[x-16]),E=Yp(b,D,Y,rr[x-7],rr[x-16]);rr[x]=E|0,nr[x]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:y,Hl:w}=this;for(let x=0;x<80;x++){let _=Ar(f,d,14)^Ar(f,d,18)^No(f,d,41),A=_r(f,d,14)^_r(f,d,18)^Mo(f,d,41),D=f&h^~f&g,I=d&p^~d&m,v=Zp(w,A,I,xx[x],nr[x]),F=Qp(v,y,_,D,wx[x],rr[x]),Y=v|0,q=Ar(n,o,28)^No(n,o,34)^No(n,o,39),b=_r(n,o,28)^Mo(n,o,34)^Mo(n,o,39),E=n&s^n&a^s&a,T=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=bt(u|0,l|0,F|0,Y|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Gp(Y,b,T);n=Wp(C,F,q,E),o=C|0}({h:n,l:o}=bt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=bt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=bt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=bt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=bt(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=bt(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=bt(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=bt(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,u,l,f,d,h,p,g,m,y,w)}roundClean(){Ot(rr,nr)}destroy(){this.destroyed=!0,Ot(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ku=class extends Uu{Ah=Ae[0]|0;Al=Ae[1]|0;Bh=Ae[2]|0;Bl=Ae[3]|0;Ch=Ae[4]|0;Cl=Ae[5]|0;Dh=Ae[6]|0;Dl=Ae[7]|0;Eh=Ae[8]|0;El=Ae[9]|0;Fh=Ae[10]|0;Fl=Ae[11]|0;Gh=Ae[12]|0;Gl=Ae[13]|0;Hh=Ae[14]|0;Hl=Ae[15]|0;constructor(){super(64)}};var fn=Ru(()=>new Bu,Fu(1));var vi=Ru(()=>new Ku,Fu(3));var j=(r,e,t)=>Xe(r,e,t),qu=er,dn=wi,be=(...r)=>ku(...r),hn=r=>Fo(r),Cr=Pu,Bo=r=>xi(r),Ai=BigInt(0),zu=BigInt(1);function ct(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function _i(r){if(typeof r=="bigint"){if(!Si(r))throw new RangeError("positive bigint expected, got "+r)}else qu(r);return r}function ut(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Uo(r){let e=_i(r).toString(16);return e.length&1?"0"+e:e}function em(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Ai:BigInt("0x"+r)}function Ir(r){return em(wi(r))}function wt(r){return em(wi(Ko(Xe(r)).reverse()))}function Ci(r,e){if(er(e),e===0)throw new RangeError("zero length");r=_i(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Fo(t.padStart(e*2,"0"))}function $u(r,e){return Ci(r,e).reverse()}function tm(r,e){if(r=j(r),e=j(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ko(r){return Uint8Array.from(j(r))}function Ii(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Si=r=>typeof r=="bigint"&&Ai<=r;function Ex(r,e,t){return Si(r)&&Si(e)&&Si(t)&&e<=r&&r<t}function pn(r,e,t,n){if(!Ex(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function mn(r){if(r<Ai)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Ai;r>>=zu,e+=1);return e}var zo=r=>(zu<<BigInt(r))-zu;function rm(r,e,t){if(er(r,"hashLen"),er(e,"qByteLen"),typeof t!="function")throw new TypeError("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),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...m)=>t(u,be(c,...m)),h=(m=o)=>{u=d(s,m),c=d(),m.length!==0&&(u=d(i,m),c=d())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,y=[];for(;m<e;){c=d();let w=c.slice();y.push(w),m+=c.length}return be(...y)};return(m,y)=>{f(),h(m);let w;for(;(w=y(p()))===void 0;)h();return f(),w}}function lt(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Vu=()=>{throw new Error("not implemented")};var _e=BigInt(0),le=BigInt(1),Tr=BigInt(2),im=BigInt(3),am=BigInt(4),cm=BigInt(5),vx=BigInt(7),um=BigInt(8),Sx=BigInt(9),lm=BigInt(16);function ge(r,e){if(e<=_e)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=_e?t:e+t}function ie(r,e,t){if(e<_e)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >_e;)n*=n,n%=t;return n}function nm(r,e){if(r===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let t=ge(r,e),n=e,o=_e,s=le,i=le,a=_e;for(;t!==_e;){let u=n/t,l=n-t*u,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==le)throw new Error("invert: does not exist");return ge(o,e)}function Hu(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function fm(r,e){let t=r,n=(t.ORDER+le)/am,o=t.pow(e,n);return Hu(t,o,e),o}function Ax(r,e){let t=r,n=(t.ORDER-cm)/um,o=t.mul(e,Tr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Tr),s),c=t.mul(i,t.sub(a,t.ONE));return Hu(t,c,e),c}function _x(r){let e=gn(r),t=dm(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+vx)/lm;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),h=u.mul(l,s),p=u.eql(u.sqr(f),c),g=u.eql(u.sqr(d),c);l=u.cmov(l,f,p),f=u.cmov(h,d,g);let m=u.eql(u.sqr(f),c),y=u.cmov(l,f,m);return Hu(u,y,c),y})}function dm(r){if(r<im)throw new Error("sqrt is not defined for small field");let e=r-le,t=0;for(;e%Tr===_e;)e/=Tr,t++;let n=Tr,o=gn(r);for(;om(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return fm;let s=o.pow(n,e),i=(e+le)/Tr;return function(c,u){let l=c;if(l.is0(u))return u;if(om(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),p=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let g=1,m=l.sqr(h);for(;!l.eql(m,l.ONE);)if(g++,m=l.sqr(m),g===f)throw new Error("Cannot find square root");let y=le<<BigInt(f-g-1),w=l.pow(d,y);f=g,d=l.sqr(w),h=l.mul(h,d),p=l.mul(p,w)}return p}}function Cx(r){return r%am===im?fm:r%um===cm?Ax:r%lm===Sx?_x(r):dm(r)}var Mt=(r,e)=>(ge(r,e)&le)===le,Ix=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ju(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Ix.reduce((n,o)=>(n[o]="function",n),e);if(lt(r,t),ut(r.BYTES,"BYTES"),ut(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=le)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Tx(r,e,t){let n=r;if(t<_e)throw new Error("invalid exponent, negatives unsupported");if(t===_e)return n.ONE;if(t===le)return e;let o=n.ONE,s=e;for(;t>_e;)t&le&&(o=n.mul(o,s)),s=n.sqr(s),t>>=le;return o}function qo(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function om(r,e){let t=r,n=(t.ORDER-le)/Tr,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Lx(r,e){if(e!==void 0&&qu(e),r<=_e)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=mn(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var sm=new WeakMap,Ti=class{ORDER;BITS;BYTES;isLE;ZERO=_e;ONE=le;_lengths;_mod;constructor(e,t={}){if(e<=le)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Lx(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ge(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return _e<=e&&e<this.ORDER}is0(e){return e===_e}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&le)===le}neg(e){return ge(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ge(e*e,this.ORDER)}add(e,t){return ge(e+t,this.ORDER)}sub(e,t){return ge(e-t,this.ORDER)}mul(e,t){return ge(e*t,this.ORDER)}pow(e,t){return Tx(this,e,t)}div(e,t){return ge(e*nm(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 nm(e,this.ORDER)}sqrt(e){let t=sm.get(this);return t||sm.set(this,t=Cx(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?$u(e,this.BYTES):Ci(e,this.BYTES)}fromBytes(e,t=!1){j(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?wt(e):Ir(e);if(a&&(c=ge(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return qo(this,e)}cmov(e,t,n){return ct(n,"condition"),n?t:e}};Object.freeze(Ti.prototype);function gn(r,e={}){return new Ti(r,e)}function hm(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=le)throw new Error("field order must be greater than 1");let e=mn(r-le);return Math.ceil(e/8)}function Gu(r){let e=hm(r);return e+Math.ceil(e/2)}function Wu(r,e,t=!1){j(r);let n=r.length,o=hm(e),s=Math.max(Gu(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?wt(r):Ir(r),a=ge(i,e-le)+le;return t?$u(a,o):Ci(a,o)}var yn=BigInt(0),Lr=BigInt(1);function $o(r,e){let t=e.negate();return r?t:e}function Dr(r,e){let t=qo(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ym(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Xu(r,e){ym(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=zo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function pm(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+=Lr);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var Yu=new WeakMap,bm=new WeakMap;function Zu(r){return bm.get(r)||1}function mm(r){if(r!==yn)throw new Error("invalid wNAF")}var bn=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>yn;)t&Lr&&(n=n.add(o)),o=o.double(),t>>=Lr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Xu(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)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=Xu(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=pm(n,a,i);n=c,l?s=s.add($o(d,t[h])):o=o.add($o(f,t[u]))}return mm(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Xu(e,this.bits);for(let i=0;i<s.windows&&n!==yn;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=pm(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return mm(n),o}getPrecomputes(e,t,n){let o=Yu.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Yu.set(t,o))),o}cached(e,t,n){let o=Zu(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Zu(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ym(t,this.bits),bm.set(e,t),Yu.delete(e)}hasCache(e){return Zu(e)!==1}};function wm(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>yn||n>yn;)t&Lr&&(s=s.add(o)),n&Lr&&(i=i.add(o)),o=o.double(),t>>=Lr,n>>=Lr;return{p1:s,p2:i}}function gm(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ju(e),e}else return gn(r,{isLE:t})}function Li(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 u=e[c];if(!(typeof u=="bigint"&&u>yn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=gm(e.p,t.Fp,n),s=gm(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 Di(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var or=BigInt(0),Ee=BigInt(1),Qu=BigInt(2),Dx=BigInt(8);function Px(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 xm(r,e={}){let t=e,n=Li("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;lt(t,{},{uvRatio:"function"});let c=Qu<<BigInt(s.BYTES*8)-Ee,u=g=>o.create(g),l=t.uvRatio===void 0?(g,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,m))}}catch{return{isValid:!1,value:or}}}:t.uvRatio;if(!Px(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,m,y=!1){let w=y?Ee:or;return pn("coordinate "+g,m,w,c),m}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,Ee,u(i.Gx*i.Gy));static ZERO=new h(or,Ee,Ee,or);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,y,w,x){this.X=f("x",m),this.Y=f("y",y),this.Z=f("z",w,!0),this.T=f("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:y,y:w}=m||{};return f("x",y),f("y",w),new h(y,w,Ee,u(y*w))}static fromBytes(m,y=!1){let w=o.BYTES,{a:x,d:_}=i;m=Ko(j(m,w,"point")),ct(y,"zip215");let A=Ko(m),D=m[w-1];A[w-1]=D&-129;let I=wt(A),v=y?c:o.ORDER;pn("point.y",I,or,v);let F=u(I*I),Y=u(F-Ee),q=u(_*F-x),{isValid:b,value:E}=l(Y,q);if(!b)throw new Error("bad point: invalid y coordinate");let T=(E&Ee)===Ee,C=(D&128)!==0;if(!y&&E===or&&C)throw new Error("bad point: x=0 and x_0=1");return C!==T&&(E=u(-E)),h.fromAffine({x:E,y:I})}static fromHex(m,y=!1){return h.fromBytes(hn(m),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return p.createCache(this,m),y||this.multiply(Qu),this}assertValidity(){let m=this,{a:y,d:w}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:x,Y:_,Z:A,T:D}=m,I=u(x*x),v=u(_*_),F=u(A*A),Y=u(F*F),q=u(I*y),b=u(F*u(q+v)),E=u(Y+u(w*u(I*v)));if(b!==E)throw new Error("bad point: equation left != right (1)");let T=u(x*_),C=u(A*D);if(T!==C)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:y,Y:w,Z:x}=this,{X:_,Y:A,Z:D}=m,I=u(y*D),v=u(_*x),F=u(w*D),Y=u(A*x);return I===v&&F===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:m}=i,{X:y,Y:w,Z:x}=this,_=u(y*y),A=u(w*w),D=u(Qu*u(x*x)),I=u(m*_),v=y+w,F=u(u(v*v)-_-A),Y=I+A,q=Y-D,b=I-A,E=u(F*q),T=u(Y*b),C=u(F*b),S=u(q*Y);return new h(E,T,S,C)}add(m){d(m);let{a:y,d:w}=i,{X:x,Y:_,Z:A,T:D}=this,{X:I,Y:v,Z:F,T:Y}=m,q=u(x*I),b=u(_*v),E=u(D*w*Y),T=u(A*F),C=u((x+_)*(I+v)-q-b),S=T-E,L=T+E,k=u(b-y*q),P=u(C*S),O=u(L*k),B=u(C*k),H=u(S*L);return new h(P,O,H,B)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:w}=p.cached(this,m,x=>Dr(h,x));return Dr(h,[y,w])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===or?h.ZERO:this.is0()||m===Ee?this:p.unsafe(this,m,y=>Dr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(m){let y=this,w=m,{X:x,Y:_,Z:A}=y,D=y.is0();w==null&&(w=D?Dx:o.inv(A));let I=u(x*w),v=u(_*w),F=o.mul(A,w);if(D)return{x:or,y:Ee};if(F!==Ee)throw new Error("invZ was invalid");return{x:I,y:v}}clearCofactor(){return a===Ee?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y}=this.toAffine(),w=o.toBytes(y);return w[w.length-1]|=m&Ee?128:0,w}toHex(){return dn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new bn(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Pi=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Vu()}static fromHex(e){Vu()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return dn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Em(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;lt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(ut(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Bo:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,E,T)=>{if(ct(T,"phflag"),E.length||T)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(wt(b))}function g(b){let E=I.secretKey;j(b,I.secretKey,"secretKey");let T=j(n(b),2*E,"hashedSecretKey"),C=d(T.slice(0,E)),S=T.slice(E,2*E),L=p(C);return{head:C,prefix:S,scalar:L}}function m(b){let{head:E,prefix:T,scalar:C}=g(b),S=i.multiply(C),L=S.toBytes();return{head:E,prefix:T,scalar:C,point:S,pointBytes:L}}function y(b){return m(b).pointBytes}function w(b=Uint8Array.of(),...E){let T=be(...E);return p(n(h(T,j(b,void 0,"context"),!!s)))}function x(b,E,T={}){b=j(b,void 0,"message"),s&&(b=s(b));let{prefix:C,scalar:S,pointBytes:L}=m(E),k=w(T.context,C,b),P=i.multiply(k).toBytes(),O=w(T.context,P,L,b),B=c.create(k+O*S);if(!c.isValid(B))throw new Error("sign failed: invalid s");let H=be(P,c.toBytes(B));return j(H,I.signature,"result")}let _={zip215:o.zip215};function A(b,E,T,C=_){let{context:S}=C,L=C.zip215===void 0?!!_.zip215:C.zip215,k=I.signature;b=j(b,k,"signature"),E=j(E,void 0,"message"),T=j(T,I.publicKey,"publicKey"),L!==void 0&&ct(L,"zip215"),s&&(E=s(E));let P=k/2,O=b.subarray(0,P),B=wt(b.subarray(P,k)),H,X,$;try{H=r.fromBytes(T,L),X=r.fromBytes(O,L),$=i.multiplyUnsafe(B)}catch{return!1}if(!L&&H.isSmallOrder())return!1;let ye=w(S,O,T,E);return X.add(H.multiplyUnsafe(ye)).subtract($).clearCofactor().is0()}let D=a.BYTES,I={secretKey:D,publicKey:D,signature:2*D,seed:D};function v(b){return b=b===void 0?f(I.seed):b,j(b,I.seed,"seed")}function F(b){return Cr(b)&&b.length===I.secretKey}function Y(b,E){try{return!!r.fromBytes(b,E===void 0?_.zip215:E)}catch{return!1}}let q={getExtendedPublicKey:m,randomSecretKey:v,isValidSecretKey:F,isValidPublicKey:Y,toMontgomery(b){let{y:E}=r.fromBytes(b),T=I.publicKey,C=T===32;if(!C&&T!==57)throw new Error("only defined for 25519 and 448");let S=C?a.div(Ee+E,Ee-E):a.div(E-Ee,E+Ee);return a.toBytes(S)},toMontgomerySecret(b){let E=I.secretKey;j(b,E);let T=n(b.subarray(0,E));return d(T).subarray(0,E)}};return Object.freeze(I),Object.freeze(q),Object.freeze({keygen:Di(v,y),getPublicKey:y,sign:x,verify:A,utils:q,Point:r,lengths:I})}function Vo(r,e){if(ut(r),ut(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function kx(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Rx(r){if(!Cr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Ii(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ju(r,e,t,n){j(r),ut(t),e=Rx(e),e.length>255&&(e=n(be(Ii("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=be(e,Vo(e.length,1)),c=new Uint8Array(s),u=Vo(t,2),l=new Array(i),f=n(be(c,r,u,Vo(0,1),a));l[0]=n(be(f,Vo(1,1),a));for(let h=1;h<i;h++){let p=[kx(f,l[h-1]),Vo(h+1,1),a];l[h]=n(be(...p))}return be(...l).slice(0,t)}var vm="HashToScalar-";var Fx=BigInt(0),Bt=BigInt(1),Sm=BigInt(2);var Ox=BigInt(5),Nx=BigInt(8),wn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),nl={p:wn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Nx,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Mx(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=wn,a=r*r%s*r%s,c=ie(a,Sm,s)*a%s,u=ie(c,Bt,s)*r%s,l=ie(u,Ox,s)*u%s,f=ie(l,e,s)*l%s,d=ie(f,t,s)*f%s,h=ie(d,n,s)*d%s,p=ie(h,o,s)*h%s,g=ie(p,o,s)*h%s,m=ie(g,e,s)*l%s;return{pow_p_5_8:ie(m,Sm,s)*r%s,b2:a}}function Bx(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var el=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ol(r,e){let t=wn,n=ge(e*e*e,t),o=ge(n*n*e,t),s=Mx(r*o).pow_p_5_8,i=ge(r*n*s,t),a=ge(e*i*i,t),c=i,u=ge(i*el,t),l=a===r,f=a===ge(-r,t),d=a===ge(-r*el,t);return l&&(i=c),(f||d)&&(i=u),Mt(i,t)&&(i=ge(-i,t)),{isValid:l||f,value:i}}var ir=xm(nl,{uvRatio:ol}),sr=ir.Fp,Cm=ir.Fn;function Ux(r){return Em(ir,vi,Object.assign({adjustScalarBytes:Bx,zip215:!0},r))}var Ho=Ux({});var tl=el,Kx=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),zx=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qx=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),$x=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Am=r=>ol(Bt,r),Vx=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),rl=r=>sr.create(wt(r)&Vx);function _m(r){let{d:e}=nl,t=wn,n=y=>sr.create(y),o=n(tl*r*r),s=n((o+Bt)*qx),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=ol(s,a),l=n(u*r);Mt(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let f=n(i*(o-Bt)*$x-a),d=u*u,h=n((u+u)*a),p=n(f*Kx),g=n(Bt-d),m=n(Bt+d);return new ir(n(h*m),n(g*p),n(p*m),n(h*g))}var ar=class r extends Pi{static BASE=new r(ir.BASE);static ZERO=new r(ir.ZERO);static Fp=sr;static Fn=Cm;constructor(e){super(e)}static fromAffine(e){return new r(ir.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Xe(e,32);let{a:t,d:n}=nl,o=wn,s=_=>sr.create(_),i=rl(e);if(!tm(sr.toBytes(i),e)||Mt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Bt+t*a),u=s(Bt-t*a),l=s(c*c),f=s(u*u),d=s(t*n*l-f),{isValid:h,value:p}=Am(s(d*f)),g=s(p*u),m=s(p*g*d),y=s((i+i)*g);Mt(y,o)&&(y=s(-y));let w=s(c*m),x=s(y*w);if(!h||Mt(x,o)||w===Fx)throw new Error("invalid ristretto255 encoding 2");return new r(new ir(y,w,Bt,x))}static fromHex(e){return r.fromBytes(Fo(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=wn,i=m=>sr.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=Am(i(a*u)),f=i(l*a),d=i(l*c),h=i(f*d*o),p;if(Mt(o*h,s)){let m=i(t*tl),y=i(e*tl);e=m,t=y,p=i(f*zx)}else p=d;Mt(e*h,s)&&(t=i(-t));let g=i((n-t)*p);return Mt(g,s)&&(g=i(-g)),sr.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>sr.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(ar.BASE);Object.freeze(ar.ZERO);Object.freeze(ar.prototype);Object.freeze(ar);var Hx=Object.freeze({Point:ar,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ju(r,t,64,vi);return Hx.deriveToCurve(n)},hashToScalar(r,e={DST:vm}){let t=Ju(r,e.DST,64,vi);return Cm.create(wt(t))},deriveToCurve(r){Xe(r,64);let e=rl(r.subarray(0,32)),t=_m(e),n=rl(r.subarray(32,64)),o=_m(n);return new ar(t.add(o))}});var jo=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Go=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ki=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var je={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ki("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 Ri=32,Wo=64,sl=32;var xn,Im=(async()=>{try{return await je.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Tm(){let r=Ho.utils.randomSecretKey(),e=Ho.getPublicKey(r);return{privateKey:Yx(r,e),publicKey:e}}async function jx(r,e){let t;r.length===Wo?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:z(r.subarray(32),"base64url"),d:z(t,"base64url"),ext:!0,key_ops:["sign"]},o=await je.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await je.get().subtle.sign({name:"Ed25519"},o,Ne(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function Gx(r,e){let t=r.subarray(0,sl);return Ho.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Lm(r,e){return xn==null&&(xn=await Im),xn?jx(r,e):Gx(r,e)}async function Wx(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await je.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await je.get().subtle.verify({name:"Ed25519"},n,Ne(e),Ne(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Xx(r,e,t){return Ho.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Dm(r,e,t){return xn==null&&(xn=await Im),xn?Wx(r,e,t):Xx(r,e,t)}function Yx(r,e){let t=new Uint8Array(Wo);for(let n=0;n<sl;n++)t[n]=r[n],t[sl+n]=e[n];return t}function Zx(r){return r?.buffer instanceof ArrayBuffer}function il(r){if(Zx(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ut(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=vr(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return il(t)}function En(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Xo=class{type="Ed25519";raw;constructor(e){this.raw=Oi(e,Ri)}toMultihash(){return st.digest(tt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Dm(this.raw,t,e);return En(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Fi=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Oi(e,Wo),this.publicKey=new Xo(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Lm(this.raw,e);return En(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function al(r){return r=Oi(r,Ri),new Xo(r)}async function km(){let{privateKey:r,publicKey:e}=Tm();return new Fi(r,e)}function Oi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function cr(r=0){return new Uint8Array(r)}var Qx=Math.pow(2,7),Jx=Math.pow(2,14),eE=Math.pow(2,21),Rm=Math.pow(2,28),Fm=Math.pow(2,35),Om=Math.pow(2,42),Nm=Math.pow(2,49),Be=128,ur=127;function Yo(r){if(r<Qx)return 1;if(r<Jx)return 2;if(r<eE)return 3;if(r<Rm)return 4;if(r<Fm)return 5;if(r<Om)return 6;if(r<Nm)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mm(r,e,t=0){switch(Yo(r)){case 8:e[t++]=r&255|Be,r/=128;case 7:e[t++]=r&255|Be,r/=128;case 6:e[t++]=r&255|Be,r/=128;case 5:e[t++]=r&255|Be,r/=128;case 4:e[t++]=r&255|Be,r>>>=7;case 3:e[t++]=r&255|Be,r>>>=7;case 2:e[t++]=r&255|Be,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Bm(r,e){let t=r[e],n=0;if(n+=t&ur,t<Be||(t=r[e+1],n+=(t&ur)<<7,t<Be)||(t=r[e+2],n+=(t&ur)<<14,t<Be)||(t=r[e+3],n+=(t&ur)<<21,t<Be)||(t=r[e+4],n+=(t&ur)*Rm,t<Be)||(t=r[e+5],n+=(t&ur)*Fm,t<Be)||(t=r[e+6],n+=(t&ur)*Om,t<Be)||(t=r[e+7],n+=(t&ur)*Nm,t<Be))return n;throw new RangeError("Could not decode varint")}var cl=new Float32Array([-0]),lr=new Uint8Array(cl.buffer);function Um(r,e,t){cl[0]=r,e[t]=lr[0],e[t+1]=lr[1],e[t+2]=lr[2],e[t+3]=lr[3]}function Km(r,e){return lr[0]=r[e],lr[1]=r[e+1],lr[2]=r[e+2],lr[3]=r[e+3],cl[0]}var ul=new Float64Array([-0]),Te=new Uint8Array(ul.buffer);function zm(r,e,t){ul[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function qm(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],ul[0]}var tE=BigInt(Number.MAX_SAFE_INTEGER),rE=BigInt(Number.MIN_SAFE_INTEGER),Ye=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 Pr;if(e<tE&&e>rE)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>$m&&(o=0n,++n>$m&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Pr;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):Pr}},Pr=new Ye(0,0);Pr.toBigInt=function(){return 0n};Pr.zzEncode=Pr.zzDecode=function(){return this};Pr.length=function(){return 1};var $m=4294967296n;function Vm(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 Hm(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 ll(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 ft(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ni(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var fl=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,ft(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 ft(this,4);return Ni(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ft(this,4);return Ni(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ft(this,4);let e=Km(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ft(this,4);let e=qm(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 ft(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ft(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ft(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 Ye(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 ft(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 ft(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 ft(this,8);let e=Ni(this.buf,this.pos+=4),t=Ni(this.buf,this.pos+=4);return new Ye(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=Bm(this.buf,this.pos);return this.pos+=Yo(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 Zo(r){return new fl(r instanceof Uint8Array?r:r.subarray())}function Ue(r,e,t){let n=Zo(r);return e.decode(n,void 0,t)}var gl={};U(gl,{base10:()=>uE});var V8=new Uint8Array(0);function Gm(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 Kt(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 Wm(r){return new TextEncoder().encode(r)}function Xm(r){return new TextDecoder().decode(r)}function nE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var F=c.repeat(g);v<x;++v)F+=r.charAt(_[v]);return F}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),F=m;I!==w;)v[F++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var oE=nE,sE=oE,Zm=sE;var dl=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")}},hl=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 Qm(this,e)}},pl=class{decoders;constructor(e){this.decoders=e}or(e){return Qm(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 Qm(r,e){return new pl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ml=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 dl(e,t,n),this.decoder=new hl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function vn({name:r,prefix:e,encode:t,decode:n}){return new ml(r,e,t,n)}function fr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Zm(t,r);return vn({prefix:e,name:r,encode:n,decode:s=>Kt(o(s))})}function iE(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 aE(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 cE(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function fe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=cE(n);return vn({prefix:e,name:r,encode(s){return aE(s,n,t)},decode(s){return iE(s,o,t,r)}})}var uE=fr({prefix:"9",name:"base10",alphabet:"0123456789"});var yl={};U(yl,{base16:()=>lE,base16upper:()=>fE});var lE=fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fE=fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bl={};U(bl,{base2:()=>dE});var dE=fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wl={};U(wl,{base256emoji:()=>yE});var Jm=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}"),hE=Jm.reduce((r,e,t)=>(r[t]=e,r),[]),pE=Jm.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function mE(r){return r.reduce((e,t)=>(e+=hE[t],e),"")}function gE(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=pE[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var yE=vn({prefix:"\u{1F680}",name:"base256emoji",encode:mE,decode:gE});var xl={};U(xl,{base32:()=>Sn,base32hex:()=>EE,base32hexpad:()=>SE,base32hexpadupper:()=>AE,base32hexupper:()=>vE,base32pad:()=>wE,base32padupper:()=>xE,base32upper:()=>bE,base32z:()=>_E});var Sn=fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bE=fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wE=fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xE=fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EE=fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vE=fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SE=fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),AE=fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_E=fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var El={};U(El,{base36:()=>Qo,base36upper:()=>CE});var Qo=fr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),CE=fr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vl={};U(vl,{base58btc:()=>xt,base58flickr:()=>IE});var xt=fr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),IE=fr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sl={};U(Sl,{base64:()=>TE,base64pad:()=>LE,base64url:()=>DE,base64urlpad:()=>PE});var TE=fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),LE=fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),DE=fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),PE=fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Al={};U(Al,{base8:()=>kE});var kE=fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _l={};U(_l,{identity:()=>RE});var RE=vn({prefix:"\0",name:"identity",encode:r=>Xm(r),decode:r=>Wm(r)});var iT=new TextEncoder,aT=new TextDecoder;var Il={};U(Il,{identity:()=>r2});var NE=rg,eg=128,ME=127,BE=~ME,UE=Math.pow(2,31);function rg(r,e,t){e=e||[],t=t||0;for(var n=t;r>=UE;)e[t++]=r&255|eg,r/=128;for(;r&BE;)e[t++]=r&255|eg,r>>>=7;return e[t]=r|0,rg.bytes=t-n+1,e}var KE=Cl,zE=128,tg=127;function Cl(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Cl.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&tg)<<o:(i&tg)*Math.pow(2,o),o+=7}while(i>=zE);return Cl.bytes=s-n,t}var qE=Math.pow(2,7),$E=Math.pow(2,14),VE=Math.pow(2,21),HE=Math.pow(2,28),jE=Math.pow(2,35),GE=Math.pow(2,42),WE=Math.pow(2,49),XE=Math.pow(2,56),YE=Math.pow(2,63),ZE=function(r){return r<qE?1:r<$E?2:r<VE?3:r<HE?4:r<jE?5:r<GE?6:r<WE?7:r<XE?8:r<YE?9:10},QE={encode:NE,decode:KE,encodingLength:ZE},JE=QE,Jo=JE;function es(r,e=0){return[Jo.decode(r,e),Jo.decode.bytes]}function An(r,e,t=0){return Jo.encode(r,e,t),e}function _n(r){return Jo.encodingLength(r)}function In(r,e){let t=e.byteLength,n=_n(r),o=n+_n(t),s=new Uint8Array(o+t);return An(r,s,0),An(t,s,n),s.set(e,o),new Cn(r,t,e,s)}function ng(r){let e=Kt(r),[t,n]=es(e),[o,s]=es(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Cn(t,o,i,e)}function og(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Gm(r.bytes,t.bytes)}}var Cn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var sg=0,e2="identity",ig=Kt;function t2(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 In(sg,ig(r))}var r2={code:sg,name:e2,encode:ig,digest:t2};var Dl={};U(Dl,{sha256:()=>o2,sha512:()=>s2});var n2=20;function Ll({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Tl(r,e,t,n,o)}var Tl=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??n2,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?ag(n,this.code,t?.truncate):n.then(o=>ag(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ag(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 In(e,r)}function ug(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var o2=Ll({name:"sha2-256",code:18,encode:ug("SHA-256")}),s2=Ll({name:"sha2-512",code:19,encode:ug("SHA-512")});function lg(r,e){let{bytes:t,version:n}=r;return n===0?a2(t,Pl(r),e??xt.encoder):c2(t,Pl(r),e??Sn.encoder)}var fg=new WeakMap;function Pl(r){let e=fg.get(r);if(e==null){let t=new Map;return fg.set(r,t),t}return e}var Bi=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!==rs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==u2)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=In(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&&og(e.multihash,n.multihash)}toString(e){return lg(this,e)}toJSON(){return{"/":lg(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??dg(n,o,s.bytes))}else if(t[l2]===!0){let{version:n,multihash:o,code:s}=t,i=ng(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!==rs)throw new Error(`Version 0 CID must use dag-pb (code: ${rs}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=dg(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rs,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=Kt(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 Cn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=es(e.subarray(t));return t+=d,f},o=n(),s=rs;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=i2(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 Pl(s).set(n,e),s}};function i2(r,e){switch(r[0]){case"Q":{let t=e??xt;return[xt.prefix,t.decode(`${xt.prefix}${r}`)]}case xt.prefix:{let t=e??xt;return[xt.prefix,t.decode(r)]}case Sn.prefix:{let t=e??Sn;return[Sn.prefix,t.decode(r)]}case Qo.prefix:{let t=e??Qo;return[Qo.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 a2(r,e,t){let{prefix:n}=t;if(n!==xt.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 c2(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 rs=112,u2=18;function dg(r,e,t){let n=_n(r),o=n+_n(e),s=new Uint8Array(o+t.byteLength);return An(r,s,0),An(e,s,n),s.set(t,o),s}var l2=Symbol.for("@ipld/js-cid/CID");var kl={..._l,...bl,...Al,...gl,...yl,...xl,...El,...vl,...Sl,...wl},LT={...Dl,...Il};function pg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var hg=pg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Rl=pg("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=cr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),f2={utf8:hg,"utf-8":hg,hex:kl.base16,latin1:Rl,ascii:Rl,binary:Rl,...kl},mg=f2;function gg(r,e="utf8"){let t=mg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Fl(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return cr(i);o+i>e&&(n=cr(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var kr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ol(){}var Ml=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},d2=Fl();function h2(r){return globalThis.Buffer!=null?cr(r):d2(r)}var os=class{len;head;tail;states;constructor(){this.len=0,this.head=new kr(Ol,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new kr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Bl((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(Ui,10,Ye.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ye.fromBigInt(e);return this._push(Ui,t.length(),t)}uint64Number(e){return this._push(Mm,Yo(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=Ye.fromBigInt(e).zzEncode();return this._push(Ui,t.length(),t)}sint64Number(e){let t=Ye.fromNumber(e).zzEncode();return this._push(Ui,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Nl,1,e?1:0)}fixed32(e){return this._push(ns,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ye.fromBigInt(e);return this._push(ns,4,t.lo)._push(ns,4,t.hi)}fixed64Number(e){let t=Ye.fromNumber(e);return this._push(ns,4,t.lo)._push(ns,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(Um,4,e)}double(e){return this._push(zm,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Nl,1,0):this.uint32(t)._push(m2,t,e)}string(e){let t=Vm(e);return t!==0?this.uint32(t)._push(ll,t,e):this._push(Nl,1,0)}fork(){return this.states=new Ml(this),this.head=this.tail=new kr(Ol,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 kr(Ol,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=h2(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Nl(r,e,t){e[t]=r&255}function p2(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Bl=class extends kr{next;constructor(e,t){super(p2,e,t),this.next=void 0}};function Ui(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 ns(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 m2(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(os.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(g2,e,r),this},os.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(y2,e,r),this});function g2(r,e,t){e.set(r,t)}function y2(r,e,t){r.length<40?ll(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(gg(r),t)}function Ul(){return new os}function Ke(r,e){let t=Ul();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ze(r,e,t){let n=Zo(r);yield*e.stream(n,void 0,"$",t)}var Ki={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function zi(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Kl(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return zi("enum",Ki.VARINT,t,n,o)}function qe(r,e,t){return zi("message",Ki.LENGTH_DELIMITED,r,e,t)}var rt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ss=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ae;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ae||(ae={}));var zl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(zl||(zl={}));(function(r){r.codec=()=>Kl(zl)})(ae||(ae={}));var Et;(function(r){let e;r.codec=()=>(e==null&&(e=qe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ae.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ae.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ae.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return ze(s,r.codec(),i)}r.stream=o})(Et||(Et={}));var ql;(function(r){let e;r.codec=()=>(e==null&&(e=qe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ae.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ae.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ae.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return ze(s,r.codec(),i)}r.stream=o})(ql||(ql={}));function Tn(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return xi(r)}var as={};U(as,{MAX_RSA_KEY_SIZE:()=>$l,generateRSAKeyPair:()=>Ql,jwkToJWKKeyPair:()=>Eg,jwkToPkcs1:()=>E2,jwkToPkix:()=>Gl,jwkToRSAPrivateKey:()=>Zl,pkcs1MessageToJwk:()=>Hl,pkcs1MessageToRSAPrivateKey:()=>Wl,pkcs1ToJwk:()=>x2,pkcs1ToRSAPrivateKey:()=>xg,pkixMessageToJwk:()=>jl,pkixMessageToRSAPublicKey:()=>Yl,pkixToJwk:()=>v2,pkixToRSAPublicKey:()=>Xl});var Ln=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=as.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return me.createV1(114,this._multihash)}toString(){return ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return wg(this.jwk,t,e,n)}},is=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=as.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return bg(this.jwk,e,t)}};var $l=8192,Vl=18,b2=1062,w2=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function x2(r){let e=Rt(r);return Hl(e)}function Hl(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function E2(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 R("JWK was missing components");return it([Me(Uint8Array.from([0])),Me(N(r.n,"base64url")),Me(N(r.e,"base64url")),Me(N(r.d,"base64url")),Me(N(r.p,"base64url")),Me(N(r.q,"base64url")),Me(N(r.dp,"base64url")),Me(N(r.dq,"base64url")),Me(N(r.qi,"base64url"))]).subarray()}function v2(r){let e=Rt(r,{offset:0});return jl(e)}function jl(r){let e=Rt(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function Gl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return it([w2,Ro(it([Me(N(r.n,"base64url")),Me(N(r.e,"base64url"))]))]).subarray()}function xg(r){let e=Rt(r);return Wl(e)}function Wl(r){let e=Hl(r);return Zl(e)}function Xl(r,e){if(r.byteLength>=b2)throw new tn("Key size is too large");let t=Rt(r,{offset:0});return Yl(t,r,e)}function Yl(r,e,t){let n=jl(r);if(t==null){let o=fn(Et.encode({Type:ae.RSA,Data:e}));t=yt(Vl,o)}return new Ln(n,t)}function Zl(r){if(Sg(r)>$l)throw new R("Key size is too large");let e=Eg(r),t=fn(Et.encode({Type:ae.RSA,Data:Gl(e.publicKey)})),n=yt(Vl,t);return new is(e.privateKey,new Ln(e.publicKey,n))}async function Ql(r){if(r>$l)throw new R("Key size is too large");let e=await vg(r),t=fn(Et.encode({Type:ae.RSA,Data:Gl(e.publicKey)})),n=yt(Vl,t);return new is(e.privateKey,new Ln(e.publicKey,n))}function Eg(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function vg(r,e){let t=await je.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 S2(t,e);return{privateKey:n[0],publicKey:n[1]}}async function bg(r,e,t){let n=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await je.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ne(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function wg(r,e,t,n){let o=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await je.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ne(e),Ne(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function S2(r,e){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");let t=await Promise.all([je.get().subtle.exportKey("jwk",r.privateKey),je.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Sg(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return N(r.n,"base64url").length*8}var qi=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(gi(e),Xe(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),Ot(o)}update(e){return ln(this),this.iHash.update(e),this}digestInto(e){ln(this),yi(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ag=(()=>{let r=((e,t,n)=>new qi(e,t).update(n).digest());return r.create=(e,t)=>new qi(e,t),r})();var _g=(r,e)=>(r+(r>=0?e:-e)/Cg)/e;function A2(r,e,t){pn("scalar",r,vt,t);let[[n,o],[s,i]]=e,a=_g(i*r,t),c=_g(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<vt,d=l<vt;f&&(u=-u),d&&(l=-l);let h=zo(Math.ceil(mn(t)/2))+dr;if(u<vt||u>=h||l<vt||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function ef(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Jl(r,e){lt(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ct(t.lowS,"lowS"),ct(t.prehash,"prehash"),t.format!==void 0&&ef(t.format),t}var tf=class extends Error{constructor(e=""){super(e)}},dt={Err:tf,_tlv:{encode:(r,e)=>{let{Err:t}=dt;if(ut(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Uo(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Uo(o.length/2|128):"";return Uo(r)+s+o+e},decode(r,e){let{Err:t}=dt;e=j(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=dt;if(_i(r),r<vt)throw new e("integer: negative integers are not allowed");let t=Uo(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}=dt;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ir(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=dt,o=j(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:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=dt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(dt._tlv);Object.freeze(dt._int);Object.freeze(dt);var vt=BigInt(0),dr=BigInt(1),Cg=BigInt(2),$i=BigInt(3),_2=BigInt(4);function Ig(r,e={}){let t=Li("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;lt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=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=Lg(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(q,b,E){if(u&&b.is0())return Uint8Array.of(0);let{x:T,y:C}=b.toAffine(),S=n.toBytes(T);if(ct(E,"isCompressed"),E){f();let L=!n.isOdd(C);return be(Tg(L),S)}else return be(Uint8Array.of(4),S,n.toBytes(C))}function h(q){j(q,void 0,"Point");let{publicKey:b,publicKeyUncompressed:E}=l,T=q.length,C=q[0],S=q.subarray(1);if(u&&T===1&&C===0)return{x:n.ZERO,y:n.ZERO};if(T===b&&(C===2||C===3)){let L=n.fromBytes(S);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let k=m(L),P;try{P=n.sqrt(k)}catch(H){let X=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}f();let O=n.isOdd(P);return(C&1)===1!==O&&(P=n.neg(P)),{x:L,y:P}}else if(T===E&&C===4){let L=n.BYTES,k=n.fromBytes(S.subarray(0,L)),P=n.fromBytes(S.subarray(L,L*2));if(!y(k,P))throw new Error("bad point: is not on curve");return{x:k,y:P}}else throw new Error(`bad point: got length ${T}, expected compressed=${b} or uncompressed=${E}`)}let p=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function m(q){let b=n.sqr(q),E=n.mul(b,q);return n.add(n.add(E,n.mul(q,s.a)),s.b)}function y(q,b){let E=n.sqr(b),T=m(q);return n.eql(E,T)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,$i),_2),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,x)))throw new Error("bad curve params: a or b");function _(q,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${q}`);return b}function A(q){if(!(q instanceof v))throw new Error("Weierstrass Point expected")}function D(q){if(!c||!c.basises)throw new Error("no endo");return A2(q,c.basises,o.ORDER)}function I(q,b,E,T,C){return E=new v(n.mul(E.X,q),E.Y,E.Z),b=$o(T,b),E=$o(C,E),b.add(E)}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,E,T){this.X=_("x",b),this.Y=_("y",E,!0),this.Z=_("z",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:E,y:T}=b||{};if(!b||!n.isValid(E)||!n.isValid(T))throw new Error("invalid affine point");if(b instanceof v)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(T)?v.ZERO:new v(E,T,n.ONE)}static fromBytes(b){let E=v.fromAffine(g(j(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return v.fromBytes(hn(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return Y.createCache(this,b),E||this.multiply($i),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:E,y:T}=b.toAffine();if(!n.isValid(E)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!y(E,T))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){A(b);let{X:E,Y:T,Z:C}=this,{X:S,Y:L,Z:k}=b,P=n.eql(n.mul(E,k),n.mul(S,C)),O=n.eql(n.mul(T,k),n.mul(L,C));return P&&O}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:E}=s,T=n.mul(E,$i),{X:C,Y:S,Z:L}=this,k=n.ZERO,P=n.ZERO,O=n.ZERO,B=n.mul(C,C),H=n.mul(S,S),X=n.mul(L,L),$=n.mul(C,S);return $=n.add($,$),O=n.mul(C,L),O=n.add(O,O),k=n.mul(b,O),P=n.mul(T,X),P=n.add(k,P),k=n.sub(H,P),P=n.add(H,P),P=n.mul(k,P),k=n.mul($,k),O=n.mul(T,O),X=n.mul(b,X),$=n.sub(B,X),$=n.mul(b,$),$=n.add($,O),O=n.add(B,B),B=n.add(O,B),B=n.add(B,X),B=n.mul(B,$),P=n.add(P,B),X=n.mul(S,L),X=n.add(X,X),B=n.mul(X,$),k=n.sub(k,B),O=n.mul(X,H),O=n.add(O,O),O=n.add(O,O),new v(k,P,O)}add(b){A(b);let{X:E,Y:T,Z:C}=this,{X:S,Y:L,Z:k}=b,P=n.ZERO,O=n.ZERO,B=n.ZERO,H=s.a,X=n.mul(s.b,$i),$=n.mul(E,S),ye=n.mul(T,L),we=n.mul(C,k),xe=n.add(E,T),pe=n.add(S,L);xe=n.mul(xe,pe),pe=n.add($,ye),xe=n.sub(xe,pe),pe=n.add(E,C);let Ve=n.add(S,k);return pe=n.mul(pe,Ve),Ve=n.add($,we),pe=n.sub(pe,Ve),Ve=n.add(T,C),P=n.add(L,k),Ve=n.mul(Ve,P),P=n.add(ye,we),Ve=n.sub(Ve,P),B=n.mul(H,pe),P=n.mul(X,we),B=n.add(P,B),P=n.sub(ye,B),B=n.add(ye,B),O=n.mul(P,B),ye=n.add($,$),ye=n.add(ye,$),we=n.mul(H,we),pe=n.mul(X,pe),ye=n.add(ye,we),we=n.sub($,we),we=n.mul(H,we),pe=n.add(pe,we),$=n.mul(ye,pe),O=n.add(O,$),$=n.mul(Ve,pe),P=n.mul(xe,P),P=n.sub(P,$),$=n.mul(xe,ye),B=n.mul(Ve,B),B=n.add(B,$),new v(P,O,B)}subtract(b){return A(b),this.add(b.negate())}is0(){return this.equals(v.ZERO)}multiply(b){let{endo:E}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let T,C,S=L=>Y.cached(this,L,k=>Dr(v,k));if(E){let{k1neg:L,k1:k,k2neg:P,k2:O}=D(b),{p:B,f:H}=S(k),{p:X,f:$}=S(O);C=H.add($),T=I(E.beta,B,X,L,P)}else{let{p:L,f:k}=S(b);T=L,C=k}return Dr(v,[T,C])[0]}multiplyUnsafe(b){let{endo:E}=e,T=this,C=b;if(!o.isValid(C))throw new RangeError("invalid scalar: out of range");if(C===vt||T.is0())return v.ZERO;if(C===dr)return T;if(Y.hasCache(this))return this.multiply(C);if(E){let{k1neg:S,k1:L,k2neg:k,k2:P}=D(C),{p1:O,p2:B}=wm(v,T,L,P);return I(E.beta,O,B,S,k)}else return Y.unsafe(T,C)}toAffine(b){let E=this,T=b,{X:C,Y:S,Z:L}=E;if(n.eql(L,n.ONE))return{x:C,y:S};let k=E.is0();T==null&&(T=k?n.ONE:n.inv(L));let P=n.mul(C,T),O=n.mul(S,T),B=n.mul(L,T);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:P,y:O}}isTorsionFree(){let{isTorsionFree:b}=e;return i===dr?!0:b?b(v,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===dr?this:b?b(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===dr?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return ct(b,"isCompressed"),this.assertValidity(),p(v,this,b)}toHex(b=!0){return dn(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let F=o.BITS,Y=new bn(v,e.endo?Math.ceil(F/2):F);return F>=8&&v.BASE.precompute(8),Object.freeze(v.prototype),Object.freeze(v),v}function Tg(r){return Uint8Array.of(r?2:3)}function Lg(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function C2(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Bo:e.randomBytes,o=Object.assign(Lg(r.Fp,t),{seed:Math.max(Gu(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:m}=o;try{let y=h.length;return p===!0&&y!==g||p===!1&&y!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Wu(j(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function u(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:m}=o,y=t._lengths;if(!Cr(h))return;let w=j(h,void 0,"key").length,x=w===g||w===m,_=w===p||!!y?.includes(w);if(!(x&&_))return x}function l(h,p,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Di(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function Dg(r,e,t={}){let n=e;gi(n),lt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Bo:t.randomBytes,s=t.hmac===void 0?(C,S)=>Ag(n,C,S):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p}=C2(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*Cg+dr<i.ORDER;function y(C){let S=c>>dr;return C>S}function w(C,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${C}: out of range 1..Point.Fn.ORDER`);return S}function x(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function _(C,S){ef(S);let L=p.signature,k=S==="compact"?L:S==="recovered"?L+1:void 0;return j(C,k)}class A{r;s;recovery;constructor(S,L,k){if(this.r=w("r",S),this.s=w("s",L),k!=null){if(x(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(S,L=g.format){_(S,L);let k;if(L==="der"){let{r:H,s:X}=dt.toSig(j(S));return new A(H,X)}L==="recovered"&&(k=S[0],L="compact",S=S.subarray(1));let P=p.signature/2,O=S.subarray(0,P),B=S.subarray(P,P*2);return new A(a.fromBytes(O),a.fromBytes(B),k)}static fromHex(S,L){return this.fromBytes(hn(S),L)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new A(this.r,this.s,S)}recoverPublicKey(S){let{r:L,s:k}=this,P=this.assertRecovery(),O=P===2||P===3?L+c:L;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=i.toBytes(O),H=r.fromBytes(be(Tg((P&1)===0),B)),X=a.inv(O),$=I(j(S,void 0,"msgHash")),ye=a.create(-$*X),we=a.create(k*X),xe=r.BASE.multiplyUnsafe(ye).add(H.multiplyUnsafe(we));if(xe.is0())throw new Error("invalid recovery: point at infinify");return xe.assertValidity(),xe}hasHighS(){return y(this.s)}toBytes(S=g.format){if(ef(S),S==="der")return hn(dt.hexFromSig(this));let{r:L,s:k}=this,P=a.toBytes(L),O=a.toBytes(k);return S==="recovered"?(x(),be(Uint8Array.of(this.assertRecovery()),P,O)):be(P,O)}toHex(S){return dn(this.toBytes(S))}}Object.freeze(A.prototype),Object.freeze(A);let D=t.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let L=Ir(S),k=S.length*8-u;return k>0?L>>BigInt(k):L}:t.bits2int,I=t.bits2int_modN===void 0?function(S){return a.create(D(S))}:t.bits2int_modN,v=zo(u);function F(C){return pn("num < 2^"+u,C,vt,v),a.toBytes(C)}function Y(C,S){return j(C,void 0,"message"),S?j(n(C),void 0,"prehashed message"):C}function q(C,S,L){let{lowS:k,prehash:P,extraEntropy:O}=Jl(L,g);C=Y(C,P);let B=I(C),H=a.fromBytes(S);if(!a.isValidNot0(H))throw new Error("invalid private key");let X=[F(H),F(B)];if(O!=null&&O!==!1){let xe=O===!0?o(p.secretKey):O;X.push(j(xe,void 0,"extraEntropy"))}let $=be(...X),ye=B;function we(xe){let pe=D(xe);if(!a.isValidNot0(pe))return;let Ve=a.inv(pe),en=r.BASE.multiply(pe).toAffine(),wo=a.create(en.x);if(wo===vt)return;let Js=a.create(Ve*a.create(ye+wo*H));if(Js===vt)return;let tp=(en.x===wo?0:2)|Number(en.y&dr),rp=Js;return k&&y(Js)&&(rp=a.neg(Js),tp^=1),new A(wo,rp,m?void 0:tp)}return{seed:$,k2sig:we}}function b(C,S,L={}){let{seed:k,k2sig:P}=q(C,S,L);return rm(n.outputLen,a.BYTES,s)(k,P).toBytes(L.format)}function E(C,S,L,k={}){let{lowS:P,prehash:O,format:B}=Jl(k,g);if(L=j(L,void 0,"publicKey"),S=Y(S,O),!Cr(C)){let H=C instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+H)}_(C,B);try{let H=A.fromBytes(C,B),X=r.fromBytes(L);if(P&&H.hasHighS())return!1;let{r:$,s:ye}=H,we=I(S),xe=a.inv(ye),pe=a.create(we*xe),Ve=a.create($*xe),en=r.BASE.multiplyUnsafe(pe).add(X.multiplyUnsafe(Ve));return en.is0()?!1:a.create(en.x)===$}catch{return!1}}function T(C,S,L={}){let{prehash:k}=Jl(L,g);return S=Y(S,k),A.fromBytes(C,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:b,verify:E,recoverPublicKey:T,Signature:A,hash:n})}var nf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},I2={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Pg=BigInt(2);function T2(r){let e=nf.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=ie(l,t,e)*l%e,d=ie(f,t,e)*l%e,h=ie(d,Pg,e)*u%e,p=ie(h,o,e)*h%e,g=ie(p,s,e)*p%e,m=ie(g,a,e)*g%e,y=ie(m,c,e)*m%e,w=ie(y,a,e)*g%e,x=ie(w,t,e)*l%e,_=ie(x,i,e)*p%e,A=ie(_,n,e)*u%e,D=ie(A,Pg,e);if(!rf.eql(rf.sqr(D),r))throw new Error("Cannot find square root");return D}var rf=gn(nf.p,{sqrt:T2}),L2=Ig(nf,{Fp:rf,endo:I2}),ht=Dg(L2,fn);function kg(r,e,t){let n=un.digest(e instanceof Uint8Array?e:e.subarray());if(En(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ht.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new jo(String(o))});try{return ht.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new jo(String(o))}}function Rg(r,e,t,n){let o=un.digest(t instanceof Uint8Array?t:t.subarray());if(En(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ht.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Go(String(s))});try{return n?.signal?.throwIfAborted(),ht.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Go(String(s))}}var cs=class{type="secp256k1";raw;_key;constructor(e){this._key=Ng(e),this.raw=Fg(this._key)}toMultihash(){return st.digest(tt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return Rg(this._key,t,e,n)}},Vi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Og(e),this.publicKey=new cs(t??Mg(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return kg(this.raw,e,t)}};function of(r){return new cs(r)}async function Bg(){let r=D2();return new Vi(r)}function Fg(r){return ht.Point.fromBytes(r).toBytes()}function Og(r){try{return ht.getPublicKey(r,!0),r}catch(e){throw new Eo(String(e))}}function Ng(r){try{return ht.Point.fromBytes(r),r}catch(e){throw new tn(String(e))}}function Mg(r){try{return ht.getPublicKey(r,!0)}catch(e){throw new Eo(String(e))}}function D2(){return ht.utils.randomSecretKey()}async function Ug(r,e){if(r==="Ed25519")return km();if(r==="secp256k1")return Bg();if(r==="RSA")return Ql(P2(e));if(r==="ECDSA")return Kp(k2(e));throw new Yt}function Dn(r,e){let{Type:t,Data:n}=Et.decode(r),o=n??new Uint8Array;switch(t){case ae.RSA:return Xl(o,e);case ae.Ed25519:return al(o);case ae.secp256k1:return of(o);case ae.ECDSA:return Du(o);default:throw new Yt}}function Kg(r){let{Type:e,Data:t}=Et.decode(r.digest),n=t??new Uint8Array;switch(e){case ae.Ed25519:return al(n);case ae.secp256k1:return of(n);case ae.ECDSA:return Du(n);default:throw new Yt}}function tt(r){return Et.encode({Type:ae[r.type],Data:r.raw})}function P2(r){return r==null?2048:parseInt(r,10)}function k2(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 R("Unsupported curve, should be P-256, P-384 or P-521")}var zg=Symbol.for("nodejs.util.inspect.custom"),R2=114,us=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()})`}[ui]=!0;toString(){return this.string==null&&(this.string=ne.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return me.createV1(R2,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[zg](){return`PeerId(${this.toString()})`}},ls=class extends us{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},fs=class extends us{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ds=class extends us{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},F2=2336,hs=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=st.digest(N(this.url))}[zg](){return`PeerId(${this.url})`}[ui]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return me.createV1(F2,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var O2=114,qg=2336;function St(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Pt(ne.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ps(me.parse(r));if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Pt(e.decode(r))}return Pn(t)}function sf(r){if(r.type==="Ed25519")return new fs({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ds({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ls({multihash:r.toCID().multihash,publicKey:r});throw new Yt}function $g(r){return sf(r.publicKey)}function Pn(r){if(M2(r))return new ls({multihash:r});if(N2(r))try{let e=Kg(r);if(e.type==="Ed25519")return new fs({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ds({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new hs(new URL(t))}throw new ri("Supplied PeerID Multihash is invalid")}function ps(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==O2&&r.code!==qg)throw new ti("Supplied PeerID CID is invalid");if(r.code===qg){let e=z(r.multihash.digest);return new hs(new URL(e))}return Pn(r.multihash)}function N2(r){return r.code===st.code}function M2(r){return r.code===un.code}async function Vg(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return r}function Hi(r,e){if(typeof r=="string")return B2(r);if(typeof r=="number")return z2(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function B2(r){if(typeof r!="string"||r.length===0||r.length>100)throw new 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 new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function U2(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 K2(r){let e=Math.abs(r);return e>=315576e5?Rr(r,e,315576e5,"year"):e>=26298e5?Rr(r,e,26298e5,"month"):e>=6048e5?Rr(r,e,6048e5,"week"):e>=864e5?Rr(r,e,864e5,"day"):e>=36e5?Rr(r,e,36e5,"hour"):e>=6e4?Rr(r,e,6e4,"minute"):e>=1e3?Rr(r,e,1e3,"second"):`${r} ms`}function z2(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?K2(r):U2(r)}function Rr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function af(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Hi,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,p,g;function m(...y){if(!m.enabled)return;let w=m,x=Number(new Date),_=x-(d||x);w.diff=_,w.prev=d,w.curr=x,d=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let A=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,v)=>{if(I==="%%")return"%";A++;let F=t.formatters[v];if(typeof F=="function"){let Y=y[A];I=F.call(w,Y),y.splice(A,1),A--}return I}),t.formatArgs.call(w,y),f?.onLog!=null&&f.onLog(...y),(w.log||t.log).apply(w,y)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),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,g=t.enabled(l)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var ji=W2(),q2=["#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 $2(){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 V2(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Hi(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 H2=console.debug??console.log??(()=>{});function j2(r){try{r?ji?.setItem("debug",r):ji?.removeItem("debug")}catch{}}function G2(){let r;try{r=ji?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function W2(){try{return localStorage}catch{}}function X2(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Hg=af({formatArgs:V2,save:j2,load:G2,useColors:$2,setupFormatters:X2,colors:q2,storage:ji,log:H2});var Ge=Hg;Ge.formatters.b=r=>r==null?"undefined":ne.baseEncode(r);Ge.formatters.t=r=>r==null?"undefined":et.baseEncode(r);Ge.formatters.m=r=>r==null?"undefined":yu.baseEncode(r);Ge.formatters.p=r=>r==null?"undefined":r.toString();Ge.formatters.c=r=>r==null?"undefined":r.toString();Ge.formatters.k=r=>r==null?"undefined":r.toString();Ge.formatters.a=r=>r==null?"undefined":r.toString();function jg(r,e=""){let t=Gg(r.message),n=Gg(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 Ax(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function um(r,e=""){if(Ax(r)){let t=am(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
- ${e}${r.errors.map(n=>`${um(n,`${e}`)}`).join(`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Y2(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Wg(r,e=""){if(Y2(r)){let t=jg(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
+ ${e}${r.errors.map(n=>`${Wg(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return am(r,e)}Ke.formatters.e=r=>r==null?"undefined":um(r);function _x(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function hi(r){return{forComponent(e){return lm(e,r)}}}function lm(r,e){let t=_x(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ke(`${r}:trace`,e)),Object.assign(Ke(r,e),{error:Ke(`${r}:error`,e),trace:t,newScope:n=>lm(`${r}:${n}`,e)})}function cm(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Er(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 pi(r){let e=St(te.decode(`z${r}`));return wn(e)}var Ze=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 Er(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 Er(this.map.values(),e=>e.key)}values(){return Er(this.map.values(),e=>e.value)}get size(){return this.map.size}};var vr=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 Er(this.set.entries(),e=>{let t=pi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=pi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Er(this.set.values(),e=>pi(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 Tl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},fm={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},dm=new globalThis.TextEncoder;function Cx(r,e){let t=Tl[e],n=fm[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Ix(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Tl[e],o=fm[e],s=r;for(;s.length>0;){let i=dm.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 Ll(r,{size:e=32,utf8Buffer:t}={}){if(!Tl[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 Ix(r,e,t);r=dm.encode(r)}return Cx(r,e)}var zo={hash:r=>Number(Ll(r,{size:32})),hashV:(r,e)=>Tx(zo.hash(r,e))};function Tx(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var Dl=64,ct=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Dl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=qe(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?re(this.fp,e.fp):!1}};function Sr(r,e){return Math.floor(Math.random()*(e-r))+r}var Ar=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ct))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 ct))throw new TypeError("Invalid Fingerprint");let t=Sr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Lx=500,Vo=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??zo,this.seed=e.seed??Sr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new ct(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 Ar(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ar(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Sr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ar(this.bucketSize));for(let a=0;a<Lx;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 Ar(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new ct(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=M(e));let t=new ct(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}},Dx={1:.5,2:.84,4:.95,8:.98};function Px(r=.001){return r>.002?2:r>1e-5?4:8}function hm(r,e=.001){let t=Px(e),n=Dx[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Dl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var mi=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??zo,this.seed=e.seed??Sr(0,Math.pow(2,10)),this.filterSeries=[new Vo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(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 Vo({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=M(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=M(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 Ho(r,e=.001,t){return new mi({...hm(r,e),...t??{}})}function Pl(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function W(r){let e=Pl(r);if(e==null)throw new k(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var gi=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var pm=45,kx=15,xn=new gi;function yi(r){if(!(r.length>kx))return xn.new(r).parseWith(()=>xn.readIPv4Addr())}function bi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pm))return xn.new(r).parseWith(()=>xn.readIPv6Addr())}function En(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>pm)return;let t=xn.new(r).parseWith(()=>xn.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 mm(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 gm(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 kl(r){switch(r.length){case _r:return r.join(".");case Cr:{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 ym(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 bm(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var _r=4,Cr=16,x6=parseInt("0xFFFF",16),Rx=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Wo(r,e){e.length===Cr&&r.length===_r&&mm(e,0,11)&&(e=e.slice(12)),e.length===_r&&r.length===Cr&&gm(r,Rx,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 wm(r,e){if(typeof e=="string"&&(e=En(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 Rl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=_r,o=yi(e);if(o==null&&(n=Cr,o=bi(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=Ol(s,8*n);return{network:Wo(o,i),mask:i}}function Ol(r,e){if(e!==8*_r&&e!==8*Cr)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 vn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Rl(e));else{let n=En(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=En(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ol(o,8*n.length);this.network=Wo(n,this.mask)}}contains(e){return wm({network:this.network,mask:this.mask},e)}toString(){let e=ym(this.mask),t=e!==-1?String(e):bm(this.mask);return kl(this.network)+"/"+t}};function xm(r){try{let e=W(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Em(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function jo(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return Em(e.host);default:return!1}}catch{return!1}}function Se(r){return Pl(r)!==null}function ut(r){return!!yi(r)}function wi(r){return!!bi(r)}var _m=dc(Am(),1),Kx=["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"],qx=Kx.map(r=>new _m.Netmask(r));function ql(r){for(let e of qx)if(e.contains(r))return!0;return!1}function $x(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function zx(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 ql(o)}function Vx(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Hx(r){let e=r.split(":"),t=e[e.length-1];return ql(t)}function Wx(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 Cn(r){if(ut(r))return ql(r);if($x(r))return zx(r);if(Vx(r))return Hx(r);if(wi(r))return Wx(r)}function kt(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return Cn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Cm(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 Ei(r=0){return new Uint8Array(r)}function Go(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ei(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Tm(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Im=Tm("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),$l=Tm("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=Ei(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jx={utf8:Im,"utf-8":Im,hex:Ue.base16,latin1:$l,ascii:$l,binary:$l,...Ue},vi=jx;function Yo(r,e="utf8"){let t=vi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Tr(r,e="utf8"){let t=vi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ae=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Rt=class extends Error{static name="ValidationError";name="ValidationError"},Si=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ai=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Vl(r){return e=>Tr(e,r)}function Hl(r){return e=>Yo(e,r)}function In(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Lr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Lm(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=Yo(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=Lr(n);return Go([t,o],t.length+o.length)}function Dm(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=je.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=Lr(n);return Go([t,o],t.length+o.length)}function Wl(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=Tr(e,"base32"),o=In(t);return`${n}:${o}`}var jl=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 Ae("Invalid byte value in IP address");e[n]=o}),e},Pm=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ut(t[n]),i;s&&(i=jl(t[n]),t[n]=Tr(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,Tr(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 Ae("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},km=function(r){if(r.byteLength!==4)throw new Ae("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Rm=function(r){if(r.byteLength!==16)throw new Ae("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 Ae(`Invalid IPv6 address "${t}"`)}};function Om(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ae(`Invalid IPv6 address "${r}"`)}}var zl=Object.values(Ue).map(r=>r.decoder),Gx=(function(){let r=zl[0].or(zl[1]);return zl.slice(2).forEach(e=>r=r.or(e)),r})();function Nm(r){return Gx.decode(r)}function Mm(r){return e=>r.encoder.encode(e)}function Yx(r){if(parseInt(r).toString()!==r)throw new Rt("Value must be an integer")}function Xx(r){if(r<0)throw new Rt("Value must be a positive integer, or zero")}function Zx(r){return e=>{if(e>r)throw new Rt(`Value must be smaller than or equal to ${r}`)}}function Qx(...r){return e=>{for(let t of r)t(e)}}var Xo=Qx(Yx,Xx,Zx(65535));var we=-1,Gl=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 Ai(`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)}))}},Nt=new Gl,dE=[{code:4,name:"ip4",size:32,valueToBytes:jl,bytesToValue:km,validate:r=>{if(!ut(r))throw new Rt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Lr,bytesToValue:In,validate:Xo},{code:273,name:"udp",size:16,valueToBytes:Lr,bytesToValue:In,validate:Xo},{code:33,name:"dccp",size:16,valueToBytes:Lr,bytesToValue:In,validate:Xo},{code:41,name:"ip6",size:128,valueToBytes:Pm,bytesToValue:Rm,stringToValue:Om,validate:r=>{if(!wi(r))throw new Rt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:we},{code:43,name:"ipcidr",size:8,bytesToValue:Vl("base10"),valueToBytes:Hl("base10")},{code:53,name:"dns",size:we},{code:54,name:"dns4",size:we},{code:55,name:"dns6",size:we},{code:56,name:"dnsaddr",size:we},{code:132,name:"sctp",size:16,valueToBytes:Lr,bytesToValue:In,validate:Xo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:we,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:we,bytesToValue:Vl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Hl("base58btc")(r):fe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Wl,valueToBytes:Lm},{code:445,name:"onion3",size:296,bytesToValue:Wl,valueToBytes:Dm},{code:446,name:"garlic64",size:we},{code:447,name:"garlic32",size:we},{code:448,name:"tls"},{code:449,name:"sni",size:we},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:we,bytesToValue:Mm(ju),valueToBytes:Nm},{code:480,name:"http"},{code:481,name:"http-path",size:we,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:we}];dE.forEach(r=>{Nt.addProtocol(r)});function Fm(r){let e=[],t=0;for(;t<r.length;){let n=gr(r,t),o=Nt.getProtocol(n),s=be(n),i=hE(o,r,t+s),a=0;i>0&&o.size===we&&(a=be(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??Tr(f)}e.push(u),t+=c}return e}function Bm(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Nt.getProtocol(n.code),s=be(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Yo(n.value),a=i.byteLength,o.size===we&&(c=be(a)));let u=new Uint8Array(s+c+a),l=0;pn(n.code,u,l),l+=s,i!=null&&(o.size===we&&(pn(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Go(t,e)}function Um(r){if(r.charAt(0)!=="/")throw new Ae('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=Nt.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 Ae(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ae(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ae("Incomplete multiaddr");return e}function Km(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Nt.getProtocol(e.code);if(t==null)throw new Ae(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function hE(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:gr(e,t)}var pE=Symbol.for("nodejs.util.inspect.custom"),uf=Symbol.for("@multiformats/multiaddr");function mE(r){if(r==null&&(r="/"),nr(r))return r.getComponents();if(r instanceof Uint8Array)return Fm(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Um(r);if(Array.isArray(r))return r;throw new Ae("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Di=class r{[uf]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=mE(e),t.validate!==!1&&gE(this)}get bytes(){return this.#n==null&&(this.#n=Bm(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=Km(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Si(`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 Cm(this.bytes,e.bytes)}[pE](){return`Multiaddr(${this.toString()})`}};function gE(r){r.getComponents().forEach(e=>{let t=Nt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function nr(r){return!!r?.[uf]}function Z(r){return new Di(r)}var ne=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),qm=r=>({match:e=>r.match(e)===!1?e:!1}),$=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ie=(...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}}),j=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function oe(...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 yE=O(421),$m=oe(yE),ki=O(54),Ri=O(55),Oi=O(56),ff=O(53),t8=oe(ki,$(O(421))),r8=oe(Ri,$(O(421))),n8=oe(Oi,$(O(421))),o8=oe(Ie(ff,Oi,ki,Ri),$(O(421))),zm=j(O(4),$(O(43))),Vm=j($(O(42)),O(41),$(O(43))),df=Ie(zm,Vm),Rn=Ie(df,ff,ki,Ri,Oi),s8=oe(Ie(df,j(Ie(ff,Oi,ki,Ri),$(O(421))))),hf=oe(zm),pf=oe(Vm),i8=oe(df),mf=j(Rn,O(6)),Zo=j(Rn,O(273)),Qo=oe(j(mf,$(O(421)))),a8=oe(Zo),gf=j(Zo,ne(460),$(O(421))),Ni=j(Zo,ne(461),$(O(421))),bE=Ie(gf,Ni),c8=oe(gf),Hm=oe(Ni),lf=Ie(Rn,mf,Zo,gf,Ni),Wm=Ie(j(lf,ne(477),$(O(421)))),Pr=oe(Wm),jm=Ie(j(lf,ne(478),$(O(421))),j(lf,ne(448),$(O(449)),ne(477),$(O(421)))),Jo=oe(jm),Gm=j(Zo,ne(280),$(O(466)),$(O(466)),$(O(421))),yf=oe(Gm),Ym=j(Ni,ne(465),$(O(466)),$(O(466)),$(O(421))),bf=oe(Ym),Pi=Ie(Wm,jm,j(mf,$(O(421))),j(bE,$(O(421))),j(Rn,$(O(421))),Gm,Ym,O(421)),u8=oe(Pi),wE=j($(Pi),ne(290),qm(ne(281)),$(O(421))),kr=oe(wE),xE=Ie(j(Pi,ne(290),ne(281),$(O(421))),j(Pi,ne(281),$(O(421))),j(ne(281),$(O(421)))),wf=oe(xE),EE=j(Rn,Ie(j(O(6,"80")),j(O(6),ne(480)),ne(480)),$(O(481)),$(O(421))),l8=oe(EE),vE=j(Rn,Ie(j(O(6,"443")),j(O(6,"443"),ne(480)),j(O(6),ne(443)),j(O(6),ne(448),ne(480)),j(ne(448),ne(480)),ne(448),ne(443)),$(O(481)),$(O(421))),f8=oe(vE),SE=Ie(j(O(777),$(O(421)))),d8=oe(SE),AE=Ie(j(O(400),$(O(421)))),h8=oe(AE);function Xm(r,e){let t=Qo.exactMatch(r),n=Qo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Jo.exactMatch(r),s=Jo.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=Pr.exactMatch(r),a=Pr.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=wf.exactMatch(r),u=wf.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=yf.exactMatch(r),f=yf.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=bf.exactMatch(r),h=bf.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function Zm(r,e){let t=jo(r),n=jo(e);return t&&!n?1:!t&&n?-1:0}function Qm(r,e){let t=kt(r),n=kt(e);return t&&!n?1:!t&&n?-1:0}function Jm(r,e){let t=kr.exactMatch(r),n=kr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function xe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Mi=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}},On=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Mi(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Mi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var xf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nn(r={}){return _E(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 _E(r,e){e=e??{};let t=e.onEnd,n=new On,o,s,i,a=xe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(v){y(v)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=xe()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new On,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?l(m):u({done:!0})),h=()=>(n=new On,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,v;y!=null&&(w=new Promise((T,I)=>{v=()=>{I(new xf)},y.addEventListener("abort",v)}));try{await Promise.race([a.promise,w])}finally{v!=null&&y!=null&&y?.removeEventListener("abort",v)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var Ef=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},eg=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function es(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(eg(i));return}if(i&&(c=()=>{d(eg(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Ef;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var CE=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 IE(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:u,removeListener:l}=CE(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(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=es(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=IE(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ts(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 Fi=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}},Bi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Rr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function TE(r){return r.reason}async function Ve(r,e,t){if(e==null)return r;let n=t?.translateError??TE;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 Ui=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=xe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function LE(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ki=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=LE(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Qe),this.cleanup())}async join(e){let t=new Ui(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ve(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Mn=class extends De{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=ts(this.emitEmpty.bind(this),1),this.emitIdle=ts(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 Bi;let n=new Ki(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Nn({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 Qe("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 wt(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 Fn=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 DE=1.2,PE=2,kE=5e3,RE=6e4,OE=5e3,qi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??OE;this.success=new Fn(t),this.failure=new Fn(t),this.next=new Fn(t),this.failureMultiplier=e.failureMultiplier??PE,this.timeoutMultiplier=e.timeoutMultiplier??DE,this.minTimeout=e.minTimeout??kE,this.maxTimeout=e.maxTimeout??RE,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=wt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var vf=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=xe(),this.haveNext=xe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=xe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=xe(),await Ve(this.readNext.promise,t?.signal,t)}};function tg(){return new vf}function NE(r){return r[Symbol.asyncIterator]!=null}async function ME(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*FE(r){let e=new AbortController,t=tg();ME(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*BE(r){for(let e of r)yield*e}function UE(...r){let e=[];for(let t of r)NE(t)||e.push(t);return e.length===r.length?BE(e):FE(r)}var Bn=UE;var KE=4194304,$i=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Af=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_f=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Cf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function qE(r){return typeof r?.closeRead=="function"}function $E(r){return typeof r?.close=="function"}function Sf(r){return qE(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:$E(r)?r.status!=="open":!1}function zE(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function If(r,e){let t=e?.maxBufferSize??KE,n=new Q,o,s=!1;if(!zE(r))throw new k("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new $i("Stream was unwrapped");if(Sf(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Rr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await Ve(o.promise,l?.signal),Sf(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(Sf(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Rr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(s===!0)throw new $i("Stream was unwrapped");r.send(l)||await lt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function zi(r,e={}){let t=If(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=be(e.maxDataLength));let n=e?.lengthDecoder??gr,o=e?.lengthEncoder??Qt;return{async read(i){let a=-1,c=new Q;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Af("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Cf(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new _f(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Rr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Rr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function rg(r=0){return new Uint8Array(r)}var Vi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Un=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},rs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Wi(r){return r[Symbol.asyncIterator]!=null}function ng(r,e){if(r.byteLength>e)throw new Un("Message length too long")}var Gi=r=>{let e=be(r),t=rg(e);return Qt(r,t),Gi.bytes=e,t};Gi.bytes=0;function Yi(r,e){e=e??{};let t=e.lengthEncoder??Gi,n=e?.maxDataLength??4194304;function*o(s){ng(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Wi(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Yi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Gi,n=e?.maxDataLength??4194304;return ng(r,n),new Q(t(r.byteLength),r)};var Or;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Or||(Or={}));var Lf=r=>{let e=gr(r);return Lf.bytes=be(e),e};Lf.bytes=0;function Tf(r,e){let t=new Q,n=Or.LENGTH,o=-1,s=e?.lengthDecoder??Lf,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Or.LENGTH)try{if(o=s(t),o<0)throw new Vi("Invalid message length");if(o>a)throw new Un("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Or.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Hi("Message length length too long");break}throw u}if(n===Or.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Or.LENGTH}}}return Wi(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new rs("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new rs("Unexpected end of input")})()}Tf.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 Tf(n,{...e??{},onLength:s=>{t=s}})};var Xi=class extends Mn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Zi=class extends Mn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Qi=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 Df}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 Fi("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)}},Df=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 Pf=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 Te(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Pf({name:e,metrics:t}):n=new Map,n}var kf=class extends Ze{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 Rf(r){let{name:e,metrics:t}=r,n;return t!=null?n=new kf({name:e,metrics:t}):n=new Ze,n}var ns;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:qe(0),payloadType:qe(0),payload:qe(0),signature:qe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(ns||(ns={}));var Ji=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Kn=class r{static createFromProtobuf=e=>{let t=ns.decode(e),n=bn(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=og(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 Ji("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=ns.encode({publicKey:Ye(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:re(this.marshal(),e.marshal())}async validate(e,t){let n=og(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},og=(r,e,t)=>{let n=M(r),o=Qt(n.byteLength),s=Qt(e.length),i=Qt(t.length);return new Q(o,n,s,e,i,t)};var sg="libp2p-peer-record",ig=Uint8Array.from([3,1]);var os;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ne((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:qe(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?p.multiaddr=f.bytes():f.skipType(m&7)}return p},function*(f,d,h,p={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(m&7)}})),a);function c(f){return Re(f,i.codec())}i.encode=c;function u(f,d){return ke(f,i.codec(),d)}i.decode=u;function l(f,d){return Oe(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:qe(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new Xe('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new Xe('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Re(i,r.codec())}r.encode=n;function o(i,a){return ke(i,r.codec(),a)}r.decode=o;function s(i,a){return Oe(i,r.codec(),a)}r.stream=s})(os||(os={}));function ag(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 Nr=class r{static createFromProtobuf=e=>{let t=os.decode(e),n=wn(St(t.peerId)),o=(t.addresses??[]).map(i=>Z(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=sg;static CODEC=ig;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=os.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||!ag(this.multiaddrs,e.multiaddrs))}};function HE(r){return r[Symbol.asyncIterator]!=null}function WE(r){if(HE(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 ss=WE;var He=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ea(r,e,t,n){let o=new He(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(){Nf(t,"abort",f),Nf(r,e,u),Nf(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Of(t,"abort",f),Of(r,e,u),Of(r,s,l)})}function Of(r,e,t){r!=null&&(cg(r)?r.addEventListener(e,t):r.addListener(e,t))}function Nf(r,e,t){r!=null&&(cg(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function cg(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var ta=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ra=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 He)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function jE(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var na=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=jE(),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 He),this.cleanup())}async join(e={}){let t=new ra(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 Ve(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 Mf(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 is=class extends De{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=Mf(this.emitEmpty.bind(this),1),this.emitIdle=Mf(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 ta;let n=new na(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 He)}),this.clear()}async onEmpty(e){this.size!==0&&await ea(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ea(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ea(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=Nn({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 He("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 oa="lock:worker:request-read",sa="lock:worker:abort-read-request",ia="lock:worker:release-read",aa="lock:master:grant-read",ca="lock:master:error-read",ua="lock:worker:request-write",la="lock:worker:abort-write-request",fa="lock:worker:release-write",da="lock:master:grant-write",ha="lock:master:error-write",pa="lock:worker:finalize",ma="mortice",ug={singleProcess:!1};var Ff=(r,e,t,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{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===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===pa&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var lg=(r=10)=>Math.random().toString().substring(2,r+2);var ga=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ma)}readLock(e){return this.sendRequest(oa,sa,aa,ca,ia,e)}writeLock(e){return this.sendRequest(ua,la,da,ha,fa,e)}finalize(){this.channel.postMessage({type:pa,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=lg();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);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),u(h)}};this.channel.addEventListener("message",f)})}};var fg=r=>{if(r=Object.assign({},ug,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ma),n=new De;return t.addEventListener("message",Ff(n,t,"requestReadLock","abortReadLockRequest",oa,sa,ca,ia,aa)),t.addEventListener("message",Ff(n,t,"requestWriteLock","abortWriteLockRequest",ua,la,ha,fa,da)),n}return new ga(r.name)};var Mr=new Map,as;function dg(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function GE(r){if(as==null&&(as=fg(r),!dg(as))){let e=as;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Mr.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=Mr.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=Mr.get(n);o?.finalize()})}return as}async function Bf(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new He)};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 hg=(r,e)=>{let t=Mr.get(r);if(t!=null)return t;let n=GE(e);if(dg(n))return t=n,Mr.set(r,t),t;let o=new is({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Bf(s,i);s=new is({concurrency:e.concurrency,autoStart:!1});let a=s,c=Bf(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Bf(o,i)},finalize:()=>{Mr.delete(r)},queue:o},Mr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var YE={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Uf(r){let e=Object.assign({},YE,r);return hg(e.name,e)}var Mt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:"",value:qe(0)},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Re(d,a.codec())}a.encode=u;function l(d,h){return ke(d,a.codec(),h)}a.decode=l;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),us.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:""},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=us.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*us.codec().stream(d,d.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Re(d,a.codec())}a.encode=u;function l(d,h){return ke(d,a.codec(),h)}a.decode=l;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),cs.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new Xe('Decode error - repeated field "addresses" had too many elements');l.addresses.push(cs.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new Xe('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new Ro('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new Ro('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new Xe('Streaming decode error - repeated field "addresses" had too many elements');for(let p of cs.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new Xe('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new Xe('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new Xe('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,r.codec())}r.encode=o;function s(a,c){return ke(a,r.codec(),c)}r.decode=s;function i(a,c){return Oe(a,r.codec(),c)}r.stream=i})(Mt||(Mt={}));var cs;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:qe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(cs||(cs={}));var us;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(us||(us={}));function XE(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=bn(e.publicKey,t);return Cl(n)}function pg(r,e,t){let n=Mt.decode(e);return qn(r,n,t)}function qn(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:XE(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:Z(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function mg(r,e){return ZE(r.addresses,e.addresses)&&QE(r.protocols,e.protocols)&&JE(r.publicKey,e.publicKey)&&ev(r.peerRecordEnvelope,e.peerRecordEnvelope)&&tv(r.metadata,e.metadata)&&rv(r.tags,e.tags)}function ZE(r,e){return yg(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!re(t.multiaddr,n.multiaddr)))}function QE(r,e){return yg(r,e,(t,n)=>t===n)}function JE(r,e){return gg(r,e)}function ev(r,e){return gg(r,e)}function tv(r,e){return bg(r,e,(t,n)=>re(t,n))}function rv(r,e){return bg(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function gg(r,e){return r==null&&e==null?!0:r!=null&&e!=null?re(r,e):!1}function yg(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 bg(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}function wg(r=0){return new Uint8Array(r)}function Eg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xg=Eg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kf=Eg("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=wg(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nv={utf8:xg,"utf-8":xg,hex:Ue.base16,latin1:Kf,ascii:Kf,binary:Kf,...Ue},ya=nv;function vg(r,e="utf8"){let t=ya[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Sg(r,e="utf8"){let t=ya[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ft="/",Ag=new TextEncoder().encode(Ft),ba=Ag[0],Fr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=vg(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]!==ba)throw new Error("Invalid key")}toString(e="utf8"){return Sg(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Ag),this._buf[0]!==ba){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ba,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ba;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return ov(this.baseNamespace())}name(){return sv(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...iv(e.map(t=>t.namespaces()))])}};function ov(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function sv(r){let e=r.split(":");return e[e.length-1]}function iv(r){return[].concat(...r)}var qf="/peers/";function ls(r){if(!Kt(r)||r.type==null)throw new k("Invalid PeerId");let e=r.toCID().toString();return new Fr(`${qf}${e}`)}async function _g(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=Z(i.multiaddr)),!nr(i.multiaddr))throw new k("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),u=s.get(c);u!=null?i.isCertified=u.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(u=>u.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Z(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function xa(r,e,t,n){if(e==null)throw new k("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new k("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new k("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,u=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=wa(d,{validate:Cg})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=wa(d,{validate:Ig,map:Tg})}e.peerRecordEnvelope!=null&&(u=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=wa([...a.entries()],{validate:Cg})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=wa([...h.entries()],{validate:Ig,map:Tg})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=Ye(o.id.publicKey):e.publicKey!=null?l=Ye(e.publicKey):r.publicKey!=null&&(l=Ye(r.publicKey));let f={addresses:await _g(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:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>re(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function wa(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 Cg(r,e){if(typeof r!="string")throw new k("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new k("Metadata value must be a Uint8Array")}function Ig(r,e){if(typeof r!="string")throw new k("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new k("Tag value must be an integer");if(e.value<0||e.value>100)throw new k("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new k("Tag ttl must be an integer");if(e.ttl<0)throw new k("Tag ttl must be between greater than 0")}}function Tg(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 Lg(r){let e=r.toString().split("/")[2],t=fe.parse(e,je);return $o(t)}function $f(r,e,t){let n=Lg(r);return pg(n,e,t)}function av(r,e){return{prefix:qf,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t($f(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t($f(n.key,n.value,e),$f(o.key,o.value,e)))}}var Ea=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=Rf({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:Uf({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(ls(e),t)}async load(e,t){let n=ls(e),o=await this.datastore.get(n,t),s=Mt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new ir;return qn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await xa(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await xa(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await xa(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(av(e??{},this.maxAddressAge),e)){let o=Lg(t);if(o.equals(this.peerId))continue;let s=Mt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield qn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=ls(e),o=await this.datastore.get(n,t),s=Mt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new ir;return{peerPB:s,peer:qn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Mt.encode(t);return await this.datastore.put(ls(e),s,o),{peer:qn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!mg(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 zf=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 Ea(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 ss(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=Kt(t)?t:Kt(t?.expectedPeer)?t.expectedPeer:void 0,s=Kt(t)||t===void 0?n:t,i=await Kn.openAndCertify(e,Nr.DOMAIN,s),a=$o(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=Nr.createFromProtobuf(i.payload),u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=Kn.createFromProtobuf(u.peerRecordEnvelope),f=Nr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},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 Dg(r,e={}){return new zf(r,e)}var va=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function cv(r){return r[Symbol.asyncIterator]!=null}function uv(r){if(cv(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Vf=uv;function lv(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 Pg=lv;function fv(r){return r[Symbol.asyncIterator]!=null}function dv(r,e){let t=0;if(fv(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Pg(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 Br=dv;function hv(r){return r[Symbol.asyncIterator]!=null}function pv(r,e){return hv(r)?(async function*(){yield*(await ss(r)).sort(e)})():(function*(){yield*ss(r).sort(e)})()}var Hf=pv;function mv(r){return r[Symbol.asyncIterator]!=null}function gv(r,e){return mv(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 Wf=gv;var Sa=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 Vf(this.putMany(e,n)),e=[],await Vf(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=Br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Hf(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Br(n,()=>o++>=s)}return e.limit!=null&&(n=Wf(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Br(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Hf(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Br(n,()=>s++>=o)}return e.limit!=null&&(n=Wf(n,e.limit)),n}};var Aa=class extends Sa{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 va;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 Fr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Fr(n),t?.signal?.throwIfAborted()}};var kg=864e13;var _a=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Te({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=W(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Cn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?kg-Date.now():0,lastVerified:o?kg-Date.now():void 0})})}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Se(o))continue;let s=W(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),Z(n)}confirm(e,t){let n=W(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=W(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Ca=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Te({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ut(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Se(n))continue;let o=W(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,Z(i)):e}confirm(e,t){if(!Se(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Se(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var yv={maxObservedAddresses:10},Ia=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Te({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??yv.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&&(kt(e)||xm(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:Z(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 bv={maxObservedAddresses:10},Ta=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Te({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??bv.maxObservedAddresses}get(e,t){if(kt(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:!Se(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(!Se(e))return e.toString();let t=W(e);return`${t.host}-${t.port}-${t.protocol}`}};var Rg=6e4,Og={maxObservedAddresses:10,addressVerificationTTL:Rg*10,addressVerificationRetry:Rg*5},wv=r=>r;function jf(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&yt(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var La=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 Ia(e,t),this.dnsMappings=new _a(e,t),this.ipMappings=new Ca(e,t),this.transportAddresses=new Ta(e,t),this.announceFilter=t.announceFilter??wv,this.observedAddressFilter=Ho(1024),this.addressVerificationTTL=t.addressVerificationTTL??Og.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Og.addressVerificationRetry,this._updatePeerStoreAddresses=ts(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=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Z(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=W(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=jf(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=jf(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=jf(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let 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=Z(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(Z(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ut(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(Z(`/ip${ut(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Se(e))return!1;let t=W(e);if(t.type!=="ip4"||Cn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Pr.exactMatch(s)||Jo.exactMatch(s),s=>Qo.exactMatch(s),s=>Hm.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>W(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!jo(u)).pop();if(a==null)continue;let c=W(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var Ng;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Ng||(Ng={}));var Da=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Pa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},$n=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},fs=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ka=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Ra=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Oa=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},ds=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Na=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Ma=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Fa=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ba=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ua=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},or=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Ur=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ka=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},qa=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Gf=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=hi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ls(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")}},xv=["metrics","connectionProtector","dns"],Ev=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Mg(r={}){let e=new Gf(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ev.includes(o)){let i=e.components[o];if(i==null&&!xv.includes(o))throw new Da(`${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 Fg(r){let e={};for(let t of Object.values(r.components))for(let n of vv(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Sv(t))if(e[n]!==!0)throw new Pa(`Service "${Av(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function vv(r){return Array.isArray(r?.[Qn])?r[Qn]:[]}function Sv(r){return Array.isArray(r?.[yc])?r[yc]:[]}function Av(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Bg(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Pr.matches(e)?!0:kt(e)),r}var J=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function $a(r){if(Kt(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:yt(n),e.forEach(o=>{if(!nr(o))throw new Bt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new k("Multiaddrs must all have the same peer id or have no peer id")}else{let i=yt(s);if(t?.equals(i)!==!0)throw new k("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!$m.exactMatch(n)),{peerId:t,multiaddrs:e}}var _v=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Ug(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_v;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function hs(r){let e=W(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new k(`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 k(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new vn(e.host,t)}function Yf(r){return!kr.exactMatch(r)}function za(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Yf(s)))return n}var Va=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>hs(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 Ze;for(let c of e){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",l)}}}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(l=>{if(Se(c.remoteAddr)){let f=W(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Ug(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 Kg="last-dial-failure",qg="last-dial-success";var $g=100,Ha=50;function Cv(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function zg(r){return r.sort((e,t)=>Zm(e.multiaddr,t.multiaddr)||Qm(e.multiaddr,t.multiaddr)||Jm(e.multiaddr,t.multiaddr)||Cv(e,t)||Xm(e.multiaddr,t.multiaddr))}var Wa=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Zf=dc(Hg(),1);function Qf(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 Lv=100,zn=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=Qf(this.#e,i,(c,u)=>u.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>Lv&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var ms=class extends Zf.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#c;#I=0;#x=0;#u;#l;#a;#i=[];#s=0;#r;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:zn,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#q()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#M(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#F(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#l=void 0,this.#P(),this.#D()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#U()},e))}#_(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#b(){if(this.#r.size===0){if(this.#_(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#M&&this.#F){let o=this.#r.dequeue();this.#t||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#D(),e=!0}}return e}#D(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#P()},this.#c),this.#I=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#u&&this.#_(),this.#n=this.#e?this.#o:0),this.#C(),this.#p()}#C(){for(;this.#b(););}get concurrency(){return this.#g}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#C()}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.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#$(),this.#y.delete(s),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=es(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,p)=>{u=()=>{p(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof zn){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#C(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#_(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async 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.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#q(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#$(){this.#t||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Ga(r){let e=[We.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}function Wg(r=0){return new Uint8Array(r)}function Gg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var jg=Gg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Jf=Gg("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=Wg(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Dv={utf8:jg,"utf-8":jg,hex:Ue.base16,latin1:Jf,ascii:Jf,binary:Jf,...Ue},Yg=Dv;function Xg(r,e="utf8"){let t=Yg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ed=60;function Ya(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:We[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:We[e.type],TTL:e.TTL??e.ttl??ed,data:e.data instanceof Uint8Array?Xg(e.data):e.data}))}}var Pv=4;function td(r,e={}){let t=new ms({concurrency:e.queryConcurrency??Pv});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Ga(o.types).forEach(c=>{i.append("type",We[c])}),o.onProgress?.(new J("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 u=Ya(await c.json());return o.onProgress?.(new J("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function Zg(){return[td("https://cloudflare-dns.com/dns-query"),td("https://dns.google/resolve")]}var e0=dc(Jg(),1);var rd=class{lru;constructor(e){this.lru=(0,e0.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 Ya({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:We[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??ed)*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 t0(r){return new rd(r)}var kv=1e3,Xa=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=t0(e.cacheSize??kv),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["."]=Zg())}async query(e,t={}){let n=Ga(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new J("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 u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new J("dns:error",u))}}throw new Wa(a,`DNS lookup of ${e} ${n} failed`)}};var We;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(We||(We={}));function r0(r={}){return new Xa(r)}var nd=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:[We.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(Z(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=r0()),this.dns)}},Kr=new nd;async function od(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new qa("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 od(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Vn={maxParallelDials:Ha,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Kr}},Za=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Vn.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Vn.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Vn.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Vn.addressDialTimeout,this.connections=t.connections??new Ze,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Vn.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Zi({concurrency:t.maxParallelDials??Vn.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Qe.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}=$a(e);if(n!=null&&t.force!==!0){let i=za(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new J("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new J("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Vr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new J("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new J("dial-queue:start-dial"));let a=wt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??ud,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,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new J("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Vr("Peer had more than maxPeerAddrsToDial");a++;let p=wt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[qg]:M(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Kg]:M(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new As(g.message);u.push(g)}finally{p.clear()}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:Z(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Vr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new ds("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await od(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Fa(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?zg(u):u.sort(this.addressSorter);if(l.length===0)throw new ds(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}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=>!kr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Rv=Object.prototype.toString,Ov=r=>Rv.call(r)==="[object Error]",Nv=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 ld(r){if(!(r&&Ov(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:Nv.has(t)}function Mv(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 Qa(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function fd(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var dd=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 Fv(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 Ja(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Bv(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function Uv({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 dd)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Fv(t,o);if(Ja(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let l=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(l),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Ja(n,a)<=0||Ja(n,a)<=0||i<=0||s instanceof TypeError&&!ld(s)||!await o.shouldRetry(h))throw s;let g=Ja(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let m=Math.min(d,g);return o.signal?.throwIfAborted(),await Bv(m,o),o.signal?.throwIfAborted(),!0}async function hd(r,e={}){if(e={...e},Mv(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,fd("onFailedAttempt",e.onFailedAttempt),fd("shouldRetry",e.shouldRetry),fd("shouldConsumeRetry",e.shouldConsumeRetry),Qa("factor",e.factor,{min:0,allowInfinity:!1}),Qa("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Qa("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Qa("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 Uv({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var ec=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 Xi({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);n0(t)&&(this.queue.has(e)||this.queue.add(async n=>{await hd(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(gc)&&(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=>n0(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 n0(r){for(let e of r.tags.keys())if(e.startsWith(gc))return!0;return!1}var ud=50,pd={maxConnections:$g,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},tc=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??pd.maxConnections,this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");this.connections=new Ze,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=>hs(Z(n))),this.deny=(t.deny??[]).map(n=>hs(Z(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??pd.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??pd.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Va({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Z(n))}),this.dialQueue=new Za(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ha,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Kr},connections:this.connections}),this.reconnectQueue=new ec({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 Ad(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 _d(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([lt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new k("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 Et("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new J("connection:open",e));let{peerId:n,multiaddrs:o}=$a(e);if(this.peerId.equals(n))throw new zr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=za(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 J("dial-queue:already-connected")),t.onProgress?.(new J("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??ud});if(s.status!=="open")throw new sr("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 Bt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new J("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([lt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Se(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Se(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Se(e.remoteAddr)){let o=W(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var $v=1e4,zv="1.0.0",Vv="ping",Hv="ipfs",o0=32,Wv=!0,rc=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Hv}/${Vv}/${zv}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??$v,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Wv,this.timeout=new qi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Qn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=If(o);t=Date.now(),await Promise.all([s.write(gn(o0),{signal:n}),s.read({bytes:o0,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var nc=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:H(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:H(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 $n("No content routers available");let n=this,o=new vr;for await(let s of Bn(...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 $n("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 $n("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 Et;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 Et;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var oc=globalThis.CustomEvent??Event;async function*md(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=xe(),a=xe(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=xe(),await i.promise),l)break;let g={done:!1};s.push(g),p().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new oc("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new oc("task-complete"))})}c=!0,o.dispatchEvent(new oc("task-complete"))}catch(p){u=p,o.dispatchEvent(new oc("task-complete"))}});function f(){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 l=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=xe(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var sc=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:H(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 fs("No peer routers available");if(e.toString()===this.peerId.toString())throw new ka("Should not try to find self");let n=this,o=Bn(...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 ir}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new fs("No peer routers available");let n=this,o=Ho(1024);for await(let s of md((async function*(){let i=Bn(...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 ic=class extends De{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=wt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=xe(),yield(await lt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=wt([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=gn(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 Ve(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 gd=32,yd=64,ac=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=Te({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 Ra(`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 Oa(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:gd,maxOutboundStreams:yd,...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 k("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var cc=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=Te({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Te({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Zn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new k("Transport must have a valid tag");if(this.transports.has(t))throw new k(`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 Ka(`No transport available for address ${String(e)}`);return t?.onProgress?.(new J("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 Et("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 Na)});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 u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),hf.matches(c)?t.ipv4.attempts++:pf.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),hf.matches(c)&&t.ipv4.success++,pf.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Zn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Ma(`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 jg(r,e)}Ge.formatters.e=r=>r==null?"undefined":Wg(r);function Z2(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Gi(r){return{forComponent(e){return Xg(e,r)}}}function Xg(r,e){let t=Z2(`${r}:trace`);return Ge.enabled(`${r}:trace`)&&Ge.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ge(`${r}:trace`,e)),Object.assign(Ge(r,e),{error:Ge(`${r}:error`,e),trace:t,newScope:n=>Xg(`${r}:${n}`,e)})}function Gg(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Fr(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 Wi(r){let e=Pt(ne.decode(`z${r}`));return Pn(e)}var nt=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 Fr(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 Fr(this.map.values(),e=>e.key)}values(){return Fr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Or=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 Fr(this.set.entries(),e=>{let t=Wi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Wi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Fr(this.set.values(),e=>Wi(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 cf={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Yg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Zg=new globalThis.TextEncoder;function Q2(r,e){let t=cf[e],n=Yg[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function J2(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=cf[e],o=Yg[e],s=r;for(;s.length>0;){let i=Zg.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 uf(r,{size:e=32,utf8Buffer:t}={}){if(!cf[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 J2(r,e,t);r=Zg.encode(r)}return Q2(r,e)}var ms={hash:r=>Number(uf(r,{size:32})),hashV:(r,e)=>e1(ms.hash(r,e))};function e1(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),N(e,"base16")}var lf=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>lf)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=He(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?ee(this.fp,e.fp):!1}};function Nr(r,e){return Math.floor(Math.random()*(e-r))+r}var Mr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof pt))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 pt))throw new TypeError("Invalid Fingerprint");let t=Nr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var t1=500,gs=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??ms,this.seed=e.seed??Nr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=N(e));let t=new pt(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 Mr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Mr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Nr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Mr(this.bucketSize));for(let a=0;a<t1;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 Mr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=N(e));let t=new pt(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=N(e));let t=new pt(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}},r1={1:.5,2:.84,4:.95,8:.98};function n1(r=.001){return r>.002?2:r>1e-5?4:8}function Qg(r,e=.001){let t=n1(e),n=r1[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),lf);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Xi=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??ms,this.seed=e.seed??Nr(0,Math.pow(2,10)),this.filterSeries=[new gs({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=N(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 gs({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=N(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=N(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 ys(r,e=.001,t){return new Xi({...Qg(r,e),...t??{}})}function ff(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function G(r){let e=ff(r);if(e==null)throw new R(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Yi=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jg=45,o1=15,kn=new Yi;function Zi(r){if(!(r.length>o1))return kn.new(r).parseWith(()=>kn.readIPv4Addr())}function Qi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jg))return kn.new(r).parseWith(()=>kn.readIPv6Addr())}function Rn(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Jg)return;let t=kn.new(r).parseWith(()=>kn.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 e0(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 t0(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 df(r){switch(r.length){case Br: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 r0(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 n0(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Br=4,Ur=16,B3=parseInt("0xFFFF",16),s1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function bs(r,e){e.length===Ur&&r.length===Br&&e0(e,0,11)&&(e=e.slice(12)),e.length===Br&&r.length===Ur&&t0(r,s1,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 o0(r,e){if(typeof e=="string"&&(e=Rn(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 hf(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Br,o=Zi(e);if(o==null&&(n=Ur,o=Qi(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=pf(s,8*n);return{network:bs(o,i),mask:i}}function pf(r,e){if(e!==8*Br&&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 Fn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=hf(e));else{let n=Rn(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=Rn(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=pf(o,8*n.length);this.network=bs(n,this.mask)}}contains(e){return o0({network:this.network,mask:this.mask},e)}toString(){let e=r0(this.mask),t=e!==-1?String(e):n0(this.mask);return df(this.network)+"/"+t}};function s0(r){try{let e=G(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 i0(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function ws(r){try{let e=G(r);switch(e.type){case"ip4":case"ip6":return i0(e.host);default:return!1}}catch{return!1}}function Ce(r){return ff(r)!==null}function mt(r){return!!Zi(r)}function Ji(r){return!!Qi(r)}var l0=Yc(u0(),1),d1=["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"],h1=d1.map(r=>new l0.Netmask(r));function Ef(r){for(let e of h1)if(e.contains(r))return!0;return!1}function p1(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function m1(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 Ef(o)}function g1(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function y1(r){let e=r.split(":"),t=e[e.length-1];return Ef(t)}function b1(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 Bn(r){if(mt(r))return Ef(r);if(p1(r))return m1(r);if(g1(r))return y1(r);if(Ji(r))return b1(r)}function zt(r){try{let e=G(r);switch(e.type){case"ip4":case"ip6":return Bn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var w1=Math.pow(2,7),x1=Math.pow(2,14),E1=Math.pow(2,21),vf=Math.pow(2,28),Sf=Math.pow(2,35),Af=Math.pow(2,42),_f=Math.pow(2,49),ce=128,Le=127;function Un(r){if(r<w1)return 1;if(r<x1)return 2;if(r<E1)return 3;if(r<vf)return 4;if(r<Sf)return 5;if(r<Af)return 6;if(r<_f)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Cf(r,e,t=0){switch(Un(r)){case 8:e[t++]=r&255|ce,r/=128;case 7:e[t++]=r&255|ce,r/=128;case 6:e[t++]=r&255|ce,r/=128;case 5:e[t++]=r&255|ce,r/=128;case 4:e[t++]=r&255|ce,r>>>=7;case 3:e[t++]=r&255|ce,r>>>=7;case 2:e[t++]=r&255|ce,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function v1(r,e){let t=r[e],n=0;if(n+=t&Le,t<ce||(t=r[e+1],n+=(t&Le)<<7,t<ce)||(t=r[e+2],n+=(t&Le)<<14,t<ce)||(t=r[e+3],n+=(t&Le)<<21,t<ce)||(t=r[e+4],n+=(t&Le)*vf,t<ce)||(t=r[e+5],n+=(t&Le)*Sf,t<ce)||(t=r[e+6],n+=(t&Le)*Af,t<ce)||(t=r[e+7],n+=(t&Le)*_f,t<ce))return n;throw new RangeError("Could not decode varint")}function S1(r,e){let t=r.get(e),n=0;if(n+=t&Le,t<ce||(t=r.get(e+1),n+=(t&Le)<<7,t<ce)||(t=r.get(e+2),n+=(t&Le)<<14,t<ce)||(t=r.get(e+3),n+=(t&Le)<<21,t<ce)||(t=r.get(e+4),n+=(t&Le)*vf,t<ce)||(t=r.get(e+5),n+=(t&Le)*Sf,t<ce)||(t=r.get(e+6),n+=(t&Le)*Af,t<ce)||(t=r.get(e+7),n+=(t&Le)*_f,t<ce))return n;throw new RangeError("Could not decode varint")}function If(r,e=0){return r instanceof Uint8Array?v1(r,e):S1(r,e)}var Ie=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},qt=class extends Error{static name="ValidationError";name="ValidationError"},ta=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ra=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Lf(r){return e=>z(e,r)}function Df(r){return e=>N(e,r)}function Kn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function zr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function f0(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=N(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=zr(n);return Ut([t,o],t.length+o.length)}function d0(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=et.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=zr(n);return Ut([t,o],t.length+o.length)}function Pf(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=Kn(t);return`${n}:${o}`}var kf=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 Ie("Invalid byte value in IP address");e[n]=o}),e},h0=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=mt(t[n]),i;s&&(i=kf(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(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 Ie("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},p0=function(r){if(r.byteLength!==4)throw new Ie("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},m0=function(r){if(r.byteLength!==16)throw new Ie("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 Ie(`Invalid IPv6 address "${t}"`)}};function g0(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ie(`Invalid IPv6 address "${r}"`)}}var Tf=Object.values(Do).map(r=>r.decoder),_1=(function(){let r=Tf[0].or(Tf[1]);return Tf.slice(2).forEach(e=>r=r.or(e)),r})();function y0(r){return _1.decode(r)}function b0(r){return e=>r.encoder.encode(e)}function C1(r){if(parseInt(r).toString()!==r)throw new qt("Value must be an integer")}function I1(r){if(r<0)throw new qt("Value must be a positive integer, or zero")}function T1(r){return e=>{if(e>r)throw new qt(`Value must be smaller than or equal to ${r}`)}}function L1(...r){return e=>{for(let t of r)t(e)}}var xs=L1(C1,I1,T1(65535));var ve=-1,Rf=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 ra(`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)}))}},Vt=new Rf,$1=[{code:4,name:"ip4",size:32,valueToBytes:kf,bytesToValue:p0,validate:r=>{if(!mt(r))throw new qt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:zr,bytesToValue:Kn,validate:xs},{code:273,name:"udp",size:16,valueToBytes:zr,bytesToValue:Kn,validate:xs},{code:33,name:"dccp",size:16,valueToBytes:zr,bytesToValue:Kn,validate:xs},{code:41,name:"ip6",size:128,valueToBytes:h0,bytesToValue:m0,stringToValue:g0,validate:r=>{if(!Ji(r))throw new qt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ve},{code:43,name:"ipcidr",size:8,bytesToValue:Lf("base10"),valueToBytes:Df("base10")},{code:53,name:"dns",size:ve},{code:54,name:"dns4",size:ve},{code:55,name:"dns6",size:ve},{code:56,name:"dnsaddr",size:ve},{code:132,name:"sctp",size:16,valueToBytes:zr,bytesToValue:Kn,validate:xs},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ve,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ve,bytesToValue:Lf("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Df("base58btc")(r):me.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Pf,valueToBytes:f0},{code:445,name:"onion3",size:296,bytesToValue:Pf,valueToBytes:d0},{code:446,name:"garlic64",size:ve},{code:447,name:"garlic32",size:ve},{code:448,name:"tls"},{code:449,name:"sni",size:ve},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ve,bytesToValue:b0(bu),valueToBytes:y0},{code:480,name:"http"},{code:481,name:"http-path",size:ve,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:ve}];$1.forEach(r=>{Vt.addProtocol(r)});function w0(r){let e=[],t=0;for(;t<r.length;){let n=If(r,t),o=Vt.getProtocol(n),s=Un(n),i=V1(o,r,t+s),a=0;i>0&&o.size===ve&&(a=Un(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ne(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??z(f)}e.push(u),t+=c}return e}function x0(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Vt.getProtocol(n.code),s=Un(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??N(n.value),a=i.byteLength,o.size===ve&&(c=Un(a)));let u=new Uint8Array(s+c+a),l=0;Cf(n.code,u,l),l+=s,i!=null&&(o.size===ve&&(Cf(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Ut(t,e)}function E0(r){if(r.charAt(0)!=="/")throw new Ie('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=Vt.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 Ie(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ie(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ie("Incomplete multiaddr");return e}function v0(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Vt.getProtocol(e.code);if(t==null)throw new Ie(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function V1(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:If(e,t)}var H1=Symbol.for("nodejs.util.inspect.custom"),Gf=Symbol.for("@multiformats/multiaddr");function j1(r){if(r==null&&(r="/"),mr(r))return r.getComponents();if(r instanceof Uint8Array)return w0(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),E0(r);if(Array.isArray(r))return r;throw new Ie("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ca=class r{[Gf]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=j1(e),t.validate!==!1&&G1(this)}get bytes(){return this.#n==null&&(this.#n=x0(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=v0(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new ta(`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 ee(this.bytes,e.bytes)}[H1](){return`Multiaddr(${this.toString()})`}};function G1(r){r.getComponents().forEach(e=>{let t=Vt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function mr(r){return!!r?.[Gf]}function Z(r){return new ca(r)}var oe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),S0=r=>({match:e=>r.match(e)===!1?e:!1}),V=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),De=(...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}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function se(...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 W1=M(421),A0=se(W1),la=M(54),fa=M(55),da=M(56),Xf=M(53),_D=se(la,V(M(421))),CD=se(fa,V(M(421))),ID=se(da,V(M(421))),TD=se(De(Xf,da,la,fa),V(M(421))),_0=W(M(4),V(M(43))),C0=W(V(M(42)),M(41),V(M(43))),Yf=De(_0,C0),jn=De(Yf,Xf,la,fa,da),LD=se(De(Yf,W(De(Xf,da,la,fa),V(M(421))))),Zf=se(_0),Qf=se(C0),DD=se(Yf),Jf=W(jn,M(6)),Es=W(jn,M(273)),vs=se(W(Jf,V(M(421)))),PD=se(Es),ed=W(Es,oe(460),V(M(421))),ha=W(Es,oe(461),V(M(421))),X1=De(ed,ha),kD=se(ed),I0=se(ha),Wf=De(jn,Jf,Es,ed,ha),T0=De(W(Wf,oe(477),V(M(421)))),$r=se(T0),L0=De(W(Wf,oe(478),V(M(421))),W(Wf,oe(448),V(M(449)),oe(477),V(M(421)))),Ss=se(L0),D0=W(Es,oe(280),V(M(466)),V(M(466)),V(M(421))),td=se(D0),P0=W(ha,oe(465),V(M(466)),V(M(466)),V(M(421))),rd=se(P0),ua=De(T0,L0,W(Jf,V(M(421))),W(X1,V(M(421))),W(jn,V(M(421))),D0,P0,M(421)),RD=se(ua),Y1=W(V(ua),oe(290),S0(oe(281)),V(M(421))),Vr=se(Y1),Z1=De(W(ua,oe(290),oe(281),V(M(421))),W(ua,oe(281),V(M(421))),W(oe(281),V(M(421)))),nd=se(Z1),Q1=W(jn,De(W(M(6,"80")),W(M(6),oe(480)),oe(480)),V(M(481)),V(M(421))),FD=se(Q1),J1=W(jn,De(W(M(6,"443")),W(M(6,"443"),oe(480)),W(M(6),oe(443)),W(M(6),oe(448),oe(480)),W(oe(448),oe(480)),oe(448),oe(443)),V(M(481)),V(M(421))),OD=se(J1),ev=De(W(M(777),V(M(421)))),ND=se(ev),tv=De(W(M(400),V(M(421)))),MD=se(tv);function k0(r,e){let t=vs.exactMatch(r),n=vs.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Ss.exactMatch(r),s=Ss.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=$r.exactMatch(r),a=$r.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nd.exactMatch(r),u=nd.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=td.exactMatch(r),f=td.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=rd.exactMatch(r),h=rd.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function R0(r,e){let t=ws(r),n=ws(e);return t&&!n?1:!t&&n?-1:0}function F0(r,e){let t=zt(r),n=zt(e);return t&&!n?1:!t&&n?-1:0}function O0(r,e){let t=Vr.exactMatch(r),n=Vr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Se(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var pa=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}},Gn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pa(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 pa(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 od=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Wn(r={}){return rv(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 rv(r,e){e=e??{};let t=e.onEnd,n=new Gn,o,s,i,a=Se(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(x){y(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Se()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new Gn,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?l(m):u({done:!0})),h=()=>(n=new Gn,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,x;y!=null&&(w=new Promise((_,A)=>{x=()=>{A(new od)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,w])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var sd=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},N0=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function As(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(N0(i));return}if(i&&(c=()=>{d(N0(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new sd;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var nv=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 ov(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:u,removeListener:l}=nv(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(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=As(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function gt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=ov(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function _s(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 ma=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}},ga=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Hr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function sv(r){return r.reason}async function Ze(r,e,t){if(e==null)return r;let n=t?.translateError??sv;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 ya=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Se(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function iv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ba=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=iv(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ot),this.cleanup())}async join(e){let t=new ya(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ze(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Xn=class extends Oe{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=_s(this.emitEmpty.bind(this),1),this.emitIdle=_s(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 ga;let n=new ba(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ot)}),this.clear()}async onEmpty(e){this.size!==0&&await gt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await gt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gt(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=Wn({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 ot("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 _t(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 Yn=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 av=1.2,cv=2,uv=5e3,lv=6e4,fv=5e3,wa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??fv;this.success=new Yn(t),this.failure=new Yn(t),this.next=new Yn(t),this.failureMultiplier=e.failureMultiplier??cv,this.timeoutMultiplier=e.timeoutMultiplier??av,this.minTimeout=e.minTimeout??uv,this.maxTimeout=e.maxTimeout??lv,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=_t([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};function M0(r=0){return new Uint8Array(r)}var dv=Math.pow(2,7),hv=Math.pow(2,14),pv=Math.pow(2,21),id=Math.pow(2,28),ad=Math.pow(2,35),cd=Math.pow(2,42),ud=Math.pow(2,49),Q=128,Pe=127;function Cs(r){if(r<dv)return 1;if(r<hv)return 2;if(r<pv)return 3;if(r<id)return 4;if(r<ad)return 5;if(r<cd)return 6;if(r<ud)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mv(r,e,t=0){switch(Cs(r)){case 8:e[t++]=r&255|Q,r/=128;case 7:e[t++]=r&255|Q,r/=128;case 6:e[t++]=r&255|Q,r/=128;case 5:e[t++]=r&255|Q,r/=128;case 4:e[t++]=r&255|Q,r>>>=7;case 3:e[t++]=r&255|Q,r>>>=7;case 2:e[t++]=r&255|Q,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function gv(r,e,t=0){switch(Cs(r)){case 8:e.set(t++,r&255|Q),r/=128;case 7:e.set(t++,r&255|Q),r/=128;case 6:e.set(t++,r&255|Q),r/=128;case 5:e.set(t++,r&255|Q),r/=128;case 4:e.set(t++,r&255|Q),r>>>=7;case 3:e.set(t++,r&255|Q),r>>>=7;case 2:e.set(t++,r&255|Q),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function yv(r,e){let t=r[e],n=0;if(n+=t&Pe,t<Q||(t=r[e+1],n+=(t&Pe)<<7,t<Q)||(t=r[e+2],n+=(t&Pe)<<14,t<Q)||(t=r[e+3],n+=(t&Pe)<<21,t<Q)||(t=r[e+4],n+=(t&Pe)*id,t<Q)||(t=r[e+5],n+=(t&Pe)*ad,t<Q)||(t=r[e+6],n+=(t&Pe)*cd,t<Q)||(t=r[e+7],n+=(t&Pe)*ud,t<Q))return n;throw new RangeError("Could not decode varint")}function bv(r,e){let t=r.get(e),n=0;if(n+=t&Pe,t<Q||(t=r.get(e+1),n+=(t&Pe)<<7,t<Q)||(t=r.get(e+2),n+=(t&Pe)<<14,t<Q)||(t=r.get(e+3),n+=(t&Pe)<<21,t<Q)||(t=r.get(e+4),n+=(t&Pe)*id,t<Q)||(t=r.get(e+5),n+=(t&Pe)*ad,t<Q)||(t=r.get(e+6),n+=(t&Pe)*cd,t<Q)||(t=r.get(e+7),n+=(t&Pe)*ud,t<Q))return n;throw new RangeError("Could not decode varint")}function B0(r,e,t=0){return e==null&&(e=M0(Cs(r))),e instanceof Uint8Array?mv(r,e,t):gv(r,e,t)}function U0(r,e=0){return r instanceof Uint8Array?yv(r,e):bv(r,e)}var ld=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Se(),this.haveNext=Se()}[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=Se(),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=Se(),await Ze(this.readNext.promise,t?.signal,t)}};function K0(){return new ld}function xv(r){return r[Symbol.asyncIterator]!=null}async function Ev(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*vv(r){let e=new AbortController,t=K0();Ev(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Sv(r){for(let e of r)yield*e}function Av(...r){let e=[];for(let t of r)xv(t)||e.push(t);return e.length===r.length?Sv(e):vv(r)}var Zn=Av;var _v=4194304,xa=class extends Error{static name="UnwrappedError";name="UnwrappedError"},dd=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},hd=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},pd=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Cv(r){return typeof r?.closeRead=="function"}function Iv(r){return typeof r?.close=="function"}function fd(r){return Cv(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Iv(r)?r.status!=="open":!1}function Tv(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function md(r,e){let t=e?.maxBufferSize??_v,n=new te,o,s=!1;if(!Tv(r))throw new R("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new xa("Stream was unwrapped");if(fd(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Hr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await Ze(o.promise,l?.signal),fd(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(fd(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Hr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(s===!0)throw new xa("Stream was unwrapped");r.send(l)||await gt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function Ea(r,e={}){let t=md(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Cs(e.maxDataLength));let n=e?.lengthDecoder??U0,o=e?.lengthEncoder??B0;return{async read(i){let a=-1,c=new te;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new dd("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new pd(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new hd(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Hr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Hr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new te(o(i.byteLength),i),a)},async writeV(i,a){let c=new te(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function va(r=0){return new Uint8Array(r)}var Lv=Math.pow(2,7),Dv=Math.pow(2,14),Pv=Math.pow(2,21),gd=Math.pow(2,28),yd=Math.pow(2,35),bd=Math.pow(2,42),wd=Math.pow(2,49),J=128,ke=127;function jr(r){if(r<Lv)return 1;if(r<Dv)return 2;if(r<Pv)return 3;if(r<gd)return 4;if(r<yd)return 5;if(r<bd)return 6;if(r<wd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function kv(r,e,t=0){switch(jr(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 Rv(r,e,t=0){switch(jr(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 Fv(r,e){let t=r[e],n=0;if(n+=t&ke,t<J||(t=r[e+1],n+=(t&ke)<<7,t<J)||(t=r[e+2],n+=(t&ke)<<14,t<J)||(t=r[e+3],n+=(t&ke)<<21,t<J)||(t=r[e+4],n+=(t&ke)*gd,t<J)||(t=r[e+5],n+=(t&ke)*yd,t<J)||(t=r[e+6],n+=(t&ke)*bd,t<J)||(t=r[e+7],n+=(t&ke)*wd,t<J))return n;throw new RangeError("Could not decode varint")}function Ov(r,e){let t=r.get(e),n=0;if(n+=t&ke,t<J||(t=r.get(e+1),n+=(t&ke)<<7,t<J)||(t=r.get(e+2),n+=(t&ke)<<14,t<J)||(t=r.get(e+3),n+=(t&ke)<<21,t<J)||(t=r.get(e+4),n+=(t&ke)*gd,t<J)||(t=r.get(e+5),n+=(t&ke)*yd,t<J)||(t=r.get(e+6),n+=(t&ke)*bd,t<J)||(t=r.get(e+7),n+=(t&ke)*wd,t<J))return n;throw new RangeError("Could not decode varint")}function z0(r,e,t=0){return e==null&&(e=va(jr(r))),e instanceof Uint8Array?kv(r,e,t):Rv(r,e,t)}function q0(r,e=0){return r instanceof Uint8Array?Fv(r,e):Ov(r,e)}var Sa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Aa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Is=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _a(r){return r[Symbol.asyncIterator]!=null}function V0(r,e){if(r.byteLength>e)throw new Qn("Message length too long")}var Ia=r=>{let e=jr(r),t=va(e);return z0(r,t),Ia.bytes=e,t};Ia.bytes=0;function Ta(r,e){e=e??{};let t=e.lengthEncoder??Ia,n=e?.maxDataLength??4194304;function*o(s){V0(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return _a(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ta.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ia,n=e?.maxDataLength??4194304;return V0(r,n),new te(t(r.byteLength),r)};var Gr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Gr||(Gr={}));var Ed=r=>{let e=q0(r);return Ed.bytes=jr(e),e};Ed.bytes=0;function xd(r,e){let t=new te,n=Gr.LENGTH,o=-1,s=e?.lengthDecoder??Ed,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Gr.LENGTH)try{if(o=s(t),o<0)throw new Sa("Invalid message length");if(o>a)throw new Qn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Gr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Aa("Message length length too long");break}throw u}if(n===Gr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Gr.LENGTH}}}return _a(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Is("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Is("Unexpected end of input")})()}xd.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 xd(n,{...e??{},onLength:s=>{t=s}})};var La=class extends Xn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Da=class extends Xn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Pa=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 vd}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 ma("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)}},vd=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 Sd=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 Re(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Sd({name:e,metrics:t}):n=new Map,n}var Ad=class extends nt{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 _d(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ad({name:e,metrics:t}):n=new nt,n}function H0(r=0){return new Uint8Array(r)}var Mv=Math.pow(2,7),Bv=Math.pow(2,14),Uv=Math.pow(2,21),Kv=Math.pow(2,28),zv=Math.pow(2,35),qv=Math.pow(2,42),$v=Math.pow(2,49),We=128;function Cd(r){if(r<Mv)return 1;if(r<Bv)return 2;if(r<Uv)return 3;if(r<Kv)return 4;if(r<zv)return 5;if(r<qv)return 6;if(r<$v)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Vv(r,e,t=0){switch(Cd(r)){case 8:e[t++]=r&255|We,r/=128;case 7:e[t++]=r&255|We,r/=128;case 6:e[t++]=r&255|We,r/=128;case 5:e[t++]=r&255|We,r/=128;case 4:e[t++]=r&255|We,r>>>=7;case 3:e[t++]=r&255|We,r>>>=7;case 2:e[t++]=r&255|We,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Hv(r,e,t=0){switch(Cd(r)){case 8:e.set(t++,r&255|We),r/=128;case 7:e.set(t++,r&255|We),r/=128;case 6:e.set(t++,r&255|We),r/=128;case 5:e.set(t++,r&255|We),r/=128;case 4:e.set(t++,r&255|We),r>>>=7;case 3:e.set(t++,r&255|We),r>>>=7;case 2:e.set(t++,r&255|We),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ka(r,e,t=0){return e==null&&(e=H0(Cd(r))),e instanceof Uint8Array?Vv(r,e,t):Hv(r,e,t)}var Ts;(function(r){let e;r.codec=()=>(e==null&&(e=qe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:He(0),payloadType:He(0),payload:He(0),signature:He(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return ze(s,r.codec(),i)}r.stream=o})(Ts||(Ts={}));var Ra=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Jn=class r{static createFromProtobuf=e=>{let t=Ts.decode(e),n=Dn(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=j0(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 Ra("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=Ts.encode({publicKey:tt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ee(this.marshal(),e.marshal())}async validate(e,t){let n=j0(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},j0=(r,e,t)=>{let n=N(r),o=ka(n.byteLength),s=ka(e.length),i=ka(t.length);return new te(o,n,s,e,i,t)};var G0="libp2p-peer-record",W0=Uint8Array.from([3,1]);var Ls;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=qe((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:He(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?p.multiaddr=f.bytes():f.skipType(m&7)}return p},function*(f,d,h,p={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(m&7)}})),a);function c(f){return Ke(f,i.codec())}i.encode=c;function u(f,d){return Ue(f,i.codec(),d)}i.decode=u;function l(f,d){return ze(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=qe((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:He(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new rt('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new rt('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Ke(i,r.codec())}r.encode=n;function o(i,a){return Ue(i,r.codec(),a)}r.decode=o;function s(i,a){return ze(i,r.codec(),a)}r.stream=s})(Ls||(Ls={}));function X0(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 Wr=class r{static createFromProtobuf=e=>{let t=Ls.decode(e),n=Pn(Pt(t.peerId)),o=(t.addresses??[]).map(i=>Z(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=G0;static CODEC=W0;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=Ls.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||!X0(this.multiaddrs,e.multiaddrs))}};function Gv(r){return r[Symbol.asyncIterator]!=null}function Wv(r){if(Gv(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 Ds=Wv;var Qe=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Fa(r,e,t,n){let o=new Qe(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(){Td(t,"abort",f),Td(r,e,u),Td(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Id(t,"abort",f),Id(r,e,u),Id(r,s,l)})}function Id(r,e,t){r!=null&&(Y0(r)?r.addEventListener(e,t):r.addListener(e,t))}function Td(r,e,t){r!=null&&(Y0(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Y0(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Oa=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Na=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 Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ma=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Xv(),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 Qe),this.cleanup())}async join(e={}){let t=new Na(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ze(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Ld(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 Ps=class extends Oe{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=Ld(this.emitEmpty.bind(this),1),this.emitIdle=Ld(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 Oa;let n=new Ma(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 Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await Fa(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Fa(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Fa(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=Wn({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 Qe("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 Ba="lock:worker:request-read",Ua="lock:worker:abort-read-request",Ka="lock:worker:release-read",za="lock:master:grant-read",qa="lock:master:error-read",$a="lock:worker:request-write",Va="lock:worker:abort-write-request",Ha="lock:worker:release-write",ja="lock:master:grant-write",Ga="lock:master:error-write",Wa="lock:worker:finalize",Xa="mortice",Z0={singleProcess:!1};var Dd=(r,e,t,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{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===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===Wa&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var Q0=(r=10)=>Math.random().toString().substring(2,r+2);var Ya=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Xa)}readLock(e){return this.sendRequest(Ba,Ua,za,qa,Ka,e)}writeLock(e){return this.sendRequest($a,Va,ja,Ga,Ha,e)}finalize(){this.channel.postMessage({type:Wa,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Q0();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);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),u(h)}};this.channel.addEventListener("message",f)})}};var J0=r=>{if(r=Object.assign({},Z0,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Xa),n=new Oe;return t.addEventListener("message",Dd(n,t,"requestReadLock","abortReadLockRequest",Ba,Ua,qa,Ka,za)),t.addEventListener("message",Dd(n,t,"requestWriteLock","abortWriteLockRequest",$a,Va,Ga,Ha,ja)),n}return new Ya(r.name)};var Xr=new Map,ks;function ey(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Yv(r){if(ks==null&&(ks=J0(r),!ey(ks))){let e=ks;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Xr.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=Xr.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=Xr.get(n);o?.finalize()})}return ks}async function Pd(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Qe)};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 ty=(r,e)=>{let t=Xr.get(r);if(t!=null)return t;let n=Yv(e);if(ey(n))return t=n,Xr.set(r,t),t;let o=new Ps({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Pd(s,i);s=new Ps({concurrency:e.concurrency,autoStart:!1});let a=s,c=Pd(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Pd(o,i)},finalize:()=>{Xr.delete(r)},queue:o},Xr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Zv={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function kd(r){let e=Object.assign({},Zv,r);return ty(e.name,e)}var Ht;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=qe((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:"",value:He(0)},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Ke(d,a.codec())}a.encode=u;function l(d,h){return Ue(d,a.codec(),h)}a.decode=l;function f(d,h){return ze(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=qe((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Fs.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:""},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=Fs.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*Fs.codec().stream(d,d.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Ke(d,a.codec())}a.encode=u;function l(d,h){return Ue(d,a.codec(),h)}a.decode=l;function f(d,h){return ze(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=qe((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),Rs.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new rt('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Rs.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new rt('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new ss('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new ss('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new rt('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Rs.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new rt('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new rt('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new rt('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Ke(a,r.codec())}r.encode=o;function s(a,c){return Ue(a,r.codec(),c)}r.decode=s;function i(a,c){return ze(a,r.codec(),c)}r.stream=i})(Ht||(Ht={}));var Rs;(function(r){let e;r.codec=()=>(e==null&&(e=qe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:He(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return ze(s,r.codec(),i)}r.stream=o})(Rs||(Rs={}));var Fs;(function(r){let e;r.codec=()=>(e==null&&(e=qe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return ze(s,r.codec(),i)}r.stream=o})(Fs||(Fs={}));function Qv(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Dn(e.publicKey,t);return sf(n)}function ry(r,e,t){let n=Ht.decode(e);return eo(r,n,t)}function eo(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:Qv(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:Z(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function ny(r,e){return Jv(r.addresses,e.addresses)&&eS(r.protocols,e.protocols)&&tS(r.publicKey,e.publicKey)&&rS(r.peerRecordEnvelope,e.peerRecordEnvelope)&&nS(r.metadata,e.metadata)&&oS(r.tags,e.tags)}function Jv(r,e){return sy(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!ee(t.multiaddr,n.multiaddr)))}function eS(r,e){return sy(r,e,(t,n)=>t===n)}function tS(r,e){return oy(r,e)}function rS(r,e){return oy(r,e)}function nS(r,e){return iy(r,e,(t,n)=>ee(t,n))}function oS(r,e){return iy(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function oy(r,e){return r==null&&e==null?!0:r!=null&&e!=null?ee(r,e):!1}function sy(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 iy(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 Md={};U(Md,{base10:()=>fS});var VR=new Uint8Array(0);function ay(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 jt(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 cy(r){return new TextEncoder().encode(r)}function uy(r){return new TextDecoder().decode(r)}function sS(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var F=c.repeat(g);v<x;++v)F+=r.charAt(_[v]);return F}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),F=m;I!==w;)v[F++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var iS=sS,aS=iS,fy=aS;var Rd=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")}},Fd=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 dy(this,e)}},Od=class{decoders;constructor(e){this.decoders=e}or(e){return dy(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 dy(r,e){return new Od({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Nd=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 Rd(e,t,n),this.decoder=new Fd(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function to({name:r,prefix:e,encode:t,decode:n}){return new Nd(r,e,t,n)}function gr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=fy(t,r);return to({prefix:e,name:r,encode:n,decode:s=>jt(o(s))})}function cS(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 uS(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 lS(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=lS(n);return to({prefix:e,name:r,encode(s){return uS(s,n,t)},decode(s){return cS(s,o,t,r)}})}var fS=gr({prefix:"9",name:"base10",alphabet:"0123456789"});var Bd={};U(Bd,{base16:()=>dS,base16upper:()=>hS});var dS=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hS=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ud={};U(Ud,{base2:()=>pS});var pS=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kd={};U(Kd,{base256emoji:()=>wS});var hy=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}"),mS=hy.reduce((r,e,t)=>(r[t]=e,r),[]),gS=hy.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function yS(r){return r.reduce((e,t)=>(e+=mS[t],e),"")}function bS(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=gS[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wS=to({prefix:"\u{1F680}",name:"base256emoji",encode:yS,decode:bS});var zd={};U(zd,{base32:()=>ro,base32hex:()=>SS,base32hexpad:()=>_S,base32hexpadupper:()=>CS,base32hexupper:()=>AS,base32pad:()=>ES,base32padupper:()=>vS,base32upper:()=>xS,base32z:()=>IS});var ro=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xS=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ES=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vS=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),SS=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),AS=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_S=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),CS=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IS=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qd={};U(qd,{base36:()=>Os,base36upper:()=>TS});var Os=gr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),TS=gr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $d={};U($d,{base58btc:()=>Ct,base58flickr:()=>LS});var Ct=gr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),LS=gr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vd={};U(Vd,{base64:()=>DS,base64pad:()=>PS,base64url:()=>kS,base64urlpad:()=>RS});var DS=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),PS=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),kS=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),RS=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Hd={};U(Hd,{base8:()=>FS});var FS=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jd={};U(jd,{identity:()=>OS});var OS=to({prefix:"\0",name:"identity",encode:r=>uy(r),decode:r=>cy(r)});var iF=new TextEncoder,aF=new TextDecoder;var Wd={};U(Wd,{identity:()=>oA});var BS=gy,py=128,US=127,KS=~US,zS=Math.pow(2,31);function gy(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zS;)e[t++]=r&255|py,r/=128;for(;r&KS;)e[t++]=r&255|py,r>>>=7;return e[t]=r|0,gy.bytes=t-n+1,e}var qS=Gd,$S=128,my=127;function Gd(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Gd.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&my)<<o:(i&my)*Math.pow(2,o),o+=7}while(i>=$S);return Gd.bytes=s-n,t}var VS=Math.pow(2,7),HS=Math.pow(2,14),jS=Math.pow(2,21),GS=Math.pow(2,28),WS=Math.pow(2,35),XS=Math.pow(2,42),YS=Math.pow(2,49),ZS=Math.pow(2,56),QS=Math.pow(2,63),JS=function(r){return r<VS?1:r<HS?2:r<jS?3:r<GS?4:r<WS?5:r<XS?6:r<YS?7:r<ZS?8:r<QS?9:10},eA={encode:BS,decode:qS,encodingLength:JS},tA=eA,Ns=tA;function Ms(r,e=0){return[Ns.decode(r,e),Ns.decode.bytes]}function no(r,e,t=0){return Ns.encode(r,e,t),e}function oo(r){return Ns.encodingLength(r)}function io(r,e){let t=e.byteLength,n=oo(r),o=n+oo(t),s=new Uint8Array(o+t);return no(r,s,0),no(t,s,n),s.set(e,o),new so(r,t,e,s)}function yy(r){let e=jt(r),[t,n]=Ms(e),[o,s]=Ms(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new so(t,o,i,e)}function by(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ay(r.bytes,t.bytes)}}var so=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var wy=0,rA="identity",xy=jt;function nA(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 io(wy,xy(r))}var oA={code:wy,name:rA,encode:xy,digest:nA};var Zd={};U(Zd,{sha256:()=>iA,sha512:()=>aA});var sA=20;function Yd({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Xd(r,e,t,n,o)}var Xd=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??sA,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?Ey(n,this.code,t?.truncate):n.then(o=>Ey(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ey(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 io(e,r)}function Sy(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var iA=Yd({name:"sha2-256",code:18,encode:Sy("SHA-256")}),aA=Yd({name:"sha2-512",code:19,encode:Sy("SHA-512")});function Ay(r,e){let{bytes:t,version:n}=r;return n===0?uA(t,Qd(r),e??Ct.encoder):lA(t,Qd(r),e??ro.encoder)}var _y=new WeakMap;function Qd(r){let e=_y.get(r);if(e==null){let t=new Map;return _y.set(r,t),t}return e}var Qa=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!==Us)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==fA)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=io(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&&by(e.multihash,n.multihash)}toString(e){return Ay(this,e)}toJSON(){return{"/":Ay(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??Cy(n,o,s.bytes))}else if(t[dA]===!0){let{version:n,multihash:o,code:s}=t,i=yy(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!==Us)throw new Error(`Version 0 CID must use dag-pb (code: ${Us}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Cy(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Us,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=jt(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 so(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Ms(e.subarray(t));return t+=d,f},o=n(),s=Us;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=cA(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 Qd(s).set(n,e),s}};function cA(r,e){switch(r[0]){case"Q":{let t=e??Ct;return[Ct.prefix,t.decode(`${Ct.prefix}${r}`)]}case Ct.prefix:{let t=e??Ct;return[Ct.prefix,t.decode(r)]}case ro.prefix:{let t=e??ro;return[ro.prefix,t.decode(r)]}case Os.prefix:{let t=e??Os;return[Os.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 uA(r,e,t){let{prefix:n}=t;if(n!==Ct.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 lA(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 Us=112,fA=18;function Cy(r,e,t){let n=oo(r),o=n+oo(e),s=new Uint8Array(o+t.byteLength);return no(r,s,0),no(e,s,n),s.set(t,o),s}var dA=Symbol.for("@ipld/js-cid/CID");var Jd={...jd,...Ud,...Hd,...Md,...Bd,...zd,...qd,...$d,...Vd,...Kd},LF={...Zd,...Wd};function Iy(r=0){return new Uint8Array(r)}function Ly(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ty=Ly("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),eh=Ly("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=Iy(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),hA={utf8:Ty,"utf-8":Ty,hex:Jd.base16,latin1:eh,ascii:eh,binary:eh,...Jd},Ja=hA;function Dy(r,e="utf8"){let t=Ja[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Py(r,e="utf8"){let t=Ja[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Gt="/",ky=new TextEncoder().encode(Gt),ec=ky[0],Yr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=Dy(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]!==ec)throw new Error("Invalid key")}toString(e="utf8"){return Py(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Gt))}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=ky),this._buf[0]!==ec){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ec,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ec;)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(Gt).slice(1)}type(){return pA(this.baseNamespace())}name(){return mA(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Gt)||(e+=Gt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Gt):new r(e.slice(0,-1).join(Gt))}child(e){return this.toString()===Gt?e:e.toString()===Gt?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(),...gA(e.map(t=>t.namespaces()))])}};function pA(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function mA(r){let e=r.split(":");return e[e.length-1]}function gA(r){return[].concat(...r)}var th="/peers/";function Ks(r){if(!Zt(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Yr(`${th}${e}`)}async function Ry(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=Z(i.multiaddr)),!mr(i.multiaddr))throw new R("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),u=s.get(c);u!=null?i.isCertified=u.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(u=>u.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Z(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function rc(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new R("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,u=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=tc(d,{validate:Fy})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=tc(d,{validate:Oy,map:Ny})}e.peerRecordEnvelope!=null&&(u=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=tc([...a.entries()],{validate:Fy})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=tc([...h.entries()],{validate:Oy,map:Ny})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=tt(o.id.publicKey):e.publicKey!=null?l=tt(e.publicKey):r.publicKey!=null&&(l=tt(r.publicKey));let f={addresses:await Ry(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:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>ee(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function tc(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 Fy(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function Oy(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Ny(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 My(r){let e=r.toString().split("/")[2],t=me.parse(e,et);return ps(t)}function rh(r,e,t){let n=My(r);return ry(n,e,t)}function yA(r,e){return{prefix:th,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(rh(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(rh(n.key,n.value,e),rh(o.key,o.value,e)))}}var nc=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=_d({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:kd({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(Ks(e),t)}async load(e,t){let n=Ks(e),o=await this.datastore.get(n,t),s=Ht.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new xr;return eo(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await rc(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await rc(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await rc(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(yA(e??{},this.maxAddressAge),e)){let o=My(t);if(o.equals(this.peerId))continue;let s=Ht.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield eo(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ks(e),o=await this.datastore.get(n,t),s=Ht.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new xr;return{peerPB:s,peer:eo(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Ht.encode(t);return await this.datastore.put(Ks(e),s,o),{peer:eo(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!ny(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 nh=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 nc(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 Ds(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=Zt(t)?t:Zt(t?.expectedPeer)?t.expectedPeer:void 0,s=Zt(t)||t===void 0?n:t,i=await Jn.openAndCertify(e,Wr.DOMAIN,s),a=ps(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=Wr.createFromProtobuf(i.payload),u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=Jn.createFromProtobuf(u.peerRecordEnvelope),f=Wr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},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 By(r,e={}){return new nh(r,e)}var oc=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function bA(r){return r[Symbol.asyncIterator]!=null}function wA(r){if(bA(r))return(async()=>{for await(let e of r);})();for(let e of r);}var oh=wA;function xA(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 Uy=xA;function EA(r){return r[Symbol.asyncIterator]!=null}function vA(r,e){let t=0;if(EA(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Uy(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 Zr=vA;function SA(r){return r[Symbol.asyncIterator]!=null}function AA(r,e){return SA(r)?(async function*(){yield*(await Ds(r)).sort(e)})():(function*(){yield*Ds(r).sort(e)})()}var sh=AA;function _A(r){return r[Symbol.asyncIterator]!=null}function CA(r,e){return _A(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 ih=CA;var sc=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 oh(this.putMany(e,n)),e=[],await oh(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=Zr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Zr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>sh(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Zr(n,()=>o++>=s)}return e.limit!=null&&(n=ih(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Zr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Zr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>sh(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Zr(n,()=>s++>=o)}return e.limit!=null&&(n=ih(n,e.limit)),n}};var ic=class extends sc{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 oc;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 Yr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Yr(n),t?.signal?.throwIfAborted()}};var Ky=864e13;var ac=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Re({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=G(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=Bn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Ky-Date.now():0,lastVerified:o?Ky-Date.now():void 0})})}remove(e){let t=G(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(!Ce(o))continue;let s=G(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}),Z(n)}confirm(e,t){let n=G(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=G(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 cc=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Re({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=G(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:mt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=G(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(!Ce(n))continue;let o=G(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(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,Z(i)):e}confirm(e,t){if(!Ce(e))return!1;let n=G(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(!Ce(e))return!1;let n=G(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 IA={maxObservedAddresses:10},uc=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Re({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??IA.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&&(zt(e)||s0(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:Z(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 TA={maxObservedAddresses:10},lc=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Re({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??TA.maxObservedAddresses}get(e,t){if(zt(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:!Ce(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(!Ce(e))return e.toString();let t=G(e);return`${t.host}-${t.port}-${t.protocol}`}};var zy=6e4,qy={maxObservedAddresses:10,addressVerificationTTL:zy*10,addressVerificationRetry:zy*5},LA=r=>r;function ah(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&St(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var fc=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 uc(e,t),this.dnsMappings=new ac(e,t),this.ipMappings=new cc(e,t),this.transportAddresses=new lc(e,t),this.announceFilter=t.announceFilter??LA,this.observedAddressFilter=ys(1024),this.addressVerificationTTL=t.addressVerificationTTL??qy.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??qy.addressVerificationRetry,this._updatePeerStoreAddresses=_s(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=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Z(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=G(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=ah(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=ah(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=ah(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let 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=Z(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(Z(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${mt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(Z(`/ip${mt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ce(e))return!1;let t=G(e);if(t.type!=="ip4"||Bn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>$r.exactMatch(s)||Ss.exactMatch(s),s=>vs.exactMatch(s),s=>I0.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>G(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!ws(u)).pop();if(a==null)continue;let c=G(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 $y;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})($y||($y={}));var dc=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},hc=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},ao=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},zs=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},pc=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},mc=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},gc=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},qs=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},yc=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},bc=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},wc=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},xc=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ec=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},yr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Qr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},vc=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Sc=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var ch=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=Gi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>li(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")}},DA=["metrics","connectionProtector","dns"],PA=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Vy(r={}){let e=new ch(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!PA.includes(o)){let i=e.components[o];if(i==null&&!DA.includes(o))throw new dc(`${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 Hy(r){let e={};for(let t of Object.values(r.components))for(let n of kA(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of RA(t))if(e[n]!==!0)throw new hc(`Service "${FA(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function kA(r){return Array.isArray(r?.[Ao])?r[Ao]:[]}function RA(r){return Array.isArray(r?.[tu])?r[tu]:[]}function FA(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function jy(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>$r.matches(e)?!0:zt(e)),r}var re=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Ac(r){if(Zt(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:St(n),e.forEach(o=>{if(!mr(o))throw new Xt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=St(s);if(t?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!A0.exactMatch(n)),{peerId:t,multiaddrs:e}}var OA=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Gy(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??OA;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function $s(r){let e=G(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new R(`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 R(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Fn(e.host,t)}function uh(r){return!Vr.exactMatch(r)}function _c(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>uh(s)))return n}var Cc=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>$s(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 nt;for(let c of e){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",l)}}}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(l=>{if(Ce(c.remoteAddr)){let f=G(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Gy(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 Wy="last-dial-failure",Xy="last-dial-success";var Yy=100,Ic=50;function NA(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Zy(r){return r.sort((e,t)=>R0(e.multiaddr,t.multiaddr)||F0(e.multiaddr,t.multiaddr)||O0(e.multiaddr,t.multiaddr)||NA(e,t)||k0(e.multiaddr,t.multiaddr))}var Tc=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var fh=Yc(Jy(),1);function dh(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 UA=100,co=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=dh(this.#e,i,(c,u)=>u.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>UA&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Hs=class extends fh.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#c;#I=0;#x=0;#u;#l;#a;#i=[];#s=0;#r;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:co,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#z()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#F(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--}#S(){return this.#i.length-this.#s}get#N(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#l=void 0,this.#P(),this.#D()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#U()},e))}#_(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#b(){if(this.#r.size===0){if(this.#_(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#N&&this.#M){let o=this.#r.dequeue();this.#t||(this.#F(t),this.#p()),this.emit("active"),o(),n&&this.#D(),e=!0}}return e}#D(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#P()},this.#c),this.#I=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#u&&this.#_(),this.#n=this.#e?this.#o:0),this.#C(),this.#p()}#C(){for(;this.#b(););}get concurrency(){return this.#g}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#C()}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.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#y.delete(s),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=As(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,p)=>{u=()=>{p(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof co){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#C(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#_(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async 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.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#z(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#q(){this.#t||(this.#O(),this.#p())}#k(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Dc(r){let e=[Je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var yh={};U(yh,{base10:()=>jA});var GN=new Uint8Array(0);function eb(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 Wt(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 tb(r){return new TextEncoder().encode(r)}function rb(r){return new TextDecoder().decode(r)}function KA(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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 g=0,m=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var F=c.repeat(g);v<x;++v)F+=r.charAt(_[v]);return F}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),F=m;I!==w;)v[F++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var zA=KA,qA=zA,ob=qA;var hh=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")}},ph=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 sb(this,e)}},mh=class{decoders;constructor(e){this.decoders=e}or(e){return sb(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 sb(r,e){return new mh({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gh=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 hh(e,t,n),this.decoder=new ph(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function uo({name:r,prefix:e,encode:t,decode:n}){return new gh(r,e,t,n)}function br({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=ob(t,r);return uo({prefix:e,name:r,encode:n,decode:s=>Wt(o(s))})}function $A(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 u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,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 VA(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 HA(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function he({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=HA(n);return uo({prefix:e,name:r,encode(s){return VA(s,n,t)},decode(s){return $A(s,o,t,r)}})}var jA=br({prefix:"9",name:"base10",alphabet:"0123456789"});var bh={};U(bh,{base16:()=>GA,base16upper:()=>WA});var GA=he({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),WA=he({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var wh={};U(wh,{base2:()=>XA});var XA=he({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xh={};U(xh,{base256emoji:()=>e_});var ib=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}"),YA=ib.reduce((r,e,t)=>(r[t]=e,r),[]),ZA=ib.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function QA(r){return r.reduce((e,t)=>(e+=YA[t],e),"")}function JA(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=ZA[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var e_=uo({prefix:"\u{1F680}",name:"base256emoji",encode:QA,decode:JA});var Eh={};U(Eh,{base32:()=>lo,base32hex:()=>o_,base32hexpad:()=>i_,base32hexpadupper:()=>a_,base32hexupper:()=>s_,base32pad:()=>r_,base32padupper:()=>n_,base32upper:()=>t_,base32z:()=>c_});var lo=he({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),t_=he({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),r_=he({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),n_=he({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),o_=he({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),s_=he({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),i_=he({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),a_=he({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),c_=he({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vh={};U(vh,{base36:()=>js,base36upper:()=>u_});var js=br({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),u_=br({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sh={};U(Sh,{base58btc:()=>It,base58flickr:()=>l_});var It=br({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),l_=br({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ah={};U(Ah,{base64:()=>f_,base64pad:()=>d_,base64url:()=>h_,base64urlpad:()=>p_});var f_=he({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),d_=he({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),h_=he({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),p_=he({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _h={};U(_h,{base8:()=>m_});var m_=he({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ch={};U(Ch,{identity:()=>g_});var g_=uo({prefix:"\0",name:"identity",encode:r=>rb(r),decode:r=>tb(r)});var uM=new TextEncoder,lM=new TextDecoder;var Th={};U(Th,{identity:()=>U_});var w_=ub,ab=128,x_=127,E_=~x_,v_=Math.pow(2,31);function ub(r,e,t){e=e||[],t=t||0;for(var n=t;r>=v_;)e[t++]=r&255|ab,r/=128;for(;r&E_;)e[t++]=r&255|ab,r>>>=7;return e[t]=r|0,ub.bytes=t-n+1,e}var S_=Ih,A_=128,cb=127;function Ih(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ih.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&cb)<<o:(i&cb)*Math.pow(2,o),o+=7}while(i>=A_);return Ih.bytes=s-n,t}var __=Math.pow(2,7),C_=Math.pow(2,14),I_=Math.pow(2,21),T_=Math.pow(2,28),L_=Math.pow(2,35),D_=Math.pow(2,42),P_=Math.pow(2,49),k_=Math.pow(2,56),R_=Math.pow(2,63),F_=function(r){return r<__?1:r<C_?2:r<I_?3:r<T_?4:r<L_?5:r<D_?6:r<P_?7:r<k_?8:r<R_?9:10},O_={encode:w_,decode:S_,encodingLength:F_},N_=O_,Gs=N_;function Ws(r,e=0){return[Gs.decode(r,e),Gs.decode.bytes]}function fo(r,e,t=0){return Gs.encode(r,e,t),e}function ho(r){return Gs.encodingLength(r)}function mo(r,e){let t=e.byteLength,n=ho(r),o=n+ho(t),s=new Uint8Array(o+t);return fo(r,s,0),fo(t,s,n),s.set(e,o),new po(r,t,e,s)}function lb(r){let e=Wt(r),[t,n]=Ws(e),[o,s]=Ws(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new po(t,o,i,e)}function fb(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&eb(r.bytes,t.bytes)}}var po=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var db=0,M_="identity",hb=Wt;function B_(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 mo(db,hb(r))}var U_={code:db,name:M_,encode:hb,digest:B_};var Ph={};U(Ph,{sha256:()=>z_,sha512:()=>q_});var K_=20;function Dh({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Lh(r,e,t,n,o)}var Lh=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??K_,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?pb(n,this.code,t?.truncate):n.then(o=>pb(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function pb(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 mo(e,r)}function gb(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var z_=Dh({name:"sha2-256",code:18,encode:gb("SHA-256")}),q_=Dh({name:"sha2-512",code:19,encode:gb("SHA-512")});function yb(r,e){let{bytes:t,version:n}=r;return n===0?V_(t,kh(r),e??It.encoder):H_(t,kh(r),e??lo.encoder)}var bb=new WeakMap;function kh(r){let e=bb.get(r);if(e==null){let t=new Map;return bb.set(r,t),t}return e}var kc=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!==Ys)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==j_)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=mo(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&&fb(e.multihash,n.multihash)}toString(e){return yb(this,e)}toJSON(){return{"/":yb(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??wb(n,o,s.bytes))}else if(t[G_]===!0){let{version:n,multihash:o,code:s}=t,i=lb(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!==Ys)throw new Error(`Version 0 CID must use dag-pb (code: ${Ys}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=wb(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ys,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=Wt(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 po(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Ws(e.subarray(t));return t+=d,f},o=n(),s=Ys;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=$_(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 kh(s).set(n,e),s}};function $_(r,e){switch(r[0]){case"Q":{let t=e??It;return[It.prefix,t.decode(`${It.prefix}${r}`)]}case It.prefix:{let t=e??It;return[It.prefix,t.decode(r)]}case lo.prefix:{let t=e??lo;return[lo.prefix,t.decode(r)]}case js.prefix:{let t=e??js;return[js.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 V_(r,e,t){let{prefix:n}=t;if(n!==It.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 H_(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 Ys=112,j_=18;function wb(r,e,t){let n=ho(r),o=n+ho(e),s=new Uint8Array(o+t.byteLength);return fo(r,s,0),fo(e,s,n),s.set(t,o),s}var G_=Symbol.for("@ipld/js-cid/CID");var Rh={...Ch,...wh,..._h,...yh,...bh,...Eh,...vh,...Sh,...Ah,...xh},kM={...Ph,...Th};function xb(r=0){return new Uint8Array(r)}function vb(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Eb=vb("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Fh=vb("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=xb(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),W_={utf8:Eb,"utf-8":Eb,hex:Rh.base16,latin1:Fh,ascii:Fh,binary:Fh,...Rh},Sb=W_;function Ab(r,e="utf8"){let t=Sb[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Oh=60;function Rc(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:Je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Je[e.type],TTL:e.TTL??e.ttl??Oh,data:e.data instanceof Uint8Array?Ab(e.data):e.data}))}}var X_=4;function Nh(r,e={}){let t=new Hs({concurrency:e.queryConcurrency??X_});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Dc(o.types).forEach(c=>{i.append("type",Je[c])}),o.onProgress?.(new re("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 u=Rc(await c.json());return o.onProgress?.(new re("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function _b(){return[Nh("https://cloudflare-dns.com/dns-query"),Nh("https://dns.google/resolve")]}var Tb=Yc(Ib(),1);var Mh=class{lru;constructor(e){this.lru=(0,Tb.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 Rc({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:Je[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??Oh)*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 Lb(r){return new Mh(r)}var Y_=1e3,Fc=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Lb(e.cacheSize??Y_),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["."]=_b())}async query(e,t={}){let n=Dc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new re("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 u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new re("dns:error",u))}}throw new Tc(a,`DNS lookup of ${e} ${n} failed`)}};var Je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Je||(Je={}));function Db(r={}){return new Fc(r)}var Bh=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:[Je.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(Z(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Db()),this.dns)}},Jr=new Bh;async function Uh(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Sc("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 Uh(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var go={maxParallelDials:Ic,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Jr}},Oc=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??go.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??go.maxDialQueueLength,this.dialTimeout=t.dialTimeout??go.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??go.addressDialTimeout,this.connections=t.connections??new nt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??go.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Da({concurrency:t.maxParallelDials??go.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==ot.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}=Ac(e);if(n!=null&&t.force!==!0){let i=_c(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new re("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new re("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new nn("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new re("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new re("dial-queue:start-dial"));let a=_t([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Vh,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,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new re("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new nn("Peer had more than maxPeerAddrsToDial");a++;let p=_t([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[Xy]:N(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Wy]:N(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new si(g.message);u.push(g)}finally{p.clear()}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:Z(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new nn("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new qs("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Uh(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new wc(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?Zy(u):u.sort(this.addressSorter);if(l.length===0)throw new qs(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}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 Z_=Object.prototype.toString,Q_=r=>Z_.call(r)==="[object Error]",J_=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 Hh(r){if(!(r&&Q_(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:J_.has(t)}function eC(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 Nc(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function jh(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Gh=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 tC(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 Mc(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function rC(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function nC({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 Gh)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=tC(t,o);if(Mc(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let l=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(l),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Mc(n,a)<=0||Mc(n,a)<=0||i<=0||s instanceof TypeError&&!Hh(s)||!await o.shouldRetry(h))throw s;let g=Mc(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let m=Math.min(d,g);return o.signal?.throwIfAborted(),await rC(m,o),o.signal?.throwIfAborted(),!0}async function Wh(r,e={}){if(e={...e},eC(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,jh("onFailedAttempt",e.onFailedAttempt),jh("shouldRetry",e.shouldRetry),jh("shouldConsumeRetry",e.shouldConsumeRetry),Nc("factor",e.factor,{min:0,allowInfinity:!1}),Nc("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Nc("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Nc("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 nC({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Bc=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 La({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);Pb(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Wh(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(eu)&&(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=>Pb(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 Pb(r){for(let e of r.tags.keys())if(e.startsWith(eu))return!0;return!1}var Vh=50,Xh={maxConnections:Yy,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Uc=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??Xh.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new nt,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=>$s(Z(n))),this.deny=(t.deny??[]).map(n=>$s(Z(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Xh.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Pa({points:t.inboundConnectionThreshold??Xh.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Cc({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Z(n))}),this.dialQueue=new Oc(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ic,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Jr},connections:this.connections}),this.reconnectQueue=new Bc({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 sp(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 ip(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([gt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new R("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 Lt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new re("connection:open",e));let{peerId:n,multiaddrs:o}=Ac(e);if(this.peerId.equals(n))throw new rn("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=_c(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 re("dial-queue:already-connected")),t.onProgress?.(new re("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Vh});if(s.status!=="open")throw new wr("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 Xt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new re("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([gt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ce(e.remoteAddr)){let s=G(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(Ce(e.remoteAddr)){let s=G(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(Ce(e.remoteAddr)){let o=G(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=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var iC=1e4,aC="1.0.0",cC="ping",uC="ipfs",kb=32,lC=!0,Kc=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??uC}/${cC}/${aC}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??iC,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??lC,this.timeout=new wa({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ao]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=md(o);t=Date.now(),await Promise.all([s.write(Tn(kb),{signal:n}),s.read({bytes:kb,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var zc=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:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(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 ao("No content routers available");let n=this,o=new Or;for await(let s of Zn(...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 ao("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 ao("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 Lt;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 Lt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var qc=globalThis.CustomEvent??Event;async function*Yh(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Se(),a=Se(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=Se(),await i.promise),l)break;let g={done:!1};s.push(g),p().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new qc("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new qc("task-complete"))})}c=!0,o.dispatchEvent(new qc("task-complete"))}catch(p){u=p,o.dispatchEvent(new qc("task-complete"))}});function f(){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 l=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=Se(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var $c=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:z(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 zs("No peer routers available");if(e.toString()===this.peerId.toString())throw new pc("Should not try to find self");let n=this,o=Zn(...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 xr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new zs("No peer routers available");let n=this,o=ys(1024);for await(let s of Yh((async function*(){let i=Zn(...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 Vc=class extends Oe{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=_t([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Se(),yield(await gt(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=_t([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ze(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Zh=32,Qh=64,Hc=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=Re({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 mc(`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 gc(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Zh,maxOutboundStreams:Qh,...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 R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var jc=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=Re({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Re({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??So.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`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 vc(`No transport available for address ${String(e)}`);return t?.onProgress?.(new re("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Lt("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 yc)});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 u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),Zf.matches(c)?t.ipv4.attempts++:Qf.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),Zf.matches(c)&&t.ipv4.success++,Qf.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===So.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new bc(`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}: ${`${jv(i)}`.split(`
14
+ ${s}: ${`${fC(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 jv(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var xt="/multistream/1.0.0";var Gv=M(`
18
- `);async function gs(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Gv[0])throw new Ss("Missing newline");return H(n).trimEnd()}async function Hn(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=zi(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"]',xt,i);let c=M(`${xt}
19
- `),u=M(`${i}
20
- `);if(await o.writeV([c,u],t),n.trace("reading multistream-select header"),a=await gs(o,t),n.trace('read "%s"',a),a!==xt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(M(`${i}
21
- `),t);if(n.trace("reading protocol response"),a=await gs(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new vs(`Protocol selection failed - could not negotiate ${e}`)}async function Wn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=zi(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await gs(o,t);if(n.trace('read "%s"',s),s===xt){n.trace('respond with "%s" for "%s"',xt,s),await o.write(M(`${xt}
22
- `),t),n.trace('responded with "%s" for "%s"',xt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(M(`${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=>Yi.single(M(`${a}
24
- `))),M(`
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(M(`na
26
- `),t),n('responded with "na" for "%s"',s)}}var wd=class extends De{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=Yf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Is(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Sd]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new or("Connection is not multiplexed");if(this.muxer.status!=="open")throw new sr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new sr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Xn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new J("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Hn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Zv(n.protocol,this.components.registrar,t),s=c0(n.protocol,"outbound",this);if(s>o){let c=new Cs(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new J("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await Wn(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Xv(t.protocol,this.components.registrar);if(c0(t.protocol,"inbound",this)>o)throw new _s(`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 Xn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),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,(u,l)=>{e=u,t=l,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 u0(r,e){return new wd(r,e)}function Xv(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 gd}function Zv(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??yd}function c0(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var uc=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Te({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Te({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 Ba(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=wt([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 Ua("Connection denied");await Ve(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=yt(n),await Ve(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,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(Qv(n)){if(n.remotePeer==null)throw new Bt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=yt(f)),n?.onProgress?.(new J(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new zr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new J(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=u0(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 Wn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Ur(`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 Ur(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 Hn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Ur(`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 Ur(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 Hn(e,o,n),i=t.get(s);if(i==null)throw new or(`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 or(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 Wn(e,o,n),i=t.get(s);if(i==null)throw new or(`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 Qv(r){return r.skipEncryption===!0}var lc="3.3.2-29797a5bb",fc="js-libp2p";function f0(r,e){return`${r??fc}/${e??lc} browser/${globalThis.navigator.userAgent}`}var ys=class extends De{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new De,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??hi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??fc,s=e.nodeInfo?.version??lc,i=this.components=Mg({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??f0(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Aa,connectionGater:Bg(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Dg(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new uc(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new cc(this.components,e.transportManager)),this.configureComponent("connectionManager",new tc(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new rc(this.components,e.connectionMonitor)),this.configureComponent("registrar",new ac(this.components)),this.configureComponent("addressManager",new La(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new sc(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new nc(this.components,{routers:c})),this.configureComponent("randomWalk",new ic(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[hc]!=null&&(this.log("registering service %s for content routing",u),c.push(f[hc])),f[mc]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[mc])),f[pc]!=null&&(this.log("registering service %s for peer discovery",u),f[pc].addEventListener?.("peer",d=>{this.#e(d)}))}Fg(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 vr;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 k("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new k("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={}){nr(e)&&(e=yt(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=Pu([M("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=bn(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 Jv(r={}){r.privateKey??=await em("Ed25519");let e=new ys({...await sm(r),peerId:om(r.privateKey)});return r.start!==!1&&await e.start(),e}var e1=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function t1(r){return r==null?!1:r instanceof ys?!0:e1.every(e=>typeof r[e]=="function")}return y0(r1);})();
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 fC(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var Tt="/multistream/1.0.0";var dC=N(`
18
+ `);async function Zs(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==dC[0])throw new oi("Missing newline");return z(n).trimEnd()}async function yo(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=Ea(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"]',Tt,i);let c=N(`${Tt}
19
+ `),u=N(`${i}
20
+ `);if(await o.writeV([c,u],t),n.trace("reading multistream-select header"),a=await Zs(o,t),n.trace('read "%s"',a),a!==Tt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(N(`${i}
21
+ `),t);if(n.trace("reading protocol response"),a=await Zs(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new ni(`Protocol selection failed - could not negotiate ${e}`)}async function bo(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Ea(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Zs(o,t);if(n.trace('read "%s"',s),s===Tt){n.trace('respond with "%s" for "%s"',Tt,s),await o.write(N(`${Tt}
22
+ `),t),n.trace('responded with "%s" for "%s"',Tt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(N(`${s}
23
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new te(...e.map(a=>Ta.single(N(`${a}
24
+ `))),N(`
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(N(`na
26
+ `),t),n('responded with "na" for "%s"',s)}}var ep=class extends Oe{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=uh(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 ci(n.local,n.error))})}[Symbol.toStringTag]="Connection";[op]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new yr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new wr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new wr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new vo("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new re("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await yo(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=mC(n.protocol,this.components.registrar,t),s=Nb(n.protocol,"outbound",this);if(s>o){let c=new ai(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new re("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await bo(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=pC(t.protocol,this.components.registrar);if(Nb(t.protocol,"inbound",this)>o)throw new ii(`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 vo("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),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,(u,l)=>{e=u,t=l,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 Mb(r,e){return new ep(r,e)}function pC(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 Zh}function mC(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??Qh}function Nb(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Gc=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Re({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Re({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 xc(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=_t([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 Ec("Connection denied");await Ze(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=St(n),await Ze(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(gC(n)){if(n.remotePeer==null)throw new Xt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=St(f)),n?.onProgress?.(new re(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new rn("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new re(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=Mb(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 bo(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Qr(`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 Qr(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 yo(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Qr(`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 Qr(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 yo(e,o,n),i=t.get(s);if(i==null)throw new yr(`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 yr(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 bo(e,o,n),i=t.get(s);if(i==null)throw new yr(`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 gC(r){return r.skipEncryption===!0}var Wc="3.3.2-5b8813abc",Xc="js-libp2p";function Ub(r,e){return`${r??Xc}/${e??Wc} browser/${globalThis.navigator.userAgent}`}var Qs=class extends Oe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Oe,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??Gi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Xc,s=e.nodeInfo?.version??Wc,i=this.components=Vy({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Ub(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ic,connectionGater:jy(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",By(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Gc(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new jc(this.components,e.transportManager)),this.configureComponent("connectionManager",new Uc(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Kc(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Hc(this.components)),this.configureComponent("addressManager",new fc(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new $c(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new zc(this.components,{routers:c})),this.configureComponent("randomWalk",new Vc(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Zc]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Zc])),f[Jc]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Jc])),f[Qc]!=null&&(this.log("registering service %s for peer discovery",u),f[Qc].addEventListener?.("peer",d=>{this.#e(d)}))}Hy(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 Or;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 R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("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={}){mr(e)&&(e=St(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=Ut([N("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Dn(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 yC(r={}){r.privateKey??=await Ug("Ed25519");let e=new Qs({...await Vg(r),peerId:$g(r.privateKey)});return r.start!==!1&&await e.start(),e}var bC=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function wC(r){return r==null?!1:r instanceof Qs?!0:bC.every(e=>typeof r[e]=="function")}return Hb(xC);})();
27
27
  /*! Bundled license information:
28
28
 
29
29
  @noble/curves/utils.js: