libp2p 3.4.0 → 3.5.0

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 qm=Object.create;var jo=Object.defineProperty;var $m=Object.getOwnPropertyDescriptor;var zm=Object.getOwnPropertyNames;var Vm=Object.getPrototypeOf,Hm=Object.prototype.hasOwnProperty;var Rn=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},$e=(r,e)=>{for(var t in e)jo(r,t,{get:e[t],enumerable:!0})},_f=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zm(e))!Hm.call(r,o)&&o!==t&&jo(r,o,{get:()=>e[o],enumerable:!(n=$m(e,o))||n.enumerable});return r};var Va=(r,e,t)=>(t=r!=null?qm(Vm(r)):{},_f(e||!r||!r.__esModule?jo(t,"default",{value:r,enumerable:!0}):t,r)),Wm=r=>_f(jo({},"__esModule",{value:!0}),r);var zl=Rn(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.Netmask4Impl=void 0;cn.ip2long=an;cn.long2ip=xt;function xt(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 ub=48,fb=97,db=65;function hb(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)-ub)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-fb)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-db)>>>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 an(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]=hb(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 $l=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=an(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=(an(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=xt(this.netLong),this.mask=xt(this.maskLong),this.hostmask=xt(~this.maskLong),this.first=this.bitmask<=30?xt(this.netLong+1):this.base,this.last=this.bitmask<=30?xt(this.netLong+this.size-2):xt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?xt(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):(an(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(xt(this.netLong+this.size*e),this.mask)}forEach(e){let t=an(this.first),n=an(this.last),o=0;for(;t<=n;)e(xt(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};cn.Netmask4Impl=$l});var ap=Rn(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.Netmask6Impl=void 0;ln.ip6bigint=Hl;ln.bigint2ip6=Sr;var pb=zl(),Vl=(1n<<128n)-1n;function Hl(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,pb.ip2long)(n),s=r.substring(0,t+1)+"0:0";return ip(s)&~0xffffffffn|BigInt(o)}return ip(r)}function ip(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 Sr(r){if(r<0n||r>Vl)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 Wl=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=Vl>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Hl(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Sr(this.netBigint),this.mask=Sr(this.maskBigint),this.hostmask=Sr(~this.maskBigint&Vl),this.first=this.base,this.last=Sr(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):(Hl(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Sr(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(Sr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};ln.Netmask6Impl=Wl});var cp=Rn(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.long2ip=Qt.ip2long=Qt.Netmask=void 0;var Js=zl();Object.defineProperty(Qt,"ip2long",{enumerable:!0,get:function(){return Js.ip2long}});Object.defineProperty(Qt,"long2ip",{enumerable:!0,get:function(){return Js.long2ip}});var mb=ap(),jl=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 mb.Netmask6Impl(e,t):this._impl=new Js.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 Js.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()}};Qt.Netmask=jl});var vm=Rn((FP,ef)=>{"use strict";var ex=Object.prototype.hasOwnProperty,qe="~";function zo(){}Object.create&&(zo.prototype=Object.create(null),new zo().__proto__||(qe=!1));function tx(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Em(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new tx(t,n||r,o),i=qe?qe+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 Aa(r,e){--r._eventsCount===0?r._events=new zo:delete r._events[e]}function Oe(){this._events=new zo,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ex.call(t,n)&&e.push(qe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Oe.prototype.listeners=function(e){var t=qe?qe+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};Oe.prototype.listenerCount=function(e){var t=qe?qe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Oe.prototype.emit=function(e,t,n,o,s,i){var a=qe?qe+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Oe.prototype.on=function(e,t,n){return Em(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Em(this,e,t,n,!0)};Oe.prototype.removeListener=function(e,t,n,o){var s=qe?qe+e:e;if(!this._events[s])return this;if(!t)return Aa(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Aa(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Aa(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Aa(this,t)):(this._events=new zo,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=qe;Oe.EventEmitter=Oe;typeof ef<"u"&&(ef.exports=Oe)});var _m=Rn((i4,Am)=>{Am.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Lx={};$e(Lx,{createLibp2p:()=>Ix,dnsaddrResolver:()=>Nr,isLibp2p:()=>Tx});var If=Symbol.for("@libp2p/connection");var Ha=Symbol.for("@libp2p/content-routing");var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Go=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}};var C=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Mt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},kn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var rr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Yo=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},nr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Mr=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"}},Xo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Zo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Qo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Jo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var es=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},St=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Br=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var On=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ts=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},rs=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ns=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Wa=Symbol.for("@libp2p/peer-discovery");var os=Symbol.for("@libp2p/peer-id");function Ut(r){return!!r?.[os]}var ja=Symbol.for("@libp2p/peer-routing");var Ga="keep-alive";function ss(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Cf(...r){let e=[];for(let t of r)ss(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 Tf(...r){let e=[];for(let t of r)ss(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 Nn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Nn||(Nn={}));function jm(r){return typeof r?.handleEvent=="function"}function Gm(r){return r===!0||r===!1}function Ym(r){return Gm(r)?r:r?.capture??!1}function Ya(r){let e={capture:Ym(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function Lf(r,e){return Ya(r).capture===Ya(e).capture}var Ne=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=Ya(n);if(o?.signal?.aborted===!0)return;let s=l=>{o.once&&this.removeEventListener(e,t,o),jm(t)?t.handleEvent(l):t(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==t?!1:Lf(l.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&Lf(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Mn=Symbol.for("@libp2p/service-capabilities"),Xa=Symbol.for("@libp2p/service-dependencies");var tc={};$e(tc,{base58btc:()=>se,base58flickr:()=>ng});var hE=new Uint8Array(0);function Df(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 Je(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return or(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return or(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Rf(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Pf=4096;function kf(r){let e=r.length;if(e<=Pf)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Pf));return t}function Xm(r){return r?.buffer instanceof ArrayBuffer}function or(r){return Xm(r)?r:r.slice()}function Zm(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}var u=r.length,f=r.charAt(0),d=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function b(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,w=0,A=0,S=y.length;A!==S&&y[A]===0;)A++,v++;for(var B=(S-A)*h+1>>>0,F=new Uint8Array(B);A!==S;){for(var M=y[A],P=0,O=B-1;(M!==0||P<w)&&O!==-1;O--,P++)M+=256*F[O]>>>0,F[O]=M%u>>>0,M=M/u>>>0;if(M!==0)throw new Error("Non-zero carry");w=P,A++}for(var j=B-w;j!==B&&F[j]===0;)j++;for(var W=f.repeat(v);j<B;++j)W+=r.charAt(F[j]);return W}function m(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var v=0;if(y[v]!==" "){for(var w=0,A=0;y[v]===f;)w++,v++;for(var S=(y.length-v)*d+1>>>0,B=new Uint8Array(S);y[v];){var F=n[y.charCodeAt(v)];if(F===255)return;for(var M=0,P=S-1;(F!==0||M<A)&&P!==-1;P--,M++)F+=u*B[P]>>>0,B[P]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");A=M,v++}if(y[v]!==" "){for(var O=S-A;O!==S&&B[O]===0;)O++;for(var j=new Uint8Array(w+(S-O)),W=w;O!==S;)j[W++]=B[O++];return j}}}function g(y){var v=m(y);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:b,decodeUnsafe:m,decode:g}}var Qm=Zm,Jm=Qm,Nf=Jm;var Za=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")}},Qa=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 Mf(this,e)}},Ja=class{decoders;constructor(e){this.decoders=e}or(e){return Mf(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 Mf(r,e){return new Ja({...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 Za(e,t,n),this.decoder=new Qa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new ec(r,e,t,n)}function Kt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Nf(t,r,n);return Fr({prefix:e,name:r,encode:o,decode:i=>Je(s(i))})}function eg(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function tg(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 rg(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function ye({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=rg(n,o);return Fr({prefix:e,name:r,encode(i){return tg(i,n,t)},decode(i){return eg(i,s,t,r)}})}var se=Kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ng=Kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var rc={};$e(rc,{base32:()=>et,base32hex:()=>ag,base32hexpad:()=>lg,base32hexpadupper:()=>ug,base32hexupper:()=>cg,base32pad:()=>sg,base32padupper:()=>ig,base32upper:()=>og,base32z:()=>fg});var et=ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),og=ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),sg=ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),ig=ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ag=ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),cg=ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),lg=ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),ug=ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),fg=ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nc={};$e(nc,{base36:()=>Bn,base36upper:()=>dg});var Bn=Kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),dg=Kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var hg=Uf,Bf=128,pg=127,mg=~pg,gg=Math.pow(2,31);function Uf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gg;)e[t++]=r&255|Bf,r/=128;for(;r&mg;)e[t++]=r&255|Bf,r>>>=7;return e[t]=r|0,Uf.bytes=t-n+1,e}var yg=oc,bg=128,Ff=127;function oc(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw oc.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ff)<<o:(i&Ff)*Math.pow(2,o),o+=7}while(i>=bg);return oc.bytes=s-n,t}var wg=Math.pow(2,7),xg=Math.pow(2,14),Eg=Math.pow(2,21),vg=Math.pow(2,28),Sg=Math.pow(2,35),Ag=Math.pow(2,42),_g=Math.pow(2,49),Ig=Math.pow(2,56),Cg=Math.pow(2,63),Tg=function(r){return r<wg?1:r<xg?2:r<Eg?3:r<vg?4:r<Sg?5:r<Ag?6:r<_g?7:r<Ig?8:r<Cg?9:10},Lg={encode:hg,decode:yg,encodingLength:Tg},Pg=Lg,Fn=Pg;function Un(r,e=0){let t=Fn.decode(r,e),n=Fn.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ur(r,e,t=0){return Fn.encode(r,e,t),e}function Kr(r){return Fn.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new qr(r,t,e,s)}function At(r){let e=Je(r),[t,n]=Un(e),[o,s]=Un(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function Kf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Df(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=or(n),this.bytes=or(o)}};function qf(r,e){let{bytes:t,version:n}=r;return n===0?Rg(t,sc(r),e??se.encoder):kg(t,sc(r),e??et.encoder)}var $f=new WeakMap;function sc(r){let e=$f.get(r);if(e==null){let t=new Map;return $f.set(r,t),t}return e}var xe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=or(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!==Kn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Og)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=mt(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&&Kf(e.multihash,n.multihash)}toString(e){return qf(this,e)}toJSON(){return{"/":qf(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??zf(n,o,s.bytes))}else if(t[Ng]===!0){let{version:n,multihash:o,code:s}=t,i=At(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!==Kn)throw new Error(`Version 0 CID must use dag-pb (code: ${Kn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=zf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Kn,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=Je(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 qr(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]=Un(e.subarray(t));return t+=d,f},o=n(),s=Kn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Dg(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 sc(s).set(n,e),s}};function Dg(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case Bn.prefix:{let t=e??Bn;return[Bn.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 Rg(r,e,t){let{prefix:n}=t;if(n!==se.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 kg(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 Kn=112,Og=18;function zf(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var Ng=Symbol.for("@ipld/js-cid/CID");var ic={};$e(ic,{identity:()=>at});var Vf=0,Mg="identity",Hf=Je;function Bg(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 mt(Vf,Hf(r))}var at={code:Vf,name:Mg,encode:Hf,digest:Bg};function Q(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Fg(r){return r.buffer instanceof ArrayBuffer}function Ce(r){return Fg(r)?r:r.slice()}async function Wf(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 jf(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,Ce(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Gf(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,Ce(e),Ce(t.subarray()));return n?.signal?.throwIfAborted(),s}function pe(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function Ug(r){return r?.buffer instanceof ArrayBuffer}function ac(r){if(Ug(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function tt(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return ac(t)}var Xf=Symbol.for("@achingbrain/uint8arraylist");function Yf(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 as(r){return!!r?.[Xf]}var ne=class r{bufs;length;[Xf]=!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(as(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(as(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=Yf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Yf(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(as(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 tt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:tt(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!as(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=pe(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=pe(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=pe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=pe(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=pe(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=pe(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=pe(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=pe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var cc={};$e(cc,{base10:()=>Kg});var Kg=Kt({prefix:"9",name:"base10",alphabet:"0123456789"});var lc={};$e(lc,{base16:()=>qg,base16upper:()=>$g});var qg=ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),$g=ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var uc={};$e(uc,{base2:()=>zg});var zg=ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fc={};$e(fc,{base256emoji:()=>Gg});var Zf=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}"),Vg=Zf.reduce((r,e,t)=>(r[t]=e,r),[]),Hg=Zf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wg(r){return r.reduce((e,t)=>(e+=Vg[t],e),"")}function jg(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Hg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Gg=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:Wg,decode:jg});var pc={};$e(pc,{base64:()=>dc,base64pad:()=>Yg,base64url:()=>hc,base64urlpad:()=>Xg});var dc=ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yg=ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hc=ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xg=ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mc={};$e(mc,{base8:()=>Zg});var Zg=ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gc={};$e(gc,{identity:()=>Qg});var Qg=Fr({prefix:"\0",name:"identity",encode:r=>kf(Je(r)),decode:r=>Je(Rf(r))});var QE=new TextEncoder,JE=new TextDecoder;var wc={};$e(wc,{sha256:()=>$r,sha512:()=>ry});var ty=20;function bc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new yc(r,e,t,n,o)}var yc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??ty,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?Qf(n,this.code,t?.truncate):n.then(o=>Qf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Qf(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 mt(e,r)}function ed(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var $r=bc({name:"sha2-256",code:18,encode:ed("SHA-256")}),ry=bc({name:"sha2-512",code:19,encode:ed("SHA-512")});var qn={...gc,...uc,...mc,...cc,...lc,...rc,...nc,...tc,...pc,...fc},fv={...wc,...ic};function rd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var td=rd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),xc=rd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ny={utf8:td,"utf-8":td,hex:qn.base16,latin1:xc,ascii:xc,binary:xc,...qn},cs=ny;function T(r,e="utf8"){let t=cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function q(r,e="utf8"){let t=cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var oy=parseInt("11111",2),Ec=parseInt("10000000",2),sy=parseInt("01111111",2),nd={0:$n,1:$n,2:iy,3:ly,4:uy,5:cy,6:ay,16:$n,22:$n,48:$n};function _t(r,e={offset:0}){let t=r[e.offset]&oy;if(e.offset++,nd[t]!=null)return nd[t](r,e);throw new Error("No decoder for tag "+t)}function zn(r,e){let t=0;if((r[e.offset]&Ec)===Ec){let n=r[e.offset]&sy,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function $n(r,e){zn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=_t(r,e);if(n===null)break;t.push(n)}return t}function iy(r,e){let t=zn(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 ay(r,e){let t=zn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function cy(r,e){return e.offset++,null}function ly(r,e){let t=zn(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 uy(r,e){let t=zn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function fy(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ne;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function ls(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=fy(r.byteLength);return new ne(Uint8Array.from([e.byteLength|Ec]),e)}function Me(r){let e=new ne,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ne(Uint8Array.from([2]),ls(e),e)}function Vn(r){let e=Uint8Array.from([0]),t=new ne(e,r);return new ne(Uint8Array.from([3]),ls(t),t)}function od(r){return new ne(Uint8Array.from([4]),ls(r),r)}function ct(r,e=48){let t=new ne;for(let n of r)t.append(n);return new ne(Uint8Array.from([e]),ls(t),t)}var dy=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),hy=Uint8Array.from([6,5,43,129,4,0,34]),py=Uint8Array.from([6,5,43,129,4,0,35]),my={ext:!0,kty:"EC",crv:"P-256"},gy={ext:!0,kty:"EC",crv:"P-384"},yy={ext:!0,kty:"EC",crv:"P-521"},vc=32,Sc=48,Ac=66;function _c(r){let e=_t(r);return sd(e)}function sd(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===vc*2+1)return n=q(e.subarray(t,t+vc),"base64url"),o=q(e.subarray(t+vc),"base64url"),new sr({...my,key_ops:["verify"],x:n,y:o});if(e.byteLength===Sc*2+1)return n=q(e.subarray(t,t+Sc),"base64url"),o=q(e.subarray(t+Sc),"base64url"),new sr({...gy,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ac*2+1)return n=q(e.subarray(t,t+Ac),"base64url"),o=q(e.subarray(t+Ac),"base64url"),new sr({...yy,key_ops:["verify"],x:n,y:o});throw new C(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function id(r){return ct([Me(Uint8Array.from([1])),od(T(r.d??"","base64url")),ct([cd(r.crv)],160),ct([Vn(new ne(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function ad(r){return ct([Me(Uint8Array.from([1])),ct([cd(r.crv)],160),ct([Vn(new ne(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function cd(r){if(r==="P-256")return dy;if(r==="P-384")return hy;if(r==="P-521")return py;throw new C(`Invalid curve ${r}`)}async function ld(r="P-256"){let e=await Wf(r);return new us(e.privateKey)}var sr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ad(this.jwk)),this._raw}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return Gf(this.jwk,t,e,n)}},us=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=id(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async sign(e,t){return jf(this.jwk,e,t)}};var fs=BigInt(4294967295),ud=BigInt(32);function by(r,e=!1){return e?{h:Number(r&fs),l:Number(r>>ud&fs)}:{h:Number(r>>ud&fs)|0,l:Number(r&fs)|0}}function fd(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}=by(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var wy=r=>r/2**32|0,xy=r=>r>>>0;function dd(r,e,t,n){let o=wy(t),s=xy(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var Ic=(r,e,t)=>r>>>t,Cc=(r,e,t)=>r<<32-t|e>>>t,ir=(r,e,t)=>r>>>t|e<<32-t,ar=(r,e,t)=>r<<32-t|e>>>t,Hn=(r,e,t)=>r<<64-t|e>>>t-32,Wn=(r,e,t)=>r>>>t-32|e<<64-t;function gt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var hd=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),pd=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,md=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),gd=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,yd=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),bd=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function ds(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Tc=r=>r?`"${r}" `:"";function It(r,e=""){if(typeof r!="number")throw new TypeError(Tc(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Tc(e)+"expected integer >= 0, got "+r);return r}function nt(r,e,t=""){if(ds(r)&&(e===void 0||r.length===e))return r;e!==void 0&&It(e,"length");let n=ds(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=Tc(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function hs(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(It(r.outputLen),It(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var vy=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},wd=(r,e)=>{vy(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function zr(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function ps(r,e){nt(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function cr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ms(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function lt(r,e){return r<<32-e|r>>>e}var Ed=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sy=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gs(r){if(nt(r),Ed)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Sy[r[t]];return e}function xd(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function ys(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Ed)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=xd(r.charCodeAt(s)),a=xd(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 Lc(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];nt(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 Ay(r,e,t="opts"){return wd(r,"defaults"),e!==void 0&&wd(e,t),Object.assign(Object.create(null),r,e)}function Pc(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=Ay({},e,"info");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 vd(r=32){It(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 Dc=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Sd(r,e,t){return r&e^~r&t}function Ad(r,e,t){return r&e^r&t^e&t}var jn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ms(this.buffer)}update(e){zr(this),nt(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let l=ms(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){zr(this),ps(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),dd(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:ms(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},_d=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Id=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var _y=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]),$t=new Uint32Array(64),Rc=class extends jn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D: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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let f=0;f<16;f++,t+=4)$t[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=$t[f-15],h=$t[f-2],b=lt(d,7)^lt(d,18)^d>>>3,m=lt(h,17)^lt(h,19)^h>>>10;$t[f]=m+$t[f-7]+b+$t[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=lt(a,6)^lt(a,11)^lt(a,25),h=u+d+Sd(a,c,l)+_y[f]+$t[f]|0,m=(lt(n,2)^lt(n,13)^lt(n,22))+Ad(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){cr($t)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}},kc=class extends Rc{constructor(){super(32,_d)}};var Cd=fd(["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))),Iy=Cd[0],Cy=Cd[1],zt=new Uint32Array(80),Vt=new Uint32Array(80),Oc=class extends jn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:b,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,b,m,g]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,b,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=b|0,this.Hh=m|0,this.Hl=g|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let w=0;w<16;w++,t+=4)zt[w]=e.getUint32(t),Vt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let A=zt[w-15]|0,S=Vt[w-15]|0,B=ir(A,S,1)^ir(A,S,8)^Ic(A,S,7),F=ar(A,S,1)^ar(A,S,8)^Cc(A,S,7),M=zt[w-2]|0,P=Vt[w-2]|0,O=ir(M,P,19)^Hn(M,P,61)^Ic(M,P,6),j=ar(M,P,19)^Wn(M,P,61)^Cc(M,P,6),W=md(F,j,Vt[w-7],Vt[w-16]),ie=gd(W,B,O,zt[w-7],zt[w-16]);zt[w]=ie|0,Vt[w]=W|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:b,Gh:m,Gl:g,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let A=ir(f,d,14)^ir(f,d,18)^Hn(f,d,41),S=ar(f,d,14)^ar(f,d,18)^Wn(f,d,41),B=f&h^~f&m,F=d&b^~d&g,M=yd(v,S,F,Cy[w],Vt[w]),P=bd(M,y,A,B,Iy[w],zt[w]),O=M|0,j=ir(n,o,28)^Hn(n,o,34)^Hn(n,o,39),W=ar(n,o,28)^Wn(n,o,34)^Wn(n,o,39),ie=n&s^n&a^s&a,L=o&i^o&c^i&c;y=m|0,v=g|0,m=h|0,g=b|0,h=f|0,b=d|0,{h:f,l:d}=gt(l|0,u|0,P|0,O|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let z=hd(O,W,L);n=pd(z,P,j,ie),o=z|0}({h:n,l:o}=gt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=gt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=gt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=gt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=gt(this.Eh|0,this.El|0,f|0,d|0),{h,l:b}=gt(this.Fh|0,this.Fl|0,h|0,b|0),{h:m,l:g}=gt(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:v}=gt(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,l,u,f,d,h,b,m,g,y,v)}roundClean(){cr(zt,Vt)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Nc=class extends Oc{constructor(){super(64,Id)}};var Vr=Pc(()=>new kc,Dc(1));var Mc=Pc(()=>new Nc,Dc(3));function ws(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var J=(r,e,t)=>nt(r,e,t),Bc=It;function Ld(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function Ht(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function lr(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Gn=gs,ot=(...r)=>Lc(...r),Hr=r=>ys(r),jt=ds,ur=r=>vd(r),bs=BigInt(0),Td=BigInt(1),Ty=r=>r?`"${r}" `:"";function ze(r,e=""){if(typeof r!="boolean")throw new TypeError(Ty(e)+"expected boolean, got type="+typeof r);return r}function xs(r){if(typeof r=="bigint"){if(!Wt(r))throw new RangeError("positive bigint expected, got "+r)}else Bc(r);return r}function Ct(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 Yn(r){let e=xs(r).toString(16);return e.length&1?"0"+e:e}function Pd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?bs:BigInt("0x"+r)}function yt(r){return Pd(gs(r))}function fr(r){return Pd(gs(Xn(nt(r)).reverse()))}function Es(r,e){if(It(e),e===0)throw new Error("zero output length is invalid");r=xs(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return ys(n.padStart(t,"0"))}function Fc(r,e){return Es(r,e).reverse()}function Xn(r){return Uint8Array.from(J(r))}function Wt(r){return typeof r=="bigint"&&bs<=r}function Uc(r,e,t){return Wt(r)&&Wt(e)&&Wt(t)&&e<=r&&r<t}function Wr(r,e,t,n){if(!Uc(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function jr(r){if(r<bs)throw new Error("expected non-negative bigint, got "+r);return r===bs?0:r.toString(2).length}var Zn=r=>(Ct(r,"n"),(Td<<BigInt(r))-Td);function Dd(r,e,t){if(It(r,"hashLen"),It(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...g)=>t(l,ot(c,...g)),h=(g=o)=>{l=d(s,g),c=d(),g.length!==0&&(l=d(i,g),c=d())},b=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=d();let v=c.slice();y.push(v),g+=c.length}return ot(...y)};return(g,y)=>{f(),h(g);let v;for(;(v=y(b()))===void 0;)h();return f(),v}}function Ve(r,e={},t={},n="object"){Ht(r,n),Ht(e,"fields"),Ht(t,"optFields");function o(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let f=typeof u;if(f!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${f}`)}let s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(t,!0)}var Ee=BigInt(0),ee=BigInt(1),Gt=BigInt(2),Od=BigInt(3),Kc=BigInt(4),Nd=BigInt(5),Ly=BigInt(7),Md=BigInt(8),Py=BigInt(9),Dy=BigInt(15),Bd=BigInt(16),Ry=BigInt("0x10000000000000000");function me(r,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Ee?t:e+t}function Fd(r,e,t){if(t<=ee)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(e===Ee)return ee;if(e===ee)return r;let n=r%t;if(n<Ee&&(n+=t),e<Ry){let a=ee;for(;e>Ee;)e&ee&&(a=a*n%t),n=n*n%t,e>>=ee;return a}let o=[];for(;e>Ee;)o.push(Number(e&Dy)),e>>=Kc;let s=new Array(16);s[0]=ee,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function de(r,e,t){if(t<=ee)throw new Error("pow2: expected modulus > 1, got "+t);if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Ee;)n*=n,n%=t;return n}function Rd(r,e){if(r===Ee)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected modulus > 1, got "+e);let t=me(r,e),n=e,o=Ee,s=ee;for(;t!==Ee;){let a=n/t,c=n-t*a,l=o-s*a;n=t,t=c,o=s,s=l}if(n!==ee)throw new Error("invert: does not exist");return me(o,e)}function Ud(r,e){if(e<=ee)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=me(r,e);if(t===Ee)throw new Error("invertCt: expected non-zero number");let n=Fd(t,e-Gt,e);if(me(t*n,e)!==ee)throw new Error("invertCt: does not exist");return n}function qc(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function $c(r,e){if((r&ee)===Ee)throw new Error(e+": expected odd modulus, got "+r)}function Kd(r,e){let t=r,n=(t.ORDER+ee)/Kc,o=t.pow(e,n);return qc(t,o,e),o}function ky(r,e){let t=r,n=(t.ORDER-Nd)/Md,o=t.mul(e,Gt),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Gt),s),c=t.mul(i,t.sub(a,t.ONE));return qc(t,c,e),c}function Oy(r){let e=Yr(r),t=qd(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Ly)/Bd;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),d=l.mul(u,o),h=l.mul(u,s),b=l.eql(l.sqr(f),c),m=l.eql(l.sqr(d),c);u=l.cmov(u,f,b),f=l.cmov(h,d,m);let g=l.eql(l.sqr(f),c),y=l.cmov(u,f,g);return qc(l,y,c),y})}function qd(r){if(r<Od)throw new Error("sqrt is not defined for small field");$c(r,"tonelliShanks");let e=r-ee,t=0;for(;e%Gt===Ee;)e/=Gt,t++;let n=Gt,o=Yr(r);for(;Qn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Kd;let s=o.pow(n,e),i=(e+ee)/Gt;return function(c,l){let u=c;if(u.is0(l))return l;if(Qn(u,l)!==1)throw new Error("Cannot find square root");let f=t,d=u.mul(u.ONE,s),h=u.pow(l,e),b=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(m++,g=u.sqr(g),m===f)throw new Error("Cannot find square root");let y=ee<<BigInt(f-m-1),v=u.pow(d,y);f=m,d=u.sqr(v),h=u.mul(h,d),b=u.mul(b,v)}return b}}function Ny(r){return $c(r,"Fp.sqrt"),r%Kc===Od?Kd:r%Md===Nd?ky:r%Bd===Py?Oy(r):qd(r)}var $d=(r,e)=>(me(r,e)&ee)===ee,My=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gr(r){if(Ht(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Ct(r.BYTES,"BYTES"),Ct(r.BITS,"BITS");for(let e of My)lr(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ee)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Ss(r,e,t=!1){Gr(r),ws(e,"nums"),ze(t,"passZero");let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function Qn(r,e){Gr(r);let t=r;$c(t.ORDER,"FpLegendre");let n=(t.ORDER-ee)/Gt,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 By(r,e){if(e!==void 0&&Bc(e),r<=Ee)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=jr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var kd=new WeakMap,vs=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=ee;_lengths;_mod;constructor(e,t={}){if(e<=ee)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}=By(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 me(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return me(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return me(e*e,this.ORDER)}add(e,t){return me(e+t,this.ORDER)}sub(e,t){return me(e-t,this.ORDER)}mul(e,t){return me(e*t,this.ORDER)}pow(e,t){return Fd(e,t,this.ORDER)}div(e,t){return me(e*Rd(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 Rd(e,this.ORDER)}sqrt(e){let t=kd.get(this);return t||kd.set(this,t=Ny(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Fc(e,this.BYTES):Es(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 l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?fr(e):yt(e);if(a&&(c=me(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ss(this,e,!0)}cmov(e,t,n){return ze(n,"condition"),n?t:e}};function Yr(r,e={}){return Object.freeze(vs.prototype),new vs(r,e)}function zd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ee)throw new Error("field order must be greater than 1");let e=jr(r-ee);return Math.ceil(e/8)}function As(r){let e=zd(r);return e+Math.ceil(e/2)}function _s(r,e,t=!1){J(r);let n=r.length,o=zd(e),s=Math.max(As(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?fr(r):yt(r),a=me(i,e-ee)+ee;return t?Fc(a,o):Es(a,o)}var Hc=BigInt(0),Jn=BigInt(1),Fy=BigInt(4),zc=16,Vd=128,Uy=5,Hd=2**31;function Yt(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);lr(e.fromAffine,"Point.fromAffine"),lr(e.fromBytes,"Point.fromBytes"),lr(e.fromHex,"Point.fromHex"),Ht(e.BASE,"Point.BASE"),Ht(e.ZERO,"Point.ZERO"),Gr(e.Fp),Gr(e.Fn)}function Is(r,e){Yt(r),jd(e,r);let t=Ss(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Ky(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function qy(r,e){let t=r*(4*e+128);if(t>Hd)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Hd/2**20+" MiB")}function Wc(r,e){if(r!==void 0){lr(r,"randomBytes");try{let t=r(e);if(!jt(t)||t.length!==e)return}catch{return}return r}}function jd(r,e){ws(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function $y(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):Wt(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var Gd=new WeakMap;function Vc(r){return Gd.get(r)||1}function zy(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function Vy(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>Hc;){let i=0;r&Jn&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=Jn}return s}function Hy(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(r&s);r>>=i,l>o&&(l-=n,r+=Jn),a.push(l)}if(r!==Hc)throw new Error("invalid wnaf");return a}function Wy(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Xr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Yt(e),this.randomBytes=Wc(t,zc),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let l=a;for(let u=0;u<s;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Hy(t,n,o),c=this.ZERO,l=this.BASE;for(let u=0;u<o;u++){let f=a[u],d=u*i,h=Math.abs(f)-1,b=s[d];for(let g=1;g<i;g++)b=g===h?s[d+g]:b;let m=b.negate();f===0?l=l.add(s[d]):c=c.add(f<0?m:b)}return{p:c,f:l}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Uc(t,Jn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=Vc(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Vd,s=this.randomBytes(zc);if(!jt(s)||s.length!==zc)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+yt(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=Uy,s=1<<o,i=Zn(o),a=new Array(s);a[0]=this.ZERO;for(let u=1;u<s;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let h=0;h<o;h++)l=l.double();let f=Number(t>>BigInt(u*o)&i),d=a[0];for(let h=1;h<s;h++)d=h===f?a[h]:d;l=l.add(d)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Jn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Wt(t))throw new Error("invalid scalar");let o=Vc(e);if(o===1||t>=this.Point.Fn.ORDER)return Cs(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),Ky(t,this.bits);let n=Math.ceil((this.bits+Vd)/t)+1;qy(n*2**(t-1),this.Point.Fp.BYTES),Gd.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Vc(e)!==1}};function Cs(r,e,t,n=!1){if(Yt(r),jd(e,r),ze(n,"allowOversized"),$y(t,r.Fn,n?r.Fn.ORDER**Fy:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>zy(i,4)),s=t.map(i=>Vy(i,4));return Wy(r.ZERO,o,s)}function Wd(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Gr(e),e}else return Yr(r,{isLE:t})}function Ts(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);Ve(t);for(let c of["p","n","h"]){let l=e[c];if(!(Wt(l)&&l!==Hc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Wd(e.p,t.Fp,n),s=Wd(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 Ls(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Ps=BigInt(0),Ds=BigInt(1),Rs=BigInt(2),jy=BigInt(4),Yd=BigInt(8);function Gy(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 Xd(r,e={}){Ve(e,{},{},"extraOpts");let t=e,n=Ts("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Qn(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Qn(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ve(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?ur:t.randomBytes,l=Rs<<BigInt(o.BYTES*8)-Ds;function u(v){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(v)}let f=t.uvRatio===void 0?(v,w)=>{try{return{isValid:!0,value:o.sqrt(o.div(v,w))}}catch{return{isValid:!1,value:Ps}}}:t.uvRatio;if(!Gy(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=o.eql(i.a,o.neg(o.ONE))?v=>o.neg(v):o.eql(i.a,o.ONE)?v=>v:v=>o.mul(i.a,v);function h(v,w,A=!1){let S=A?Ds:Ps;return Wr("coordinate "+v,w,S,l),w}function b(v){if(!(v instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(w,A,S,B){this.X=h("x",w),this.Y=h("y",A),this.Z=h("z",S,!0),this.T=h("t",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof m)throw new Error("extended point not allowed");let{x:A,y:S}=w||{};return h("x",A),h("y",S),new m(A,S,o.ONE,o.mul(A,S))}static fromBytes(w,A=!1){let S=o.BYTES,{a:B,d:F}=i;w=Xn(J(w,S,"point")),ze(A,"zip215");let M=Xn(w),P=w[S-1];M[S-1]=P&-129;let O=fr(M),j=A?l:o.ORDER;Wr("point.y",O,Ps,j);let W=o.sqr(O),ie=o.sub(W,o.ONE),L=o.sub(o.mulN(F,W),B),{isValid:z,value:V}=f(ie,L);if(!z)throw new Error("bad point: invalid y coordinate");let N=u(V),le=(P&128)!==0;if(!A&&o.is0(V)&&le)throw new Error("bad point: x=0 and x_0=1");return le!==N&&(V=o.neg(V)),m.fromAffine({x:V,y:O})}static fromHex(w,A=!1){return m.fromBytes(Hr(w),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=6,A=!0){return y.setWindowSize(this,w),A||this.multiply(Rs),this}assertValidity(){let w=this,{a:A,d:S}=i;if(w.is0())throw new Error("bad point: ZERO");let{X:B,Y:F,Z:M,T:P}=w,O=o.sqr(B),j=o.sqr(F),W=o.sqr(M),ie=o.sqr(W),L=o.mul(O,A),z=o.mul(o.add(L,j),W),V=o.add(ie,o.mul(S,o.mul(O,j)));if(!o.eql(z,V))throw new Error("bad point: equation left != right (1)");let N=o.mul(B,F),le=o.mul(M,P);if(!o.eql(N,le))throw new Error("bad point: equation left != right (2)")}equals(w){b(w);let{X:A,Y:S,Z:B}=this,{X:F,Y:M,Z:P}=w,O=o.mul(A,P),j=o.mul(F,B),W=o.mul(S,P),ie=o.mul(M,B);return o.eql(O,j)&&o.eql(W,ie)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:w,Y:A,Z:S}=this,B=o.sqr(w),F=o.sqr(A),M=o.mul(o.sqr(S),Rs),P=d(B),O=o.addN(w,A),j=o.sub(o.subN(o.sqr(O),B),F),W=o.addN(P,F),ie=o.subN(W,M),L=o.subN(P,F),z=o.mul(j,ie),V=o.mul(W,L),N=o.mul(j,L),le=o.mul(ie,W);return new m(z,V,le,N)}add(w){b(w);let{d:A}=i,{X:S,Y:B,Z:F,T:M}=this,{X:P,Y:O,Z:j,T:W}=w,ie=o.mul(S,P),L=o.mul(B,O),z=o.mul(o.mulN(M,A),W),V=o.mul(F,j),N=o.sub(o.subN(o.mulN(o.addN(S,B),o.addN(P,O)),ie),L),le=o.subN(V,z),he=o.addN(V,z),_=o.sub(L,d(ie)),p=o.mul(N,le),x=o.mul(he,_),E=o.mul(N,_),I=o.mul(le,he);return new m(p,x,I,E)}subtract(w){return b(w),this.add(w.negate())}multiply(w){if(!s.isValidNot0(w))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:S}=y.mulSecret(this,w,a,g);return g([A,S])[0]}multiplyUnsafe(w){if(!s.isValid(w))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return w===Ps?m.ZERO:this.is0()||w===Ds?this:y.mulUnsafe(this,w,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(w){let A=this,S=w;if(S!=null&&typeof S!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof S);let{X:B,Y:F,Z:M}=A,P=A.is0();S==null&&(S=P?o.create(Yd):o.inv(M));let O=o.mul(B,S),j=o.mul(F,S),W=o.mul(M,S);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(W,o.ONE))throw new Error("invZ was invalid");return{x:O,y:j}}clearCofactor(){return a===Ds?this:a===Rs?this.double():a===jy?this.double().double():a===Yd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:w,y:A}=this.toAffine(),S=o.toBytes(A);return S[S.length-1]|=u(w)?128:0,S}toHex(){return Gn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=v=>Is(m,v),y=new Xr(m,c);return y.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}function Zd(r,e,t={}){if(Yt(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Ve(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Ct(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?ur:o.randomBytes,d=o.toMontgomery,h=o.toMontgomerySecret,b=o.adjustScalarBytes===void 0?L=>L:o.adjustScalarBytes,m=o.domain===void 0?(L,z,V)=>{if(ze(V,"phflag"),z.length||V)throw new Error("Contexts/pre-hash are not supported");return L}:o.domain;function g(L){return c.create(fr(L))}function y(L){let z=P.secretKey;J(L,P.secretKey,"secretKey");let V=J(n(L),2*z,"hashedSecretKey"),N=b(V.slice(0,z)),le=V.slice(z,2*z),he=g(N);return{head:N,prefix:le,scalar:he}}function v(L){let{head:z,prefix:V,scalar:N}=y(L),le=i.multiply(N),he=le.toBytes();return{head:z,prefix:V,scalar:N,point:le,pointBytes:he}}function w(L){return v(L).pointBytes}function A(L=Uint8Array.of(),...z){let V=ot(...z);return g(n(m(V,J(L,void 0,"context"),!!s)))}function S(L,z,V={}){Ve(V,{},{},"options"),L=Xn(J(L,void 0,"message")),s&&(L=s(L));let{prefix:N,scalar:le,pointBytes:he}=v(z),_=A(V.context,N,L),p=i.multiply(_).toBytes(),x=A(V.context,p,he,L),E=c.create(_+x*le);if(!c.isValid(E))throw new Error("sign failed: invalid s");let I=ot(p,c.toBytes(E));return J(I,P.signature,"result")}let B={zip215:o.zip215};function F(L,z,V,N=B){Ve(N);let{context:le}=N,he=N.zip215===void 0?!!B.zip215:N.zip215,_=P.signature;L=J(L,_,"signature"),z=J(z,void 0,"message"),V=J(V,P.publicKey,"publicKey"),he!==void 0&&ze(he,"zip215"),s&&(z=s(z));let p=_/2,x=L.subarray(0,p),E=fr(L.subarray(p,_)),I,D,R;try{I=r.fromBytes(V,he),D=r.fromBytes(x,he),R=i.multiplyUnsafe(E)}catch{return!1}if(!he&&I.isSmallOrder())return!1;let U=A(le,x,V,z);return D.add(I.multiplyUnsafe(U)).subtract(R).clearCofactor().is0()}let M=a.BYTES,P={secretKey:M,publicKey:M,signature:2*M,seed:M};function O(L){return L=L===void 0?f(P.seed):L,J(L,P.seed,"seed")}function j(L){return jt(L)&&L.length===P.secretKey}function W(L,z){try{return!!r.fromBytes(L,z===void 0?B.zip215:z)}catch{return!1}}let ie={getExtendedPublicKey:v,randomSecretKey:O,isValidSecretKey:j,isValidPublicKey:W,toMontgomery(L){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(r.fromBytes(L))},toMontgomerySecret(L){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(L)}};return Object.freeze(P),Object.freeze(ie),Object.freeze({keygen:Ls(O,w),getPublicKey:w,sign:S,verify:F,utils:ie,Point:r,lengths:P})}var jc=BigInt(1),Qd=BigInt(2);var Yy=BigInt(5),Xy=BigInt(8),Gc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zy={p:Gc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Xy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Qy(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Gc,a=r*r%s*r%s,c=de(a,Qd,s)*a%s,l=de(c,jc,s)*r%s,u=de(l,Yy,s)*l%s,f=de(u,e,s)*u%s,d=de(f,t,s)*f%s,h=de(d,n,s)*d%s,b=de(h,o,s)*h%s,m=de(b,o,s)*h%s,g=de(m,e,s)*u%s;return{pow_p_5_8:de(g,Qd,s)*r%s,b2:a}}function th(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Jd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Jy(r,e){let t=Gc,n=me(e*e*e,t),o=me(n*n*e,t),s=Qy(r*o).pow_p_5_8,i=me(r*n*s,t),a=me(e*i*i,t),c=i,l=me(i*Jd,t),u=a===r,f=a===me(-r,t),d=a===me(-r*Jd,t);return u&&(i=c),(f||d)&&(i=l),$d(i,t)&&(i=me(-i,t)),{isValid:u||f,value:i}}var Yc=Xd(Zy,{uvRatio:Jy}),eh=Yc.Fp;function e0(r){let{y:e}=r;return eh.toBytes(eh.div(jc+e,jc-e))}function t0(r){let e=Yc.Fp.BYTES;return nt(r,e),th(Mc(r.subarray(0,e))).subarray(0,e)}function r0(r){return Zd(Yc,Mc,Object.assign({adjustScalarBytes:th,toMontgomery:e0,toMontgomerySecret:t0,zip215:!0},r))}var eo=r0({});var to=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ro=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ks=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var He={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ks("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 Os=32,no=64,Xc=32;var Zr,rh=(async()=>{try{return await He.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function nh(){let r=eo.utils.randomSecretKey(),e=eo.getPublicKey(r);return{privateKey:a0(r,e),publicKey:e}}async function n0(r,e){let t;r.length===no?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:q(r.subarray(32),"base64url"),d:q(t,"base64url"),ext:!0,key_ops:["sign"]},o=await He.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await He.get().subtle.sign({name:"Ed25519"},o,Ce(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function o0(r,e){let t=r.subarray(0,Xc);return eo.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function oh(r,e){return Zr==null&&(Zr=await rh),Zr?n0(r,e):o0(r,e)}async function s0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await He.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await He.get().subtle.verify({name:"Ed25519"},n,Ce(e),Ce(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function i0(r,e,t){return eo.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function sh(r,e,t){return Zr==null&&(Zr=await rh),Zr?s0(r,e,t):i0(r,e,t)}function a0(r,e){let t=new Uint8Array(no);for(let n=0;n<Xc;n++)t[n]=r[n],t[Xc+n]=e[n];return t}function Qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var oo=class{type="Ed25519";raw;constructor(e){this.raw=Ms(e,Os)}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=sh(this.raw,t,e);return Qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Ns=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ms(e,no),this.publicKey=new oo(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=oh(this.raw,e);return Qr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Zc(r){return r=Ms(r,Os),new oo(r)}async function ah(){let{privateKey:r,publicKey:e}=nh();return new Ns(r,e)}function Ms(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new C(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var c0=Math.pow(2,7),l0=Math.pow(2,14),u0=Math.pow(2,21),Qc=Math.pow(2,28),Jc=Math.pow(2,35),el=Math.pow(2,42),tl=Math.pow(2,49),te=128,Pe=127;function Ae(r){if(r<c0)return 1;if(r<l0)return 2;if(r<u0)return 3;if(r<Qc)return 4;if(r<Jc)return 5;if(r<el)return 6;if(r<tl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Jr(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|te,r/=128;case 7:e[t++]=r&255|te,r/=128;case 6:e[t++]=r&255|te,r/=128;case 5:e[t++]=r&255|te,r/=128;case 4:e[t++]=r&255|te,r>>>=7;case 3:e[t++]=r&255|te,r>>>=7;case 2:e[t++]=r&255|te,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function f0(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|te),r/=128;case 7:e.set(t++,r&255|te),r/=128;case 6:e.set(t++,r&255|te),r/=128;case 5:e.set(t++,r&255|te),r/=128;case 4:e.set(t++,r&255|te),r>>>=7;case 3:e.set(t++,r&255|te),r>>>=7;case 2:e.set(t++,r&255|te),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function rl(r,e){let t=r[e],n=0;if(n+=t&Pe,t<te||(t=r[e+1],n+=(t&Pe)<<7,t<te)||(t=r[e+2],n+=(t&Pe)<<14,t<te)||(t=r[e+3],n+=(t&Pe)<<21,t<te)||(t=r[e+4],n+=(t&Pe)*Qc,t<te)||(t=r[e+5],n+=(t&Pe)*Jc,t<te)||(t=r[e+6],n+=(t&Pe)*el,t<te)||(t=r[e+7],n+=(t&Pe)*tl,t<te))return n;throw new RangeError("Could not decode varint")}function d0(r,e){let t=r.get(e),n=0;if(n+=t&Pe,t<te||(t=r.get(e+1),n+=(t&Pe)<<7,t<te)||(t=r.get(e+2),n+=(t&Pe)<<14,t<te)||(t=r.get(e+3),n+=(t&Pe)<<21,t<te)||(t=r.get(e+4),n+=(t&Pe)*Qc,t<te)||(t=r.get(e+5),n+=(t&Pe)*Jc,t<te)||(t=r.get(e+6),n+=(t&Pe)*el,t<te)||(t=r.get(e+7),n+=(t&Pe)*tl,t<te))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=Se(Ae(r))),e instanceof Uint8Array?Jr(r,e,t):f0(r,e,t)}function dr(r,e=0){return r instanceof Uint8Array?rl(r,e):d0(r,e)}var nl=new Float32Array([-0]),Zt=new Uint8Array(nl.buffer);function ch(r,e,t){nl[0]=r,e[t]=Zt[0],e[t+1]=Zt[1],e[t+2]=Zt[2],e[t+3]=Zt[3]}function lh(r,e){return Zt[0]=r[e],Zt[1]=r[e+1],Zt[2]=r[e+2],Zt[3]=r[e+3],nl[0]}var ol=new Float64Array([-0]),De=new Uint8Array(ol.buffer);function uh(r,e,t){ol[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function fh(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],ol[0]}var h0=BigInt(Number.MAX_SAFE_INTEGER),p0=BigInt(Number.MIN_SAFE_INTEGER),je=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 hr;if(e<h0&&e>p0)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>dh&&(o=0n,++n>dh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return hr;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):hr}},hr=new je(0,0);hr.toBigInt=function(){return 0n};hr.zzEncode=hr.zzDecode=function(){return this};hr.length=function(){return 1};var dh=4294967296n;function hh(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 ph(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 sl(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 ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Bs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var il=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ce(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,ut(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 ut(this,4);return Bs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return Bs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=lh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=fh(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 ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return ph(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ut(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 je(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 ut(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 ut(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 ut(this,8);let e=Bs(this.buf,this.pos+=4),t=Bs(this.buf,this.pos+=4);return new je(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=rl(this.buf,this.pos);return this.pos+=Ae(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 io(r){return new il(r instanceof Uint8Array?r:r.subarray())}function Be(r,e,t){let n=io(r);return e.decode(n,void 0,t)}function al(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var pr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function cl(){}var ul=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},m0=al();function g0(r){return globalThis.Buffer!=null?Se(r):m0(r)}var co=class{len;head;tail;states;constructor(){this.len=0,this.head=new pr(cl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fl((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(Fs,10,je.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=je.fromBigInt(e);return this._push(Fs,t.length(),t)}uint64Number(e){return this._push(Jr,Ae(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=je.fromBigInt(e).zzEncode();return this._push(Fs,t.length(),t)}sint64Number(e){let t=je.fromNumber(e).zzEncode();return this._push(Fs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ll,1,e?1:0)}fixed32(e){return this._push(ao,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=je.fromBigInt(e);return this._push(ao,4,t.lo)._push(ao,4,t.hi)}fixed64Number(e){let t=je.fromNumber(e);return this._push(ao,4,t.lo)._push(ao,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(ch,4,e)}double(e){return this._push(uh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ll,1,0):this.uint32(t)._push(b0,t,e)}string(e){let t=hh(e);return t!==0?this.uint32(t)._push(sl,t,e):this._push(ll,1,0)}fork(){return this.states=new ul(this),this.head=this.tail=new pr(cl,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 pr(cl,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=g0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function ll(r,e,t){e[t]=r&255}function y0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var fl=class extends pr{next;constructor(e,t){super(y0,e,t),this.next=void 0}};function Fs(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 ao(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 b0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(co.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(w0,e,r),this},co.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(x0,e,r),this});function w0(r,e,t){e.set(r,t)}function x0(r,e,t){r.length<40?sl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function dl(){return new co}function Fe(r,e){let t=dl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Ue(r,e,t){let n=io(r);yield*e.stream(n,void 0,".",t)}var Us={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ks(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function hl(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,a){};return Ks("enum",Us.VARINT,t,n,o)}function Ke(r,e,t){return Ks("message",Us.LENGTH_DELIMITED,r,e,t)}var st=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},lo=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var pl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(pl||(pl={}));(function(r){r.codec=()=>hl(pl)})(ge||(ge={}));var bt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(bt||(bt={}));var ml;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(ml||(ml={}));var fo={};$e(fo,{MAX_RSA_KEY_SIZE:()=>gl,generateRSAKeyPair:()=>_l,jwkToJWKKeyPair:()=>xh,jwkToPkcs1:()=>A0,jwkToPkix:()=>xl,jwkToRSAPrivateKey:()=>Al,pkcs1MessageToJwk:()=>bl,pkcs1MessageToRSAPrivateKey:()=>El,pkcs1ToJwk:()=>S0,pkcs1ToRSAPrivateKey:()=>wh,pkixMessageToJwk:()=>wl,pkixMessageToRSAPublicKey:()=>Sl,pkixToJwk:()=>_0,pkixToRSAPublicKey:()=>vl});var en=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=fo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return xe.createV1(114,this._multihash)}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return bh(this.jwk,t,e,n)}},uo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=fo.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return yh(this.jwk,e,t)}};var gl=8192,yl=18,E0=1062,v0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function S0(r){let e=_t(r);return bl(e)}function bl(r){return{n:q(r[1],"base64url"),e:q(r[2],"base64url"),d:q(r[3],"base64url"),p:q(r[4],"base64url"),q:q(r[5],"base64url"),dp:q(r[6],"base64url"),dq:q(r[7],"base64url"),qi:q(r[8],"base64url"),kty:"RSA"}}function A0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new C("JWK was missing components");return ct([Me(Uint8Array.from([0])),Me(T(r.n,"base64url")),Me(T(r.e,"base64url")),Me(T(r.d,"base64url")),Me(T(r.p,"base64url")),Me(T(r.q,"base64url")),Me(T(r.dp,"base64url")),Me(T(r.dq,"base64url")),Me(T(r.qi,"base64url"))]).subarray()}function _0(r){let e=_t(r,{offset:0});return wl(e)}function wl(r){let e=_t(r[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function xl(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");return ct([v0,Vn(ct([Me(T(r.n,"base64url")),Me(T(r.e,"base64url"))]))]).subarray()}function wh(r){let e=_t(r);return El(e)}function El(r){let e=bl(r);return Al(e)}function vl(r,e){if(r.byteLength>=E0)throw new Mt("Key size is too large");let t=_t(r,{offset:0});return Sl(t,r,e)}function Sl(r,e,t){let n=wl(r);if(t==null){let o=Vr(bt.encode({Type:ge.RSA,Data:e}));t=mt(yl,o)}return new en(n,t)}function Al(r){if(vh(r)>gl)throw new C("Key size is too large");let e=xh(r),t=Vr(bt.encode({Type:ge.RSA,Data:xl(e.publicKey)})),n=mt(yl,t);return new uo(e.privateKey,new en(e.publicKey,n))}async function _l(r){if(r>gl)throw new C("Key size is too large");let e=await Eh(r),t=Vr(bt.encode({Type:ge.RSA,Data:xl(e.publicKey)})),n=mt(yl,t);return new uo(e.privateKey,new en(e.publicKey,n))}function xh(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Eh(r,e){let t=await He.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 I0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function yh(r,e,t){let n=await He.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await He.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ce(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function bh(r,e,t,n){let o=await He.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await He.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ce(e),Ce(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function I0(r,e){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");let t=await Promise.all([He.get().subtle.exportKey("jwk",r.privateKey),He.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function vh(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return T(r.n,"base64url").length*8}var qs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hs(e),nt(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,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),cr(o)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),ps(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,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Sh=(()=>{let r=((e,t,n)=>new qs(e,t).update(n).digest());return r.create=(e,t)=>new qs(e,t),r})();var C0=BigInt(0),Il=class extends Error{constructor(e=""){super(e)}},Tt={Err:Il,_tlv:{encode:(r,e)=>{let{Err:t}=Tt;if(Ct(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Ld(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Yn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Yn(o.length/2|128):"";return Yn(r)+s+o+e},decode(r,e){let{Err:t}=Tt;e=J(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Tt;if(xs(r),r<C0)throw new e("integer: negative integers are not allowed");let t=Yn(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}=Tt;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 yt(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:o}=Tt;if(e!==void 0&&(Ct(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let s=J(r,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=o.decode(2,i),{v:u,l:f}=o.decode(2,l);if(f.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Tt;Ve(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},$s=(Object.freeze(Tt._tlv),Object.freeze(Tt._int),Object.freeze(Tt));var Ah=(r,e)=>(r+(r>=0?e:-e)/_h)/e;function T0(r,e,t){Wr("scalar",r,Lt,t);let[[n,o],[s,i]]=e,a=Ah(i*r,t),c=Ah(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<Lt,d=u<Lt;f&&(l=-l),d&&(u=-u);let h=Zn(Math.ceil(jr(t)/2))+mr;if(l<Lt||l>=h||u<Lt||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:d,k2:u}}function Ll(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Cl(r,e){Ve(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ze(t.lowS,"lowS"),ze(t.prehash,"prehash"),t.format!==void 0&&Ll(t.format),t}var Lt=BigInt(0),mr=BigInt(1),_h=BigInt(2),Tl=BigInt(3),L0=BigInt(4);function Ih(r,e={}){let t=Ts("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:f,fromBytes:d,toBytes:h}=e,b=e.randomBytes===void 0?ur:e.randomBytes;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 m=c?{beta:c.beta,basises:c.basises.map(_=>[..._])}:void 0,g=Th(n,o);function y(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function v(_,p,x){if(p.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:E,y:I}=p.toAffine(),D=n.toBytes(E);if(ze(x,"isCompressed"),x){y();let R=!n.isOdd(I);return ot(Ch(R),D)}else return ot(Uint8Array.of(4),D,n.toBytes(I))}function w(_){J(_,void 0,"Point");let{publicKey:p,publicKeyUncompressed:x}=g,E=_.length,I=_[0],D=_.subarray(1);if(l&&E===1&&I===0)return{x:n.ZERO,y:n.ZERO};if(E===p&&(I===2||I===3)){let R=n.fromBytes(D);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let U=M(R),K;try{K=n.sqrt(U)}catch(be){let ue=be instanceof Error?": "+be.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}y();let Z=n.isOdd(K);return(I&1)===1!==Z&&(K=n.neg(K)),{x:R,y:K}}else if(E===x&&I===4){let R=n.BYTES,U=n.fromBytes(D.subarray(0,R)),K=n.fromBytes(D.subarray(R,R*2));if(!P(U,K))throw new Error("bad point: is not on curve");return{x:U,y:K}}else throw new Error(`bad point: got length ${E}, expected compressed=${p} or uncompressed=${x}`)}let A=h===void 0?v:h,S=d===void 0?w:d,B=n.mul(s.b,Tl),F=n.is0(s.a)?_=>n.ZERO:_=>n.mul(s.a,_);function M(_){let p=n.sqr(_),x=n.mul(p,_);return n.add(n.add(x,n.mul(_,s.a)),s.b)}function P(_,p){let x=n.sqr(p),E=M(_);return n.eql(x,E)}if(!P(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let O=n.mul(n.pow(s.a,Tl),L0),j=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(O,j)))throw new Error("bad curve params: a or b");function W(_,p,x=!1){if(!n.isValid(p)||x&&n.is0(p))throw new Error(`bad point coordinate ${_}`);return typeof p=="object"&&p!==null?n.create(p):p}function ie(_){if(!(_ instanceof N))throw new Error("Weierstrass Point expected")}function L(_){if(!m||!m.basises)throw new Error("no endo");return T0(_,m.basises,o.ORDER)}function z(_,p,x,E){if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(m){let{k1neg:I,k1:D,k2neg:R,k2:U}=L(E),K=new N(n.mul(x.X,m.beta),x.Y,x.Z);_.push(I?x.negate():x,R?K.negate():K),p.push(D,U)}else _.push(x),p.push(E)}let V=new WeakSet;class N{static BASE=new N(s.Gx,s.Gy,n.ONE);static ZERO=new N(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,x,E){this.X=W("x",p),this.Y=W("y",x,!0),this.Z=W("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x,y:E}=p||{};if(!p||!n.isValid(x)||!n.isValid(E))throw new Error("invalid affine point");if(p instanceof N)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(E)?N.ZERO:new N(x,E,n.ONE)}static fromBytes(p){let x=N.fromAffine(S(J(p,void 0,"point")));return x.assertValidity(),x}static fromHex(p){return N.fromBytes(Hr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,x=!0){return he.setWindowSize(this,p),x||this.multiply(Tl),this}assertValidity(){let p=this;if(p.is0()){if(l&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(V.has(p))return;let{x,y:E}=p.toAffine();if(!n.isValid(x)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!P(x,E))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");V.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){ie(p);let{X:x,Y:E,Z:I}=this,{X:D,Y:R,Z:U}=p,K=n.eql(n.mul(x,U),n.mul(D,I)),Z=n.eql(n.mul(E,U),n.mul(R,I));return K&&Z}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:x,Z:E}=this,I=n.ZERO,D=n.ZERO,R=n.ZERO,U=n.mul(p,p),K=n.mul(x,x),Z=n.mul(E,E),G=n.mul(p,x);return G=n.add(G,G),R=n.mul(p,E),R=n.add(R,R),I=F(R),D=n.mul(B,Z),D=n.add(I,D),I=n.sub(K,D),D=n.add(K,D),D=n.mul(I,D),I=n.mul(G,I),R=n.mul(B,R),Z=F(Z),G=n.sub(U,Z),G=F(G),G=n.add(G,R),R=n.add(U,U),U=n.add(R,U),U=n.add(U,Z),U=n.mul(U,G),D=n.add(D,U),Z=n.mul(x,E),Z=n.add(Z,Z),U=n.mul(Z,G),I=n.sub(I,U),R=n.mul(Z,K),R=n.add(R,R),R=n.add(R,R),new N(I,D,R)}add(p){ie(p);let{X:x,Y:E,Z:I}=this,{X:D,Y:R,Z:U}=p,K=n.ZERO,Z=n.ZERO,G=n.ZERO,be=n.mul(x,D),ue=n.mul(E,R),ve=n.mul(I,U),Ze=n.add(x,E),fe=n.add(D,R);Ze=n.mul(Ze,fe),fe=n.add(be,ue),Ze=n.sub(Ze,fe),fe=n.add(x,I);let we=n.add(D,U);return fe=n.mul(fe,we),we=n.add(be,ve),fe=n.sub(fe,we),we=n.add(E,I),K=n.add(R,U),we=n.mul(we,K),K=n.add(ue,ve),we=n.sub(we,K),G=F(fe),K=n.mul(B,ve),G=n.add(K,G),K=n.sub(ue,G),G=n.add(ue,G),Z=n.mul(K,G),ue=n.add(be,be),ue=n.add(ue,be),ve=F(ve),fe=n.mul(B,fe),ue=n.add(ue,ve),ve=n.sub(be,ve),ve=F(ve),fe=n.add(fe,ve),be=n.mul(ue,fe),Z=n.add(Z,be),be=n.mul(we,fe),K=n.mul(Ze,K),K=n.sub(K,be),be=n.mul(Ze,ue),G=n.mul(we,G),G=n.add(G,be),new N(K,Z,G)}subtract(p){return ie(p),this.add(p.negate())}is0(){return this.equals(N.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:x,f:E}=he.mulSecret(this,p,i,le);return le([x,E])[0]}multiplyUnsafe(p){let x=this,E=p;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===Lt||x.is0())return N.ZERO;if(E===mr)return x;if(he.hasWindowSize(this))return he.mulUnsafe(x,E,le);let I=[],D=[];return z(I,D,x,E),Cs(N,I,D)}mulAddUnsafe(p,x,E){ie(x);let I=[],D=[];return z(I,D,this,p),z(I,D,x,E),Cs(N,I,D)}toAffine(p){let x=this,E=p;if(E!=null&&!n.isValid(E))throw new RangeError('"invertedZ" expected valid field element');let{X:I,Y:D,Z:R}=x;if(n.eql(R,n.ONE))return{x:I,y:D};let U=x.is0();E==null&&(E=U?n.ONE:n.inv(R));let K=n.mul(I,E),Z=n.mul(D,E),G=n.mul(R,E);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:K,y:Z}}isTorsionFree(){return i===mr?!0:f?f(N,this):he.mulUnsafe(this,a).is0()}clearCofactor(){return i===mr?this:u?u(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===mr?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return ze(p,"isCompressed"),this.assertValidity(),A(N,this,p)}toHex(p=!0){return Gn(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let le=_=>Is(N,_),he=new Xr(N,b);return he.bits>=6&&N.BASE.precompute(6),Object.freeze(N.prototype),Object.freeze(N),N}function Ch(r){return Uint8Array.of(r?2:3)}function Th(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function P0(r,e={}){Yt(r);let{Fn:t}=r,n=e.randomBytes===void 0?ur:e.randomBytes,o=Object.assign(Th(r.Fp,t),{seed:Math.max(As(t.ORDER),16)});function s(h){try{let b=t.fromBytes(h);return t.isValidNot0(b)}catch{return!1}}function i(h,b){let{publicKey:m,publicKeyUncompressed:g}=o;try{let y=h.length;return b===!0&&y!==m||b===!1&&y!==g?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,_s(J(h,o.seed,"seed"),t.ORDER)}function c(h,b=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(b)}function l(h){let{secretKey:b,publicKey:m,publicKeyUncompressed:g}=o,y=t._lengths;if(!jt(h))return;let v=J(h,void 0,"key").length,w=v===m||v===g,A=v===b||!!y?.includes(v);if(!(w&&A))return w}function u(h,b,m=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(b)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h),y=r.fromBytes(b);if(y.is0())throw new Error("invalid public key: point at infinity");return y.multiply(g).toBytes(m)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ls(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function Lh(r,e,t={}){Yt(r);let n=e;hs(n),Ve(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?ur:o.randomBytes,i=o.hmac===void 0?(_,p)=>Sh(n,_,p):o.hmac,{Fp:a,Fn:c}=r,{ORDER:l,BITS:u}=c,f=As(l),d=Wc(s,f),{keygen:h,getPublicKey:b,getSharedSecret:m,utils:g,lengths:y}=P0(r,o),v={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},w=l*_h+mr<a.ORDER;function A(_){let p=l>>mr;return _>p}function S(_,p){if(!c.isValidNot0(p))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return p}function B(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function F(_,p,x){return B(),(_===x?0:2)|Number(a.isOdd(p))}function M(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(_,p){Ll(p);let x=y.signature,E=p==="compact"?x:p==="recovered"?x+1:void 0;return J(_,E)}class O{r;s;recovery;constructor(p,x,E){if(this.r=S("r",p),this.s=S("s",x),E!=null){if(M(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(p,x=v.format){P(p,x);let E;if(x==="der"){if(p.length>2*c.BYTES+16)throw new $s.Err("invalid signature: DER signature too long");let{r:U,s:K}=$s.toSig(J(p),c.BYTES+1);return new O(U,K)}x==="recovered"&&(E=p[0],x="compact",p=p.subarray(1));let I=y.signature/2,D=p.subarray(0,I),R=p.subarray(I,I*2);return new O(c.fromBytes(D),c.fromBytes(R),E)}static fromHex(p,x){return this.fromBytes(Hr(p),x)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new O(this.r,this.s,p)}recoverPublicKey(p){let{r:x,s:E}=this,I=this.assertRecovery(),D=I===2||I===3?x+l:x;if(!a.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=a.toBytes(D),U=r.fromBytes(ot(Ch((I&1)===0),R)),K=c.inv(D),Z=W(J(p,void 0,"msgHash")),G=c.create(-Z*K),be=c.create(E*K),ue=r.BASE.mulAddUnsafe(G,U,be);if(ue.is0())throw new Error("invalid recovery: point at infinify");return ue.assertValidity(),ue}hasHighS(){return A(this.s)}toBytes(p=v.format){if(Ll(p),p==="der")return Hr($s.hexFromSig(this));let{r:x,s:E}=this,I=c.toBytes(x),D=c.toBytes(E);return p==="recovered"?(M(),ot(Uint8Array.of(this.assertRecovery()),I,D)):ot(I,D)}toHex(p){return Gn(this.toBytes(p))}}Object.freeze(O.prototype),Object.freeze(O);let j=o.bits2int===void 0?function(p){if(p.length>8192)throw new Error("input is too large");let x=yt(p),E=p.length*8-u;return E>0?x>>BigInt(E):x}:o.bits2int,W=o.bits2int_modN===void 0?function(p){return c.create(j(p))}:o.bits2int_modN,ie=Zn(u);function L(_){return Wr("num < 2^"+u,_,Lt,ie),c.toBytes(_)}function z(_,p){return J(_,void 0,"message"),p?J(n(_),void 0,"prehashed message"):_}function V(_,p,x){let{lowS:E,prehash:I,extraEntropy:D}=Cl(x,v);_=z(_,I);let R=W(_),U=c.fromBytes(p);if(!c.isValidNot0(U))throw new Error("invalid private key");let K=[L(U),L(R)];if(D!=null&&D!==!1){let ue=D===!0?s(y.secretKey):D;K.push(J(ue,void 0,"extraEntropy"))}let Z=ot(...K),G=R;function be(ue){let ve=j(ue);if(!c.isValidNot0(ve))return;let Ze=r.BASE.multiply(ve).toAffine(),fe=c.create(Ze.x);if(fe===Lt)return;let we;if(d!==void 0){let Dn=yt(_s(d(f),l)),Fm=c.inv(c.mul(Dn,ve)),Um=c.mul(Dn,G),Km=c.mul(Dn,U);we=c.create(Fm*c.create(Um+Km*fe))}else{let Dn=Ud(ve,l);we=c.create(Dn*c.create(G+fe*U))}if(we===Lt)return;let za=F(Ze.x,Ze.y,fe),Af=we;return E&&A(we)&&(Af=c.neg(we),za^=1),new O(fe,Af,w?void 0:za)}return{seed:Z,k2sig:be}}function N(_,p,x={}){let{seed:E,k2sig:I}=V(_,p,x);return Dd(n.outputLen,c.BYTES,i)(E,I).toBytes(x.format)}function le(_,p,x,E={}){let{lowS:I,prehash:D,format:R}=Cl(E,v);if(x=J(x,void 0,"publicKey"),p=z(p,D),!jt(_)){let U=_ instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}P(_,R);try{let U=O.fromBytes(_,R),K=r.fromBytes(x);if(K.is0()||I&&U.hasHighS())return!1;let{r:Z,s:G}=U,be=W(p),ue=c.inv(G),ve=c.create(be*ue),Ze=c.create(Z*ue),fe=r.BASE.mulAddUnsafe(ve,K,Ze);if(fe.is0())return!1;let we=fe.toAffine();return!(c.create(we.x)!==Z||R==="recovered"&&U.recovery!==F(we.x,we.y,Z))}catch{return!1}}function he(_,p,x={}){let{prehash:E}=Cl(x,v);return p=z(p,E),O.fromBytes(_,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:h,getPublicKey:b,getSharedSecret:m,utils:g,lengths:y,Point:r,sign:N,verify:le,recoverPublicKey:he,Signature:O,hash:n})}var Dl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},D0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ph=BigInt(2);function R0(r){let e=Dl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=de(u,t,e)*u%e,d=de(f,t,e)*u%e,h=de(d,Ph,e)*l%e,b=de(h,o,e)*h%e,m=de(b,s,e)*b%e,g=de(m,a,e)*m%e,y=de(g,c,e)*g%e,v=de(y,a,e)*m%e,w=de(v,t,e)*u%e,A=de(w,i,e)*b%e,S=de(A,n,e)*l%e,B=de(S,Ph,e);if(!Pl.eql(Pl.sqr(B),r))throw new Error("Cannot find square root");return B}var Pl=Yr(Dl.p,{sqrt:R0}),k0=Ih(Dl,{Fp:Pl,endo:D0}),ft=Lh(k0,Vr);function Dh(r,e,t){let n=$r.digest(e instanceof Uint8Array?e:e.subarray());if(Qr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ft.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new to(String(o))});try{return ft.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new to(String(o))}}function Rh(r,e,t,n){let o=$r.digest(t instanceof Uint8Array?t:t.subarray());if(Qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ft.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ro(String(s))});try{return n?.signal?.throwIfAborted(),ft.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ro(String(s))}}var ho=class{type="secp256k1";raw;_key;constructor(e){this._key=Nh(e),this.raw=kh(this._key)}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return Rh(this._key,t,e,n)}},zs=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Oh(e),this.publicKey=new ho(t??Mh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}sign(e,t){return Dh(this.raw,e,t)}};function Rl(r){return new ho(r)}async function Bh(){let r=O0();return new zs(r)}function kh(r){return ft.Point.fromBytes(r).toBytes()}function Oh(r){try{return ft.getPublicKey(r,!0),r}catch(e){throw new kn(String(e))}}function Nh(r){try{return ft.Point.fromBytes(r),r}catch(e){throw new Mt(String(e))}}function Mh(r){try{return ft.getPublicKey(r,!0)}catch(e){throw new kn(String(e))}}function O0(){return ft.utils.randomSecretKey()}async function Fh(r,e){if(r==="Ed25519")return ah();if(r==="secp256k1")return Bh();if(r==="RSA")return _l(N0(e));if(r==="ECDSA")return ld(M0(e));throw new Ft}function tn(r,e){let{Type:t,Data:n}=bt.decode(r),o=n??new Uint8Array;switch(t){case ge.RSA:return vl(o,e);case ge.Ed25519:return Zc(o);case ge.secp256k1:return Rl(o);case ge.ECDSA:return _c(o);default:throw new Ft}}function Uh(r){let{Type:e,Data:t}=bt.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Zc(n);case ge.secp256k1:return Rl(n);case ge.ECDSA:return _c(n);default:throw new Ft}}function rt(r){return bt.encode({Type:ge[r.type],Data:r.raw})}function N0(r){return r==null?2048:parseInt(r,10)}function M0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new C("Unsupported curve, should be P-256, P-384 or P-521")}var Kh=Symbol.for("nodejs.util.inspect.custom"),B0=114,po=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()})`}[os]=!0;toString(){return this.string==null&&(this.string=se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return xe.createV1(B0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Kh](){return`PeerId(${this.toString()})`}},mo=class extends po{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},go=class extends po{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},yo=class extends po{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},F0=2336,bo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=at.digest(T(this.url))}[Kh](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return xe.createV1(F0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var U0=114,qh=2336;function wt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=At(se.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return wo(xe.parse(r));if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=At(e.decode(r))}return rn(t)}function kl(r){if(r.type==="Ed25519")return new go({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new yo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new mo({multihash:r.toCID().multihash,publicKey:r});throw new Ft}function $h(r){return kl(r.publicKey)}function rn(r){if(q0(r))return new mo({multihash:r});if(K0(r))try{let e=Uh(r);if(e.type==="Ed25519")return new go({multihash:r,publicKey:e});if(e.type==="secp256k1")return new yo({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new bo(new URL(t))}throw new Zo("Supplied PeerID Multihash is invalid")}function wo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==U0&&r.code!==qh)throw new Xo("Supplied PeerID CID is invalid");if(r.code===qh){let e=q(r.multihash.digest);return new bo(new URL(e))}return rn(r.multihash)}function K0(r){return r.code===at.code}function q0(r){return r.code===$r.code}async function zh(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return r}function Vs(r,e){if(typeof r=="string")return $0(r);if(typeof r=="number")return H0(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function $0(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 z0(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 V0(r){let e=Math.abs(r);return e>=315576e5?gr(r,e,315576e5,"year"):e>=26298e5?gr(r,e,26298e5,"month"):e>=6048e5?gr(r,e,6048e5,"week"):e>=864e5?gr(r,e,864e5,"day"):e>=36e5?gr(r,e,36e5,"hour"):e>=6e4?gr(r,e,6e4,"minute"):e>=1e3?gr(r,e,1e3,"second"):`${r} ms`}function H0(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?V0(r):z0(r)}function gr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Ol(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Vs,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u,f){let d,h=null,b,m;function g(...y){if(!g.enabled)return;let v=g,w=Number(new Date),A=w-(d||w);v.diff=A,v.prev=d,v.curr=w,d=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let S=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(F,M)=>{if(F==="%%")return"%";S++;let P=t.formatters[M];if(typeof P=="function"){let O=y[S];F=P.call(v,O),y.splice(S,1),S--}return F}),t.formatArgs.call(v,y),f?.onLog!=null&&f.onLog(...y),(v.log||t.log).apply(v,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(b!==t.namespaces&&(b=t.namespaces,m=t.enabled(u)),m),set:y=>{h=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Hs=Q0(),W0=["#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 j0(){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 G0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Vs(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 Y0=console.debug??console.log??(()=>{});function X0(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function Z0(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Q0(){try{return localStorage}catch{}}function J0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Vh=Ol({formatArgs:G0,save:X0,load:Z0,useColors:j0,setupFormatters:J0,colors:W0,storage:Hs,log:Y0});var We=Vh;We.formatters.b=r=>r==null?"undefined":se.baseEncode(r);We.formatters.t=r=>r==null?"undefined":et.baseEncode(r);We.formatters.m=r=>r==null?"undefined":dc.baseEncode(r);We.formatters.p=r=>r==null?"undefined":r.toString();We.formatters.c=r=>r==null?"undefined":r.toString();We.formatters.k=r=>r==null?"undefined":r.toString();We.formatters.a=r=>r==null?"undefined":r.toString();function Hh(r,e=""){let t=Wh(r.message),n=Wh(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var Libp2P=(()=>{var zm=Object.create;var Go=Object.defineProperty;var Vm=Object.getOwnPropertyDescriptor;var Hm=Object.getOwnPropertyNames;var Wm=Object.getPrototypeOf,Gm=Object.prototype.hasOwnProperty;var Dn=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},$e=(r,e)=>{for(var t in e)Go(r,t,{get:e[t],enumerable:!0})},_f=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hm(e))!Gm.call(r,o)&&o!==t&&Go(r,o,{get:()=>e[o],enumerable:!(n=Vm(e,o))||n.enumerable});return r};var Va=(r,e,t)=>(t=r!=null?zm(Wm(r)):{},_f(e||!r||!r.__esModule?Go(t,"default",{value:r,enumerable:!0}):t,r)),jm=r=>_f(Go({},"__esModule",{value:!0}),r);var zu=Dn(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.Netmask4Impl=void 0;an.ip2long=sn;an.long2ip=Et;function Et(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 db=48,hb=97,pb=65;function mb(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)-db)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-hb)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-pb)>>>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]=mb(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 $u=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=Et(this.netLong),this.mask=Et(this.maskLong),this.hostmask=Et(~this.maskLong),this.first=this.bitmask<=30?Et(this.netLong+1):this.base,this.last=this.bitmask<=30?Et(this.netLong+this.size-2):Et(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Et(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(Et(this.netLong+this.size*e),this.mask)}forEach(e){let t=sn(this.first),n=sn(this.last),o=0;for(;t<=n;)e(Et(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};an.Netmask4Impl=$u});var cp=Dn(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.Netmask6Impl=void 0;cn.ip6bigint=Hu;cn.bigint2ip6=Sr;var gb=zu(),Vu=(1n<<128n)-1n;function Hu(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,gb.ip2long)(n),s=r.substring(0,t+1)+"0:0";return ap(s)&~0xffffffffn|BigInt(o)}return ap(r)}function ap(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 Sr(r){if(r<0n||r>Vu)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 Wu=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=Vu>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Hu(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Sr(this.netBigint),this.mask=Sr(this.maskBigint),this.hostmask=Sr(~this.maskBigint&Vu),this.first=this.base,this.last=Sr(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):(Hu(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Sr(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(Sr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};cn.Netmask6Impl=Wu});var up=Dn(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.long2ip=Qt.ip2long=Qt.Netmask=void 0;var Js=zu();Object.defineProperty(Qt,"ip2long",{enumerable:!0,get:function(){return Js.ip2long}});Object.defineProperty(Qt,"long2ip",{enumerable:!0,get:function(){return Js.long2ip}});var yb=cp(),Gu=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 yb.Netmask6Impl(e,t):this._impl=new Js.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 Js.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()}};Qt.Netmask=Gu});var Am=Dn((GP,ef)=>{"use strict";var cx=Object.prototype.hasOwnProperty,qe="~";function zo(){}Object.create&&(zo.prototype=Object.create(null),new zo().__proto__||(qe=!1));function ux(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Sm(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new ux(t,n||r,o),i=qe?qe+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 Aa(r,e){--r._eventsCount===0?r._events=new zo:delete r._events[e]}function Oe(){this._events=new zo,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)cx.call(t,n)&&e.push(qe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Oe.prototype.listeners=function(e){var t=qe?qe+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};Oe.prototype.listenerCount=function(e){var t=qe?qe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Oe.prototype.emit=function(e,t,n,o,s,i){var a=qe?qe+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};Oe.prototype.on=function(e,t,n){return Sm(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Sm(this,e,t,n,!0)};Oe.prototype.removeListener=function(e,t,n,o){var s=qe?qe+e:e;if(!this._events[s])return this;if(!t)return Aa(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Aa(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:Aa(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Aa(this,t)):(this._events=new zo,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=qe;Oe.EventEmitter=Oe;typeof ef<"u"&&(ef.exports=Oe)});var Im=Dn((m4,Cm)=>{Cm.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Bx={};$e(Bx,{createLibp2p:()=>Ox,dnsaddrResolver:()=>Nr,isLibp2p:()=>Mx});var Cf=Symbol.for("@libp2p/connection");var Ha=Symbol.for("@libp2p/content-routing");var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},jo=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}};var I=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},mt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Rn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var rr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Yo=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},nr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Mr=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"}},Xo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Zo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Qo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Jo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var es=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},At=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Br=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var kn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ts=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},rs=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ns=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Wa=Symbol.for("@libp2p/peer-discovery");var os=Symbol.for("@libp2p/peer-id");function Ut(r){return!!r?.[os]}var Ga=Symbol.for("@libp2p/peer-routing");var ja="keep-alive";function ss(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function If(...r){let e=[];for(let t of r)ss(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 Tf(...r){let e=[];for(let t of r)ss(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 On;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(On||(On={}));function Ym(r){return typeof r?.handleEvent=="function"}function Xm(r){return r===!0||r===!1}function Zm(r){return Xm(r)?r:r?.capture??!1}function Ya(r){let e={capture:Zm(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function Lf(r,e){return Ya(r).capture===Ya(e).capture}var Ne=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=Ya(n);if(o?.signal?.aborted===!0)return;let s=u=>{o.once&&this.removeEventListener(e,t,o),Ym(t)?t.handleEvent(u):t(u)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(u=>u.callback!==t?!1:Lf(u.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&Lf(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Nn=Symbol.for("@libp2p/service-capabilities"),Xa=Symbol.for("@libp2p/service-dependencies");function X(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 tc={};$e(tc,{base58btc:()=>se,base58flickr:()=>sg});var vE=new Uint8Array(0);function Df(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 Je(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return or(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return or(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Rf(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Pf=4096;function kf(r){let e=r.length;if(e<=Pf)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Pf));return t}function Qm(r){return r?.buffer instanceof ArrayBuffer}function or(r){return Qm(r)?r:r.slice()}function Jm(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var l=r.length,f=r.charAt(0),d=Math.log(l)/Math.log(256),h=Math.log(256)/Math.log(l);function b(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var S=0,w=0,v=0,A=y.length;v!==A&&y[v]===0;)v++,S++;for(var M=(A-v)*h+1>>>0,F=new Uint8Array(M);v!==A;){for(var B=y[v],P=0,O=M-1;(B!==0||P<w)&&O!==-1;O--,P++)B+=256*F[O]>>>0,F[O]=B%l>>>0,B=B/l>>>0;if(B!==0)throw new Error("Non-zero carry");w=P,v++}for(var G=M-w;G!==M&&F[G]===0;)G++;for(var W=f.repeat(S);G<M;++G)W+=r.charAt(F[G]);return W}function m(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var S=0;if(y[S]!==" "){for(var w=0,v=0;y[S]===f;)w++,S++;for(var A=(y.length-S)*d+1>>>0,M=new Uint8Array(A);y[S];){var F=n[y.charCodeAt(S)];if(F===255)return;for(var B=0,P=A-1;(F!==0||B<v)&&P!==-1;P--,B++)F+=l*M[P]>>>0,M[P]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");v=B,S++}if(y[S]!==" "){for(var O=A-v;O!==A&&M[O]===0;)O++;for(var G=new Uint8Array(w+(A-O)),W=w;O!==A;)G[W++]=M[O++];return G}}}function g(y){var S=m(y);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:b,decodeUnsafe:m,decode:g}}var eg=Jm,tg=eg,Nf=tg;var Za=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")}},Qa=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 Mf(this,e)}},Ja=class{decoders;constructor(e){this.decoders=e}or(e){return Mf(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 Mf(r,e){return new Ja({...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 Za(e,t,n),this.decoder=new Qa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new ec(r,e,t,n)}function Kt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Nf(t,r,n);return Fr({prefix:e,name:r,encode:o,decode:i=>Je(s(i))})}function rg(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 ng(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 og(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function ye({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=og(n,o);return Fr({prefix:e,name:r,encode(i){return ng(i,n,t)},decode(i){return rg(i,s,t,r)}})}var se=Kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sg=Kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var rc={};$e(rc,{base32:()=>et,base32hex:()=>ug,base32hexpad:()=>fg,base32hexpadupper:()=>dg,base32hexupper:()=>lg,base32pad:()=>ag,base32padupper:()=>cg,base32upper:()=>ig,base32z:()=>hg});var et=ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),ig=ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),ag=ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),cg=ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ug=ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),lg=ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),fg=ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),dg=ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),hg=ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nc={};$e(nc,{base36:()=>Mn,base36upper:()=>pg});var Mn=Kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),pg=Kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var mg=Uf,Bf=128,gg=127,yg=~gg,bg=Math.pow(2,31);function Uf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bg;)e[t++]=r&255|Bf,r/=128;for(;r&yg;)e[t++]=r&255|Bf,r>>>=7;return e[t]=r|0,Uf.bytes=t-n+1,e}var wg=oc,xg=128,Ff=127;function oc(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw oc.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ff)<<o:(i&Ff)*Math.pow(2,o),o+=7}while(i>=xg);return oc.bytes=s-n,t}var Eg=Math.pow(2,7),vg=Math.pow(2,14),Sg=Math.pow(2,21),Ag=Math.pow(2,28),_g=Math.pow(2,35),Cg=Math.pow(2,42),Ig=Math.pow(2,49),Tg=Math.pow(2,56),Lg=Math.pow(2,63),Pg=function(r){return r<Eg?1:r<vg?2:r<Sg?3:r<Ag?4:r<_g?5:r<Cg?6:r<Ig?7:r<Tg?8:r<Lg?9:10},Dg={encode:mg,decode:wg,encodingLength:Pg},Rg=Dg,Bn=Rg;function Fn(r,e=0){let t=Bn.decode(r,e),n=Bn.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ur(r,e,t=0){return Bn.encode(r,e,t),e}function Kr(r){return Bn.encodingLength(r)}function gt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new qr(r,t,e,s)}function _t(r){let e=Je(r),[t,n]=Fn(e),[o,s]=Fn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function Kf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Df(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=or(n),this.bytes=or(o)}};function qf(r,e){let{bytes:t,version:n}=r;return n===0?Og(t,sc(r),e??se.encoder):Ng(t,sc(r),e??et.encoder)}var $f=new WeakMap;function sc(r){let e=$f.get(r);if(e==null){let t=new Map;return $f.set(r,t),t}return e}var xe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=or(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!==Un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mg)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=gt(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&&Kf(e.multihash,n.multihash)}toString(e){return qf(this,e)}toJSON(){return{"/":qf(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??zf(n,o,s.bytes))}else if(t[Bg]===!0){let{version:n,multihash:o,code:s}=t,i=_t(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!==Un)throw new Error(`Version 0 CID must use dag-pb (code: ${Un}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=zf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Un,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=Je(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 qr(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]=Fn(e.subarray(t));return t+=d,f},o=n(),s=Un;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]=kg(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 sc(s).set(n,e),s}};function kg(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case Mn.prefix:{let t=e??Mn;return[Mn.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 Og(r,e,t){let{prefix:n}=t;if(n!==se.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 Ng(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 Un=112,Mg=18;function zf(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var Bg=Symbol.for("@ipld/js-cid/CID");var ic={};$e(ic,{identity:()=>at});var Vf=0,Fg="identity",Hf=Je;function Ug(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 gt(Vf,Hf(r))}var at={code:Vf,name:Fg,encode:Hf,digest:Ug};function Kg(r){return r.buffer instanceof ArrayBuffer}function Ie(r){return Kg(r)?r:r.slice()}async function Wf(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 Gf(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,Ie(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function jf(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,Ie(e),Ie(t.subarray()));return n?.signal?.throwIfAborted(),s}function pe(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function qg(r){return r?.buffer instanceof ArrayBuffer}function ac(r){if(qg(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function tt(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return ac(t)}var Xf=Symbol.for("@achingbrain/uint8arraylist");function Yf(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 as(r){return!!r?.[Xf]}var ne=class r{bufs;length;[Xf]=!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(as(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(as(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=Yf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Yf(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(as(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 tt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:tt(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(!as(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=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=pe(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=pe(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=pe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=pe(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=pe(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=pe(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=pe(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=pe(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(!X(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 cc={};$e(cc,{base10:()=>$g});var $g=Kt({prefix:"9",name:"base10",alphabet:"0123456789"});var uc={};$e(uc,{base16:()=>zg,base16upper:()=>Vg});var zg=ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Vg=ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var lc={};$e(lc,{base2:()=>Hg});var Hg=ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fc={};$e(fc,{base256emoji:()=>Xg});var Zf=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}"),Wg=Zf.reduce((r,e,t)=>(r[t]=e,r),[]),Gg=Zf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function jg(r){return r.reduce((e,t)=>(e+=Wg[t],e),"")}function Yg(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Gg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xg=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:jg,decode:Yg});var pc={};$e(pc,{base64:()=>dc,base64pad:()=>Zg,base64url:()=>hc,base64urlpad:()=>Qg});var dc=ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zg=ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hc=ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Qg=ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mc={};$e(mc,{base8:()=>Jg});var Jg=ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gc={};$e(gc,{identity:()=>ey});var ey=Fr({prefix:"\0",name:"identity",encode:r=>kf(Je(r)),decode:r=>Je(Rf(r))});var iv=new TextEncoder,av=new TextDecoder;var wc={};$e(wc,{sha256:()=>$r,sha512:()=>oy});var ny=20;function bc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new yc(r,e,t,n,o)}var yc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??ny,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?Qf(n,this.code,t?.truncate):n.then(o=>Qf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Qf(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 gt(e,r)}function ed(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var $r=bc({name:"sha2-256",code:18,encode:ed("SHA-256")}),oy=bc({name:"sha2-512",code:19,encode:ed("SHA-512")});var Kn={...gc,...lc,...mc,...cc,...uc,...rc,...nc,...tc,...pc,...fc},wv={...wc,...ic};function rd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var td=rd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),xc=rd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sy={utf8:td,"utf-8":td,hex:Kn.base16,latin1:xc,ascii:xc,binary:xc,...Kn},cs=sy;function T(r,e="utf8"){let t=cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function q(r,e="utf8"){let t=cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var iy=parseInt("11111",2),Ec=parseInt("10000000",2),ay=parseInt("01111111",2),nd={0:qn,1:qn,2:cy,3:fy,4:dy,5:ly,6:uy,16:qn,22:qn,48:qn};function Ct(r,e={offset:0}){let t=r[e.offset]&iy;if(e.offset++,nd[t]!=null)return nd[t](r,e);throw new Error("No decoder for tag "+t)}function $n(r,e){let t=0;if((r[e.offset]&Ec)===Ec){let n=r[e.offset]&ay,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function qn(r,e){$n(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ct(r,e);if(n===null)break;t.push(n)}return t}function cy(r,e){let t=$n(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 uy(r,e){let t=$n(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 ly(r,e){return e.offset++,null}function fy(r,e){let t=$n(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 dy(r,e){let t=$n(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function hy(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ne;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function us(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=hy(r.byteLength);return new ne(Uint8Array.from([e.byteLength|Ec]),e)}function Me(r){let e=new ne,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ne(Uint8Array.from([2]),us(e),e)}function zn(r){let e=Uint8Array.from([0]),t=new ne(e,r);return new ne(Uint8Array.from([3]),us(t),t)}function od(r){return new ne(Uint8Array.from([4]),us(r),r)}function ct(r,e=48){let t=new ne;for(let n of r)t.append(n);return new ne(Uint8Array.from([e]),us(t),t)}var py=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),my=Uint8Array.from([6,5,43,129,4,0,34]),gy=Uint8Array.from([6,5,43,129,4,0,35]),yy={ext:!0,kty:"EC",crv:"P-256"},by={ext:!0,kty:"EC",crv:"P-384"},wy={ext:!0,kty:"EC",crv:"P-521"},vc=32,Sc=48,Ac=66;function _c(r){let e=Ct(r);return sd(e)}function sd(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===vc*2+1)return n=q(e.subarray(t,t+vc),"base64url"),o=q(e.subarray(t+vc),"base64url"),new sr({...yy,key_ops:["verify"],x:n,y:o});if(e.byteLength===Sc*2+1)return n=q(e.subarray(t,t+Sc),"base64url"),o=q(e.subarray(t+Sc),"base64url"),new sr({...by,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ac*2+1)return n=q(e.subarray(t,t+Ac),"base64url"),o=q(e.subarray(t+Ac),"base64url"),new sr({...wy,key_ops:["verify"],x:n,y:o});throw new I(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function id(r){return ct([Me(Uint8Array.from([1])),od(T(r.d??"","base64url")),ct([cd(r.crv)],160),ct([zn(new ne(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function ad(r){return ct([Me(Uint8Array.from([1])),ct([cd(r.crv)],160),ct([zn(new ne(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function cd(r){if(r==="P-256")return py;if(r==="P-384")return my;if(r==="P-521")return gy;throw new I(`Invalid curve ${r}`)}async function ud(r="P-256"){let e=await Wf(r);return new ls(e.privateKey)}var sr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ad(this.jwk)),this._raw}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async verify(e,t,n){return jf(this.jwk,t,e,n)}},ls=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=id(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async sign(e,t){return Gf(this.jwk,e,t)}};var fs=BigInt(4294967295),ld=BigInt(32);function xy(r,e=!1){return e?{h:Number(r&fs),l:Number(r>>ld&fs)}:{h:Number(r>>ld&fs)|0,l:Number(r&fs)|0}}function fd(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}=xy(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ey=r=>r/2**32|0,vy=r=>r>>>0;function dd(r,e,t,n){let o=Ey(t),s=vy(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var Cc=(r,e,t)=>r>>>t,Ic=(r,e,t)=>r<<32-t|e>>>t,ir=(r,e,t)=>r>>>t|e<<32-t,ar=(r,e,t)=>r<<32-t|e>>>t,Vn=(r,e,t)=>r<<64-t|e>>>t-32,Hn=(r,e,t)=>r>>>t-32|e<<64-t;function yt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var hd=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),pd=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,md=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),gd=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,yd=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),bd=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function ds(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Tc=r=>r?`"${r}" `:"";function It(r,e=""){if(typeof r!="number")throw new TypeError(Tc(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Tc(e)+"expected integer >= 0, got "+r);return r}function nt(r,e,t=""){if(ds(r)&&(e===void 0||r.length===e))return r;e!==void 0&&It(e,"length");let n=ds(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=Tc(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function hs(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(It(r.outputLen),It(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ay=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},wd=(r,e)=>{Ay(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function zr(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function ps(r,e){nt(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function cr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ms(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ut(r,e){return r<<32-e|r>>>e}var Ed=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_y=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gs(r){if(nt(r),Ed)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=_y[r[t]];return e}function xd(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function ys(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Ed)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=xd(r.charCodeAt(s)),a=xd(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 Lc(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];nt(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 Cy(r,e,t="opts"){return wd(r,"defaults"),e!==void 0&&wd(e,t),Object.assign(Object.create(null),r,e)}function Pc(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=Cy({},e,"info");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 vd(r=32){It(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 Dc=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Sd(r,e,t){return r&e^~r&t}function Ad(r,e,t){return r&e^r&t^e&t}var Wn=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=ms(this.buffer)}update(e){zr(this),nt(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let u=ms(e);for(;o<=s-a;a+=o)this.process(u,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){zr(this),ps(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),dd(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:ms(e),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");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}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},_d=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Cd=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Iy=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]),$t=new Uint32Array(64),Rc=class extends Wn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D: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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let f=0;f<16;f++,t+=4)$t[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=$t[f-15],h=$t[f-2],b=ut(d,7)^ut(d,18)^d>>>3,m=ut(h,17)^ut(h,19)^h>>>10;$t[f]=m+$t[f-7]+b+$t[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=ut(a,6)^ut(a,11)^ut(a,25),h=l+d+Sd(a,c,u)+Iy[f]+$t[f]|0,m=(ut(n,2)^ut(n,13)^ut(n,22))+Ad(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|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(){cr($t)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}},kc=class extends Rc{constructor(){super(32,_d)}};var Id=fd(["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))),Ty=Id[0],Ly=Id[1],zt=new Uint32Array(80),Vt=new Uint32Array(80),Oc=class extends Wn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:b,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,b,m,g]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,b,m,g){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=b|0,this.Hh=m|0,this.Hl=g|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let w=0;w<16;w++,t+=4)zt[w]=e.getUint32(t),Vt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let v=zt[w-15]|0,A=Vt[w-15]|0,M=ir(v,A,1)^ir(v,A,8)^Cc(v,A,7),F=ar(v,A,1)^ar(v,A,8)^Ic(v,A,7),B=zt[w-2]|0,P=Vt[w-2]|0,O=ir(B,P,19)^Vn(B,P,61)^Cc(B,P,6),G=ar(B,P,19)^Hn(B,P,61)^Ic(B,P,6),W=md(F,G,Vt[w-7],Vt[w-16]),ie=gd(W,M,O,zt[w-7],zt[w-16]);zt[w]=ie|0,Vt[w]=W|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:b,Gh:m,Gl:g,Hh:y,Hl:S}=this;for(let w=0;w<80;w++){let v=ir(f,d,14)^ir(f,d,18)^Vn(f,d,41),A=ar(f,d,14)^ar(f,d,18)^Hn(f,d,41),M=f&h^~f&m,F=d&b^~d&g,B=yd(S,A,F,Ly[w],Vt[w]),P=bd(B,y,v,M,Ty[w],zt[w]),O=B|0,G=ir(n,o,28)^Vn(n,o,34)^Vn(n,o,39),W=ar(n,o,28)^Hn(n,o,34)^Hn(n,o,39),ie=n&s^n&a^s&a,L=o&i^o&c^i&c;y=m|0,S=g|0,m=h|0,g=b|0,h=f|0,b=d|0,{h:f,l:d}=yt(u|0,l|0,P|0,O|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let z=hd(O,W,L);n=pd(z,P,G,ie),o=z|0}({h:n,l:o}=yt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=yt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=yt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=yt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=yt(this.Eh|0,this.El|0,f|0,d|0),{h,l:b}=yt(this.Fh|0,this.Fl|0,h|0,b|0),{h:m,l:g}=yt(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:S}=yt(this.Hh|0,this.Hl|0,y|0,S|0),this.set(n,o,s,i,a,c,u,l,f,d,h,b,m,g,y,S)}roundClean(){cr(zt,Vt)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Nc=class extends Oc{constructor(){super(64,Cd)}};var Vr=Pc(()=>new kc,Dc(1));var Mc=Pc(()=>new Nc,Dc(3));function ws(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var J=(r,e,t)=>nt(r,e,t),Bc=It;function Ld(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function Ht(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function ur(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Gn=gs,ot=(...r)=>Lc(...r),Hr=r=>ys(r),Gt=ds,lr=r=>vd(r),bs=BigInt(0),Td=BigInt(1),Py=r=>r?`"${r}" `:"";function ze(r,e=""){if(typeof r!="boolean")throw new TypeError(Py(e)+"expected boolean, got type="+typeof r);return r}function xs(r){if(typeof r=="bigint"){if(!Wt(r))throw new RangeError("positive bigint expected, got "+r)}else Bc(r);return r}function Tt(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 jn(r){let e=xs(r).toString(16);return e.length&1?"0"+e:e}function Pd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?bs:BigInt("0x"+r)}function bt(r){return Pd(gs(r))}function fr(r){return Pd(gs(Yn(nt(r)).reverse()))}function Es(r,e){if(It(e),e===0)throw new Error("zero output length is invalid");r=xs(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return ys(n.padStart(t,"0"))}function Fc(r,e){return Es(r,e).reverse()}function Yn(r){return Uint8Array.from(J(r))}function Wt(r){return typeof r=="bigint"&&bs<=r}function Uc(r,e,t){return Wt(r)&&Wt(e)&&Wt(t)&&e<=r&&r<t}function Wr(r,e,t,n){if(!Uc(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Gr(r){if(r<bs)throw new Error("expected non-negative bigint, got "+r);return r===bs?0:r.toString(2).length}var Xn=r=>(Tt(r,"n"),(Td<<BigInt(r))-Td);function Dd(r,e,t){if(It(r,"hashLen"),It(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),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=(...g)=>t(u,ot(c,...g)),h=(g=o)=>{u=d(s,g),c=d(),g.length!==0&&(u=d(i,g),c=d())},b=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=d();let S=c.slice();y.push(S),g+=c.length}return ot(...y)};return(g,y)=>{f(),h(g);let S;for(;(S=y(b()))===void 0;)h();return f(),S}}function Ve(r,e={},t={},n="object"){Ht(r,n),Ht(e,"fields"),Ht(t,"optFields");function o(i,a,c){let u=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=r[i];if(!Object.hasOwn(r,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&l===void 0)return;let f=typeof l;if(f!==a||l===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${f}`)}let s=(i,a)=>Object.entries(i).forEach(([c,u])=>o(c,u,a));s(e,!1),s(t,!0)}var Ee=BigInt(0),ee=BigInt(1),jt=BigInt(2),Od=BigInt(3),Kc=BigInt(4),Nd=BigInt(5),Dy=BigInt(7),Md=BigInt(8),Ry=BigInt(9),ky=BigInt(15),Bd=BigInt(16),Oy=BigInt("0x10000000000000000");function me(r,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Ee?t:e+t}function Fd(r,e,t){if(t<=ee)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(e===Ee)return ee;if(e===ee)return r;let n=r%t;if(n<Ee&&(n+=t),e<Oy){let a=ee;for(;e>Ee;)e&ee&&(a=a*n%t),n=n*n%t,e>>=ee;return a}let o=[];for(;e>Ee;)o.push(Number(e&ky)),e>>=Kc;let s=new Array(16);s[0]=ee,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function de(r,e,t){if(t<=ee)throw new Error("pow2: expected modulus > 1, got "+t);if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Ee;)n*=n,n%=t;return n}function Rd(r,e){if(r===Ee)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected modulus > 1, got "+e);let t=me(r,e),n=e,o=Ee,s=ee;for(;t!==Ee;){let a=n/t,c=n-t*a,u=o-s*a;n=t,t=c,o=s,s=u}if(n!==ee)throw new Error("invert: does not exist");return me(o,e)}function Ud(r,e){if(e<=ee)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=me(r,e);if(t===Ee)throw new Error("invertCt: expected non-zero number");let n=Fd(t,e-jt,e);if(me(t*n,e)!==ee)throw new Error("invertCt: does not exist");return n}function qc(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function $c(r,e){if((r&ee)===Ee)throw new Error(e+": expected odd modulus, got "+r)}function Kd(r,e){let t=r,n=(t.ORDER+ee)/Kc,o=t.pow(e,n);return qc(t,o,e),o}function Ny(r,e){let t=r,n=(t.ORDER-Nd)/Md,o=t.mul(e,jt),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,jt),s),c=t.mul(i,t.sub(a,t.ONE));return qc(t,c,e),c}function My(r){let e=Yr(r),t=qd(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Dy)/Bd;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),b=u.eql(u.sqr(f),c),m=u.eql(u.sqr(d),c);l=u.cmov(l,f,b),f=u.cmov(h,d,m);let g=u.eql(u.sqr(f),c),y=u.cmov(l,f,g);return qc(u,y,c),y})}function qd(r){if(r<Od)throw new Error("sqrt is not defined for small field");$c(r,"tonelliShanks");let e=r-ee,t=0;for(;e%jt===Ee;)e/=jt,t++;let n=jt,o=Yr(r);for(;Zn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Kd;let s=o.pow(n,e),i=(e+ee)/jt;return function(c,u){let l=c;if(l.is0(u))return u;if(Zn(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),b=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,g=l.sqr(h);for(;!l.eql(g,l.ONE);)if(m++,g=l.sqr(g),m===f)throw new Error("Cannot find square root");let y=ee<<BigInt(f-m-1),S=l.pow(d,y);f=m,d=l.sqr(S),h=l.mul(h,d),b=l.mul(b,S)}return b}}function By(r){return $c(r,"Fp.sqrt"),r%Kc===Od?Kd:r%Md===Nd?Ny:r%Bd===Ry?My(r):qd(r)}var $d=(r,e)=>(me(r,e)&ee)===ee,Fy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jr(r){if(Ht(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Tt(r.BYTES,"BYTES"),Tt(r.BITS,"BITS");for(let e of Fy)ur(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ee)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Ss(r,e,t=!1){jr(r),ws(e,"nums"),ze(t,"passZero");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 Zn(r,e){jr(r);let t=r;$c(t.ORDER,"FpLegendre");let n=(t.ORDER-ee)/jt,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 Uy(r,e){if(e!==void 0&&Bc(e),r<=Ee)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Gr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var kd=new WeakMap,vs=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=ee;_lengths;_mod;constructor(e,t={}){if(e<=ee)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}=Uy(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 me(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return me(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return me(e*e,this.ORDER)}add(e,t){return me(e+t,this.ORDER)}sub(e,t){return me(e-t,this.ORDER)}mul(e,t){return me(e*t,this.ORDER)}pow(e,t){return Fd(e,t,this.ORDER)}div(e,t){return me(e*Rd(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 Rd(e,this.ORDER)}sqrt(e){let t=kd.get(this);return t||kd.set(this,t=By(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Fc(e,this.BYTES):Es(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?fr(e):bt(e);if(a&&(c=me(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ss(this,e,!0)}cmov(e,t,n){return ze(n,"condition"),n?t:e}};function Yr(r,e={}){return Object.freeze(vs.prototype),new vs(r,e)}function zd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ee)throw new Error("field order must be greater than 1");let e=Gr(r-ee);return Math.ceil(e/8)}function As(r){let e=zd(r);return e+Math.ceil(e/2)}function _s(r,e,t=!1){J(r);let n=r.length,o=zd(e),s=Math.max(As(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?fr(r):bt(r),a=me(i,e-ee)+ee;return t?Fc(a,o):Es(a,o)}var Hc=BigInt(0),Qn=BigInt(1),Ky=BigInt(4),zc=16,Vd=128,qy=5,Hd=2**31;function Yt(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);ur(e.fromAffine,"Point.fromAffine"),ur(e.fromBytes,"Point.fromBytes"),ur(e.fromHex,"Point.fromHex"),Ht(e.BASE,"Point.BASE"),Ht(e.ZERO,"Point.ZERO"),jr(e.Fp),jr(e.Fn)}function Cs(r,e){Yt(r),Gd(e,r);let t=Ss(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function $y(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function zy(r,e){let t=r*(4*e+128);if(t>Hd)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Hd/2**20+" MiB")}function Wc(r,e){if(r!==void 0){ur(r,"randomBytes");try{let t=r(e);if(!Gt(t)||t.length!==e)return}catch{return}return r}}function Gd(r,e){ws(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Vy(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):Wt(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var jd=new WeakMap;function Vc(r){return jd.get(r)||1}function Hy(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function Wy(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>Hc;){let i=0;r&Qn&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=Qn}return s}function Gy(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(r&s);r>>=i,u>o&&(u-=n,r+=Qn),a.push(u)}if(r!==Hc)throw new Error("invalid wnaf");return a}function jy(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Xr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Yt(e),this.randomBytes=Wc(t,zc),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let u=a;for(let l=0;l<s;l++)i.push(u),u=u.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Gy(t,n,o),c=this.ZERO,u=this.BASE;for(let l=0;l<o;l++){let f=a[l],d=l*i,h=Math.abs(f)-1,b=s[d];for(let g=1;g<i;g++)b=g===h?s[d+g]:b;let m=b.negate();f===0?u=u.add(s[d]):c=c.add(f<0?m:b)}return{p:c,f:u}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Uc(t,Qn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=Vc(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Vd,s=this.randomBytes(zc);if(!Gt(s)||s.length!==zc)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+bt(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=qy,s=1<<o,i=Xn(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),u=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let h=0;h<o;h++)u=u.double();let f=Number(t>>BigInt(l*o)&i),d=a[0];for(let h=1;h<s;h++)d=h===f?a[h]:d;u=u.add(d)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Qn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Wt(t))throw new Error("invalid scalar");let o=Vc(e);if(o===1||t>=this.Point.Fn.ORDER)return Is(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),$y(t,this.bits);let n=Math.ceil((this.bits+Vd)/t)+1;zy(n*2**(t-1),this.Point.Fp.BYTES),jd.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Vc(e)!==1}};function Is(r,e,t,n=!1){if(Yt(r),Gd(e,r),ze(n,"allowOversized"),Vy(t,r.Fn,n?r.Fn.ORDER**Ky:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>Hy(i,4)),s=t.map(i=>Wy(i,4));return jy(r.ZERO,o,s)}function Wd(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jr(e),e}else return Yr(r,{isLE:t})}function Ts(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);Ve(t);for(let c of["p","n","h"]){let u=e[c];if(!(Wt(u)&&u!==Hc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Wd(e.p,t.Fp,n),s=Wd(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 Ls(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Ps=BigInt(0),Ds=BigInt(1),Rs=BigInt(2),Yy=BigInt(4),Yd=BigInt(8);function Xy(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 Xd(r,e={}){Ve(e,{},{},"extraOpts");let t=e,n=Ts("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Zn(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Zn(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ve(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?lr:t.randomBytes,u=Rs<<BigInt(o.BYTES*8)-Ds;function l(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}let f=t.uvRatio===void 0?(S,w)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,w))}}catch{return{isValid:!1,value:Ps}}}:t.uvRatio;if(!Xy(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=o.eql(i.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(i.a,o.ONE)?S=>S:S=>o.mul(i.a,S);function h(S,w,v=!1){let A=v?Ds:Ps;return Wr("coordinate "+S,w,A,u),w}function b(S){if(!(S instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(w,v,A,M){this.X=h("x",w),this.Y=h("y",v),this.Z=h("z",A,!0),this.T=h("t",M),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof m)throw new Error("extended point not allowed");let{x:v,y:A}=w||{};return h("x",v),h("y",A),new m(v,A,o.ONE,o.mul(v,A))}static fromBytes(w,v=!1){let A=o.BYTES,{a:M,d:F}=i;w=Yn(J(w,A,"point")),ze(v,"zip215");let B=Yn(w),P=w[A-1];B[A-1]=P&-129;let O=fr(B),G=v?u:o.ORDER;Wr("point.y",O,Ps,G);let W=o.sqr(O),ie=o.sub(W,o.ONE),L=o.sub(o.mulN(F,W),M),{isValid:z,value:V}=f(ie,L);if(!z)throw new Error("bad point: invalid y coordinate");let N=l(V),ue=(P&128)!==0;if(!v&&o.is0(V)&&ue)throw new Error("bad point: x=0 and x_0=1");return ue!==N&&(V=o.neg(V)),m.fromAffine({x:V,y:O})}static fromHex(w,v=!1){return m.fromBytes(Hr(w),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=6,v=!0){return y.setWindowSize(this,w),v||this.multiply(Rs),this}assertValidity(){let w=this,{a:v,d:A}=i;if(w.is0())throw new Error("bad point: ZERO");let{X:M,Y:F,Z:B,T:P}=w,O=o.sqr(M),G=o.sqr(F),W=o.sqr(B),ie=o.sqr(W),L=o.mul(O,v),z=o.mul(o.add(L,G),W),V=o.add(ie,o.mul(A,o.mul(O,G)));if(!o.eql(z,V))throw new Error("bad point: equation left != right (1)");let N=o.mul(M,F),ue=o.mul(B,P);if(!o.eql(N,ue))throw new Error("bad point: equation left != right (2)")}equals(w){b(w);let{X:v,Y:A,Z:M}=this,{X:F,Y:B,Z:P}=w,O=o.mul(v,P),G=o.mul(F,M),W=o.mul(A,P),ie=o.mul(B,M);return o.eql(O,G)&&o.eql(W,ie)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:w,Y:v,Z:A}=this,M=o.sqr(w),F=o.sqr(v),B=o.mul(o.sqr(A),Rs),P=d(M),O=o.addN(w,v),G=o.sub(o.subN(o.sqr(O),M),F),W=o.addN(P,F),ie=o.subN(W,B),L=o.subN(P,F),z=o.mul(G,ie),V=o.mul(W,L),N=o.mul(G,L),ue=o.mul(ie,W);return new m(z,V,ue,N)}add(w){b(w);let{d:v}=i,{X:A,Y:M,Z:F,T:B}=this,{X:P,Y:O,Z:G,T:W}=w,ie=o.mul(A,P),L=o.mul(M,O),z=o.mul(o.mulN(B,v),W),V=o.mul(F,G),N=o.sub(o.subN(o.mulN(o.addN(A,M),o.addN(P,O)),ie),L),ue=o.subN(V,z),he=o.addN(V,z),_=o.sub(L,d(ie)),p=o.mul(N,ue),x=o.mul(he,_),E=o.mul(N,_),C=o.mul(ue,he);return new m(p,x,C,E)}subtract(w){return b(w),this.add(w.negate())}multiply(w){if(!s.isValidNot0(w))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:A}=y.mulSecret(this,w,a,g);return g([v,A])[0]}multiplyUnsafe(w){if(!s.isValid(w))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return w===Ps?m.ZERO:this.is0()||w===Ds?this:y.mulUnsafe(this,w,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(w){let v=this,A=w;if(A!=null&&typeof A!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof A);let{X:M,Y:F,Z:B}=v,P=v.is0();A==null&&(A=P?o.create(Yd):o.inv(B));let O=o.mul(M,A),G=o.mul(F,A),W=o.mul(B,A);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(W,o.ONE))throw new Error("invZ was invalid");return{x:O,y:G}}clearCofactor(){return a===Ds?this:a===Rs?this.double():a===Yy?this.double().double():a===Yd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:w,y:v}=this.toAffine(),A=o.toBytes(v);return A[A.length-1]|=l(w)?128:0,A}toHex(){return Gn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=S=>Cs(m,S),y=new Xr(m,c);return y.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}function Zd(r,e,t={}){if(Yt(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Ve(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(Tt(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?lr:o.randomBytes,d=o.toMontgomery,h=o.toMontgomerySecret,b=o.adjustScalarBytes===void 0?L=>L:o.adjustScalarBytes,m=o.domain===void 0?(L,z,V)=>{if(ze(V,"phflag"),z.length||V)throw new Error("Contexts/pre-hash are not supported");return L}:o.domain;function g(L){return c.create(fr(L))}function y(L){let z=P.secretKey;J(L,P.secretKey,"secretKey");let V=J(n(L),2*z,"hashedSecretKey"),N=b(V.slice(0,z)),ue=V.slice(z,2*z),he=g(N);return{head:N,prefix:ue,scalar:he}}function S(L){let{head:z,prefix:V,scalar:N}=y(L),ue=i.multiply(N),he=ue.toBytes();return{head:z,prefix:V,scalar:N,point:ue,pointBytes:he}}function w(L){return S(L).pointBytes}function v(L=Uint8Array.of(),...z){let V=ot(...z);return g(n(m(V,J(L,void 0,"context"),!!s)))}function A(L,z,V={}){Ve(V,{},{},"options"),L=Yn(J(L,void 0,"message")),s&&(L=s(L));let{prefix:N,scalar:ue,pointBytes:he}=S(z),_=v(V.context,N,L),p=i.multiply(_).toBytes(),x=v(V.context,p,he,L),E=c.create(_+x*ue);if(!c.isValid(E))throw new Error("sign failed: invalid s");let C=ot(p,c.toBytes(E));return J(C,P.signature,"result")}let M={zip215:o.zip215};function F(L,z,V,N=M){Ve(N);let{context:ue}=N,he=N.zip215===void 0?!!M.zip215:N.zip215,_=P.signature;L=J(L,_,"signature"),z=J(z,void 0,"message"),V=J(V,P.publicKey,"publicKey"),he!==void 0&&ze(he,"zip215"),s&&(z=s(z));let p=_/2,x=L.subarray(0,p),E=fr(L.subarray(p,_)),C,D,R;try{C=r.fromBytes(V,he),D=r.fromBytes(x,he),R=i.multiplyUnsafe(E)}catch{return!1}if(!he&&C.isSmallOrder())return!1;let U=v(ue,x,V,z);return D.add(C.multiplyUnsafe(U)).subtract(R).clearCofactor().is0()}let B=a.BYTES,P={secretKey:B,publicKey:B,signature:2*B,seed:B};function O(L){return L=L===void 0?f(P.seed):L,J(L,P.seed,"seed")}function G(L){return Gt(L)&&L.length===P.secretKey}function W(L,z){try{return!!r.fromBytes(L,z===void 0?M.zip215:z)}catch{return!1}}let ie={getExtendedPublicKey:S,randomSecretKey:O,isValidSecretKey:G,isValidPublicKey:W,toMontgomery(L){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(r.fromBytes(L))},toMontgomerySecret(L){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(L)}};return Object.freeze(P),Object.freeze(ie),Object.freeze({keygen:Ls(O,w),getPublicKey:w,sign:A,verify:F,utils:ie,Point:r,lengths:P})}var Gc=BigInt(1),Qd=BigInt(2);var Zy=BigInt(5),Qy=BigInt(8),jc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Jy={p:jc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Qy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function e0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=jc,a=r*r%s*r%s,c=de(a,Qd,s)*a%s,u=de(c,Gc,s)*r%s,l=de(u,Zy,s)*u%s,f=de(l,e,s)*l%s,d=de(f,t,s)*f%s,h=de(d,n,s)*d%s,b=de(h,o,s)*h%s,m=de(b,o,s)*h%s,g=de(m,e,s)*l%s;return{pow_p_5_8:de(g,Qd,s)*r%s,b2:a}}function th(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Jd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function t0(r,e){let t=jc,n=me(e*e*e,t),o=me(n*n*e,t),s=e0(r*o).pow_p_5_8,i=me(r*n*s,t),a=me(e*i*i,t),c=i,u=me(i*Jd,t),l=a===r,f=a===me(-r,t),d=a===me(-r*Jd,t);return l&&(i=c),(f||d)&&(i=u),$d(i,t)&&(i=me(-i,t)),{isValid:l||f,value:i}}var Yc=Xd(Jy,{uvRatio:t0}),eh=Yc.Fp;function r0(r){let{y:e}=r;return eh.toBytes(eh.div(Gc+e,Gc-e))}function n0(r){let e=Yc.Fp.BYTES;return nt(r,e),th(Mc(r.subarray(0,e))).subarray(0,e)}function o0(r){return Zd(Yc,Mc,Object.assign({adjustScalarBytes:th,toMontgomery:r0,toMontgomerySecret:n0,zip215:!0},r))}var Jn=o0({});var eo=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},to=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ks=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var He={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ks("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 Os=32,ro=64,Xc=32;var Zr,rh=(async()=>{try{return await He.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function nh(){let r=Jn.utils.randomSecretKey(),e=Jn.getPublicKey(r);return{privateKey:u0(r,e),publicKey:e}}async function s0(r,e){let t;r.length===ro?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:q(r.subarray(32),"base64url"),d:q(t,"base64url"),ext:!0,key_ops:["sign"]},o=await He.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await He.get().subtle.sign({name:"Ed25519"},o,Ie(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function i0(r,e){let t=r.subarray(0,Xc);return Jn.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function oh(r,e){return Zr==null&&(Zr=await rh),Zr?s0(r,e):i0(r,e)}async function a0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await He.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await He.get().subtle.verify({name:"Ed25519"},n,Ie(e),Ie(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function c0(r,e,t){return Jn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function sh(r,e,t){return Zr==null&&(Zr=await rh),Zr?a0(r,e,t):c0(r,e,t)}function u0(r,e){let t=new Uint8Array(ro);for(let n=0;n<Xc;n++)t[n]=r[n],t[Xc+n]=e[n];return t}function Qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var no=class{type="Ed25519";raw;constructor(e){this.raw=Ms(e,Os)}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=sh(this.raw,t,e);return Qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Ns=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ms(e,ro),this.publicKey=new no(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=oh(this.raw,e);return Qr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Zc(r){return r=Ms(r,Os),new no(r)}async function ah(){let{privateKey:r,publicKey:e}=nh();return new Ns(r,e)}function Ms(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new I(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var l0=Math.pow(2,7),f0=Math.pow(2,14),d0=Math.pow(2,21),Qc=Math.pow(2,28),Jc=Math.pow(2,35),eu=Math.pow(2,42),tu=Math.pow(2,49),te=128,Pe=127;function Ae(r){if(r<l0)return 1;if(r<f0)return 2;if(r<d0)return 3;if(r<Qc)return 4;if(r<Jc)return 5;if(r<eu)return 6;if(r<tu)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Jr(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|te,r/=128;case 7:e[t++]=r&255|te,r/=128;case 6:e[t++]=r&255|te,r/=128;case 5:e[t++]=r&255|te,r/=128;case 4:e[t++]=r&255|te,r>>>=7;case 3:e[t++]=r&255|te,r>>>=7;case 2:e[t++]=r&255|te,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function h0(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|te),r/=128;case 7:e.set(t++,r&255|te),r/=128;case 6:e.set(t++,r&255|te),r/=128;case 5:e.set(t++,r&255|te),r/=128;case 4:e.set(t++,r&255|te),r>>>=7;case 3:e.set(t++,r&255|te),r>>>=7;case 2:e.set(t++,r&255|te),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ru(r,e){let t=r[e],n=0;if(n+=t&Pe,t<te||(t=r[e+1],n+=(t&Pe)<<7,t<te)||(t=r[e+2],n+=(t&Pe)<<14,t<te)||(t=r[e+3],n+=(t&Pe)<<21,t<te)||(t=r[e+4],n+=(t&Pe)*Qc,t<te)||(t=r[e+5],n+=(t&Pe)*Jc,t<te)||(t=r[e+6],n+=(t&Pe)*eu,t<te)||(t=r[e+7],n+=(t&Pe)*tu,t<te))return n;throw new RangeError("Could not decode varint")}function p0(r,e){let t=r.get(e),n=0;if(n+=t&Pe,t<te||(t=r.get(e+1),n+=(t&Pe)<<7,t<te)||(t=r.get(e+2),n+=(t&Pe)<<14,t<te)||(t=r.get(e+3),n+=(t&Pe)<<21,t<te)||(t=r.get(e+4),n+=(t&Pe)*Qc,t<te)||(t=r.get(e+5),n+=(t&Pe)*Jc,t<te)||(t=r.get(e+6),n+=(t&Pe)*eu,t<te)||(t=r.get(e+7),n+=(t&Pe)*tu,t<te))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=Se(Ae(r))),e instanceof Uint8Array?Jr(r,e,t):h0(r,e,t)}function dr(r,e=0){return r instanceof Uint8Array?ru(r,e):p0(r,e)}var nu=new Float32Array([-0]),Zt=new Uint8Array(nu.buffer);function ch(r,e,t){nu[0]=r,e[t]=Zt[0],e[t+1]=Zt[1],e[t+2]=Zt[2],e[t+3]=Zt[3]}function uh(r,e){return Zt[0]=r[e],Zt[1]=r[e+1],Zt[2]=r[e+2],Zt[3]=r[e+3],nu[0]}var ou=new Float64Array([-0]),De=new Uint8Array(ou.buffer);function lh(r,e,t){ou[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function fh(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],ou[0]}var m0=BigInt(Number.MAX_SAFE_INTEGER),g0=BigInt(Number.MIN_SAFE_INTEGER),Ge=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 hr;if(e<m0&&e>g0)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>dh&&(o=0n,++n>dh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return hr;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):hr}},hr=new Ge(0,0);hr.toBigInt=function(){return 0n};hr.zzEncode=hr.zzDecode=function(){return this};hr.length=function(){return 1};var dh=4294967296n;function hh(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 ph(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 su(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 lt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Bs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var iu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ie(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,lt(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 lt(this,4);return Bs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw lt(this,4);return Bs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw lt(this,4);let e=uh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw lt(this,4);let e=fh(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 lt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return ph(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw lt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw lt(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 Ge(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 lt(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 lt(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 lt(this,8);let e=Bs(this.buf,this.pos+=4),t=Bs(this.buf,this.pos+=4);return new Ge(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=ru(this.buf,this.pos);return this.pos+=Ae(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 so(r){return new iu(r instanceof Uint8Array?r:r.subarray())}function Be(r,e,t){let n=so(r);return e.decode(n,void 0,t)}function au(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var pr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function cu(){}var lu=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},y0=au();function b0(r){return globalThis.Buffer!=null?Se(r):y0(r)}var ao=class{len;head;tail;states;constructor(){this.len=0,this.head=new pr(cu,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fu((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(Fs,10,Ge.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ge.fromBigInt(e);return this._push(Fs,t.length(),t)}uint64Number(e){return this._push(Jr,Ae(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=Ge.fromBigInt(e).zzEncode();return this._push(Fs,t.length(),t)}sint64Number(e){let t=Ge.fromNumber(e).zzEncode();return this._push(Fs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(uu,1,e?1:0)}fixed32(e){return this._push(io,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ge.fromBigInt(e);return this._push(io,4,t.lo)._push(io,4,t.hi)}fixed64Number(e){let t=Ge.fromNumber(e);return this._push(io,4,t.lo)._push(io,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(ch,4,e)}double(e){return this._push(lh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(uu,1,0):this.uint32(t)._push(x0,t,e)}string(e){let t=hh(e);return t!==0?this.uint32(t)._push(su,t,e):this._push(uu,1,0)}fork(){return this.states=new lu(this),this.head=this.tail=new pr(cu,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 pr(cu,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=b0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function uu(r,e,t){e[t]=r&255}function w0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var fu=class extends pr{next;constructor(e,t){super(w0,e,t),this.next=void 0}};function Fs(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 io(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 x0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ao.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(E0,e,r),this},ao.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(v0,e,r),this});function E0(r,e,t){e.set(r,t)}function v0(r,e,t){r.length<40?su(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function du(){return new ao}function Fe(r,e){let t=du();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Ue(r,e,t){let n=so(r);yield*e.stream(n,void 0,".",t)}var Us={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ks(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function hu(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,a){};return Ks("enum",Us.VARINT,t,n,o)}function Ke(r,e,t){return Ks("message",Us.LENGTH_DELIMITED,r,e,t)}var st=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},co=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var pu;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(pu||(pu={}));(function(r){r.codec=()=>hu(pu)})(ge||(ge={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.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=ge.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:ge.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 Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(wt||(wt={}));var mu;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.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=ge.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:ge.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 Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(mu||(mu={}));var lo={};$e(lo,{MAX_RSA_KEY_SIZE:()=>gu,generateRSAKeyPair:()=>_u,jwkToJWKKeyPair:()=>xh,jwkToPkcs1:()=>C0,jwkToPkix:()=>xu,jwkToRSAPrivateKey:()=>Au,pkcs1MessageToJwk:()=>bu,pkcs1MessageToRSAPrivateKey:()=>Eu,pkcs1ToJwk:()=>_0,pkcs1ToRSAPrivateKey:()=>wh,pkixMessageToJwk:()=>wu,pkixMessageToRSAPublicKey:()=>Su,pkixToJwk:()=>I0,pkixToRSAPublicKey:()=>vu});var en=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=lo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return xe.createV1(114,this._multihash)}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return bh(this.jwk,t,e,n)}},uo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=lo.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return yh(this.jwk,e,t)}};var gu=8192,yu=18,S0=1062,A0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function _0(r){let e=Ct(r);return bu(e)}function bu(r){return{n:q(r[1],"base64url"),e:q(r[2],"base64url"),d:q(r[3],"base64url"),p:q(r[4],"base64url"),q:q(r[5],"base64url"),dp:q(r[6],"base64url"),dq:q(r[7],"base64url"),qi:q(r[8],"base64url"),kty:"RSA"}}function C0(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 I("JWK was missing components");return ct([Me(Uint8Array.from([0])),Me(T(r.n,"base64url")),Me(T(r.e,"base64url")),Me(T(r.d,"base64url")),Me(T(r.p,"base64url")),Me(T(r.q,"base64url")),Me(T(r.dp,"base64url")),Me(T(r.dq,"base64url")),Me(T(r.qi,"base64url"))]).subarray()}function I0(r){let e=Ct(r,{offset:0});return wu(e)}function wu(r){let e=Ct(r[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function xu(r){if(r.n==null||r.e==null)throw new I("JWK was missing components");return ct([A0,zn(ct([Me(T(r.n,"base64url")),Me(T(r.e,"base64url"))]))]).subarray()}function wh(r){let e=Ct(r);return Eu(e)}function Eu(r){let e=bu(r);return Au(e)}function vu(r,e){if(r.byteLength>=S0)throw new mt("Key size is too large");let t=Ct(r,{offset:0});return Su(t,r,e)}function Su(r,e,t){let n=wu(r);if(t==null){let o=Vr(wt.encode({Type:ge.RSA,Data:e}));t=gt(yu,o)}return new en(n,t)}function Au(r){if(vh(r)>gu)throw new I("Key size is too large");let e=xh(r),t=Vr(wt.encode({Type:ge.RSA,Data:xu(e.publicKey)})),n=gt(yu,t);return new uo(e.privateKey,new en(e.publicKey,n))}async function _u(r){if(r>gu)throw new I("Key size is too large");let e=await Eh(r),t=Vr(wt.encode({Type:ge.RSA,Data:xu(e.publicKey)})),n=gt(yu,t);return new uo(e.privateKey,new en(e.publicKey,n))}function xh(r){if(r==null)throw new I("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Eh(r,e){let t=await He.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await T0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function yh(r,e,t){let n=await He.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await He.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ie(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function bh(r,e,t,n){let o=await He.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await He.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ie(e),Ie(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function T0(r,e){if(r.privateKey==null||r.publicKey==null)throw new I("Private and public key are required");let t=await Promise.all([He.get().subtle.exportKey("jwk",r.privateKey),He.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function vh(r){if(r.kty!=="RSA")throw new I("invalid key type");if(r.n==null)throw new I("invalid key modulus");return T(r.n,"base64url").length*8}var qs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hs(e),nt(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,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),cr(o)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),ps(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,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Sh=(()=>{let r=((e,t,n)=>new qs(e,t).update(n).digest());return r.create=(e,t)=>new qs(e,t),r})();var L0=BigInt(0),Cu=class extends Error{constructor(e=""){super(e)}},Lt={Err:Cu,_tlv:{encode:(r,e)=>{let{Err:t}=Lt;if(Tt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Ld(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=jn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?jn(o.length/2|128):"";return jn(r)+s+o+e},decode(r,e){let{Err:t}=Lt;e=J(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let 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}=Lt;if(xs(r),r<L0)throw new e("integer: negative integers are not allowed");let t=jn(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}=Lt;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 bt(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:o}=Lt;if(e!==void 0&&(Tt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let s=J(r,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l:u}=o.decode(2,i),{v:l,l:f}=o.decode(2,u);if(f.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||l.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Lt;Ve(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},$s=(Object.freeze(Lt._tlv),Object.freeze(Lt._int),Object.freeze(Lt));var Ah=(r,e)=>(r+(r>=0?e:-e)/_h)/e;function P0(r,e,t){Wr("scalar",r,Pt,t);let[[n,o],[s,i]]=e,a=Ah(i*r,t),c=Ah(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<Pt,d=l<Pt;f&&(u=-u),d&&(l=-l);let h=Xn(Math.ceil(Gr(t)/2))+mr;if(u<Pt||u>=h||l<Pt||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function Lu(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Iu(r,e){Ve(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ze(t.lowS,"lowS"),ze(t.prehash,"prehash"),t.format!==void 0&&Lu(t.format),t}var Pt=BigInt(0),mr=BigInt(1),_h=BigInt(2),Tu=BigInt(3),D0=BigInt(4);function Ch(r,e={}){let t=Ts("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u,clearCofactor:l,isTorsionFree:f,fromBytes:d,toBytes:h}=e,b=e.randomBytes===void 0?lr:e.randomBytes;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 m=c?{beta:c.beta,basises:c.basises.map(_=>[..._])}:void 0,g=Th(n,o);function y(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function S(_,p,x){if(p.is0()){if(!u)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:E,y:C}=p.toAffine(),D=n.toBytes(E);if(ze(x,"isCompressed"),x){y();let R=!n.isOdd(C);return ot(Ih(R),D)}else return ot(Uint8Array.of(4),D,n.toBytes(C))}function w(_){J(_,void 0,"Point");let{publicKey:p,publicKeyUncompressed:x}=g,E=_.length,C=_[0],D=_.subarray(1);if(u&&E===1&&C===0)return{x:n.ZERO,y:n.ZERO};if(E===p&&(C===2||C===3)){let R=n.fromBytes(D);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let U=B(R),K;try{K=n.sqrt(U)}catch(be){let le=be instanceof Error?": "+be.message:"";throw new Error("bad point: is not on curve, sqrt error"+le)}y();let Q=n.isOdd(K);return(C&1)===1!==Q&&(K=n.neg(K)),{x:R,y:K}}else if(E===x&&C===4){let R=n.BYTES,U=n.fromBytes(D.subarray(0,R)),K=n.fromBytes(D.subarray(R,R*2));if(!P(U,K))throw new Error("bad point: is not on curve");return{x:U,y:K}}else throw new Error(`bad point: got length ${E}, expected compressed=${p} or uncompressed=${x}`)}let v=h===void 0?S:h,A=d===void 0?w:d,M=n.mul(s.b,Tu),F=n.is0(s.a)?_=>n.ZERO:_=>n.mul(s.a,_);function B(_){let p=n.sqr(_),x=n.mul(p,_);return n.add(n.add(x,n.mul(_,s.a)),s.b)}function P(_,p){let x=n.sqr(p),E=B(_);return n.eql(x,E)}if(!P(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let O=n.mul(n.pow(s.a,Tu),D0),G=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(O,G)))throw new Error("bad curve params: a or b");function W(_,p,x=!1){if(!n.isValid(p)||x&&n.is0(p))throw new Error(`bad point coordinate ${_}`);return typeof p=="object"&&p!==null?n.create(p):p}function ie(_){if(!(_ instanceof N))throw new Error("Weierstrass Point expected")}function L(_){if(!m||!m.basises)throw new Error("no endo");return P0(_,m.basises,o.ORDER)}function z(_,p,x,E){if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(m){let{k1neg:C,k1:D,k2neg:R,k2:U}=L(E),K=new N(n.mul(x.X,m.beta),x.Y,x.Z);_.push(C?x.negate():x,R?K.negate():K),p.push(D,U)}else _.push(x),p.push(E)}let V=new WeakSet;class N{static BASE=new N(s.Gx,s.Gy,n.ONE);static ZERO=new N(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,x,E){this.X=W("x",p),this.Y=W("y",x,!0),this.Z=W("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x,y:E}=p||{};if(!p||!n.isValid(x)||!n.isValid(E))throw new Error("invalid affine point");if(p instanceof N)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(E)?N.ZERO:new N(x,E,n.ONE)}static fromBytes(p){let x=N.fromAffine(A(J(p,void 0,"point")));return x.assertValidity(),x}static fromHex(p){return N.fromBytes(Hr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,x=!0){return he.setWindowSize(this,p),x||this.multiply(Tu),this}assertValidity(){let p=this;if(p.is0()){if(u&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(V.has(p))return;let{x,y:E}=p.toAffine();if(!n.isValid(x)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!P(x,E))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");V.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){ie(p);let{X:x,Y:E,Z:C}=this,{X:D,Y:R,Z:U}=p,K=n.eql(n.mul(x,U),n.mul(D,C)),Q=n.eql(n.mul(E,U),n.mul(R,C));return K&&Q}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:x,Z:E}=this,C=n.ZERO,D=n.ZERO,R=n.ZERO,U=n.mul(p,p),K=n.mul(x,x),Q=n.mul(E,E),j=n.mul(p,x);return j=n.add(j,j),R=n.mul(p,E),R=n.add(R,R),C=F(R),D=n.mul(M,Q),D=n.add(C,D),C=n.sub(K,D),D=n.add(K,D),D=n.mul(C,D),C=n.mul(j,C),R=n.mul(M,R),Q=F(Q),j=n.sub(U,Q),j=F(j),j=n.add(j,R),R=n.add(U,U),U=n.add(R,U),U=n.add(U,Q),U=n.mul(U,j),D=n.add(D,U),Q=n.mul(x,E),Q=n.add(Q,Q),U=n.mul(Q,j),C=n.sub(C,U),R=n.mul(Q,K),R=n.add(R,R),R=n.add(R,R),new N(C,D,R)}add(p){ie(p);let{X:x,Y:E,Z:C}=this,{X:D,Y:R,Z:U}=p,K=n.ZERO,Q=n.ZERO,j=n.ZERO,be=n.mul(x,D),le=n.mul(E,R),ve=n.mul(C,U),Ze=n.add(x,E),fe=n.add(D,R);Ze=n.mul(Ze,fe),fe=n.add(be,le),Ze=n.sub(Ze,fe),fe=n.add(x,C);let we=n.add(D,U);return fe=n.mul(fe,we),we=n.add(be,ve),fe=n.sub(fe,we),we=n.add(E,C),K=n.add(R,U),we=n.mul(we,K),K=n.add(le,ve),we=n.sub(we,K),j=F(fe),K=n.mul(M,ve),j=n.add(K,j),K=n.sub(le,j),j=n.add(le,j),Q=n.mul(K,j),le=n.add(be,be),le=n.add(le,be),ve=F(ve),fe=n.mul(M,fe),le=n.add(le,ve),ve=n.sub(be,ve),ve=F(ve),fe=n.add(fe,ve),be=n.mul(le,fe),Q=n.add(Q,be),be=n.mul(we,fe),K=n.mul(Ze,K),K=n.sub(K,be),be=n.mul(Ze,le),j=n.mul(we,j),j=n.add(j,be),new N(K,Q,j)}subtract(p){return ie(p),this.add(p.negate())}is0(){return this.equals(N.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:x,f:E}=he.mulSecret(this,p,i,ue);return ue([x,E])[0]}multiplyUnsafe(p){let x=this,E=p;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===Pt||x.is0())return N.ZERO;if(E===mr)return x;if(he.hasWindowSize(this))return he.mulUnsafe(x,E,ue);let C=[],D=[];return z(C,D,x,E),Is(N,C,D)}mulAddUnsafe(p,x,E){ie(x);let C=[],D=[];return z(C,D,this,p),z(C,D,x,E),Is(N,C,D)}toAffine(p){let x=this,E=p;if(E!=null&&!n.isValid(E))throw new RangeError('"invertedZ" expected valid field element');let{X:C,Y:D,Z:R}=x;if(n.eql(R,n.ONE))return{x:C,y:D};let U=x.is0();E==null&&(E=U?n.ONE:n.inv(R));let K=n.mul(C,E),Q=n.mul(D,E),j=n.mul(R,E);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(j,n.ONE))throw new Error("invZ was invalid");return{x:K,y:Q}}isTorsionFree(){return i===mr?!0:f?f(N,this):he.mulUnsafe(this,a).is0()}clearCofactor(){return i===mr?this:l?l(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===mr?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return ze(p,"isCompressed"),this.assertValidity(),v(N,this,p)}toHex(p=!0){return Gn(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ue=_=>Cs(N,_),he=new Xr(N,b);return he.bits>=6&&N.BASE.precompute(6),Object.freeze(N.prototype),Object.freeze(N),N}function Ih(r){return Uint8Array.of(r?2:3)}function Th(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function R0(r,e={}){Yt(r);let{Fn:t}=r,n=e.randomBytes===void 0?lr:e.randomBytes,o=Object.assign(Th(r.Fp,t),{seed:Math.max(As(t.ORDER),16)});function s(h){try{let b=t.fromBytes(h);return t.isValidNot0(b)}catch{return!1}}function i(h,b){let{publicKey:m,publicKeyUncompressed:g}=o;try{let y=h.length;return b===!0&&y!==m||b===!1&&y!==g?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,_s(J(h,o.seed,"seed"),t.ORDER)}function c(h,b=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:m,publicKeyUncompressed:g}=o,y=t._lengths;if(!Gt(h))return;let S=J(h,void 0,"key").length,w=S===m||S===g,v=S===b||!!y?.includes(S);if(!(w&&v))return w}function l(h,b,m=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(b)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h),y=r.fromBytes(b);if(y.is0())throw new Error("invalid public key: point at infinity");return y.multiply(g).toBytes(m)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ls(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function Lh(r,e,t={}){Yt(r);let n=e;hs(n),Ve(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?lr:o.randomBytes,i=o.hmac===void 0?(_,p)=>Sh(n,_,p):o.hmac,{Fp:a,Fn:c}=r,{ORDER:u,BITS:l}=c,f=As(u),d=Wc(s,f),{keygen:h,getPublicKey:b,getSharedSecret:m,utils:g,lengths:y}=R0(r,o),S={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},w=u*_h+mr<a.ORDER;function v(_){let p=u>>mr;return _>p}function A(_,p){if(!c.isValidNot0(p))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return p}function M(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function F(_,p,x){return M(),(_===x?0:2)|Number(a.isOdd(p))}function B(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(_,p){Lu(p);let x=y.signature,E=p==="compact"?x:p==="recovered"?x+1:void 0;return J(_,E)}class O{r;s;recovery;constructor(p,x,E){if(this.r=A("r",p),this.s=A("s",x),E!=null){if(B(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(p,x=S.format){P(p,x);let E;if(x==="der"){if(p.length>2*c.BYTES+16)throw new $s.Err("invalid signature: DER signature too long");let{r:U,s:K}=$s.toSig(J(p),c.BYTES+1);return new O(U,K)}x==="recovered"&&(E=p[0],x="compact",p=p.subarray(1));let C=y.signature/2,D=p.subarray(0,C),R=p.subarray(C,C*2);return new O(c.fromBytes(D),c.fromBytes(R),E)}static fromHex(p,x){return this.fromBytes(Hr(p),x)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new O(this.r,this.s,p)}recoverPublicKey(p){let{r:x,s:E}=this,C=this.assertRecovery(),D=C===2||C===3?x+u:x;if(!a.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=a.toBytes(D),U=r.fromBytes(ot(Ih((C&1)===0),R)),K=c.inv(D),Q=W(J(p,void 0,"msgHash")),j=c.create(-Q*K),be=c.create(E*K),le=r.BASE.mulAddUnsafe(j,U,be);if(le.is0())throw new Error("invalid recovery: point at infinify");return le.assertValidity(),le}hasHighS(){return v(this.s)}toBytes(p=S.format){if(Lu(p),p==="der")return Hr($s.hexFromSig(this));let{r:x,s:E}=this,C=c.toBytes(x),D=c.toBytes(E);return p==="recovered"?(B(),ot(Uint8Array.of(this.assertRecovery()),C,D)):ot(C,D)}toHex(p){return Gn(this.toBytes(p))}}Object.freeze(O.prototype),Object.freeze(O);let G=o.bits2int===void 0?function(p){if(p.length>8192)throw new Error("input is too large");let x=bt(p),E=p.length*8-l;return E>0?x>>BigInt(E):x}:o.bits2int,W=o.bits2int_modN===void 0?function(p){return c.create(G(p))}:o.bits2int_modN,ie=Xn(l);function L(_){return Wr("num < 2^"+l,_,Pt,ie),c.toBytes(_)}function z(_,p){return J(_,void 0,"message"),p?J(n(_),void 0,"prehashed message"):_}function V(_,p,x){let{lowS:E,prehash:C,extraEntropy:D}=Iu(x,S);_=z(_,C);let R=W(_),U=c.fromBytes(p);if(!c.isValidNot0(U))throw new Error("invalid private key");let K=[L(U),L(R)];if(D!=null&&D!==!1){let le=D===!0?s(y.secretKey):D;K.push(J(le,void 0,"extraEntropy"))}let Q=ot(...K),j=R;function be(le){let ve=G(le);if(!c.isValidNot0(ve))return;let Ze=r.BASE.multiply(ve).toAffine(),fe=c.create(Ze.x);if(fe===Pt)return;let we;if(d!==void 0){let Pn=bt(_s(d(f),u)),Km=c.inv(c.mul(Pn,ve)),qm=c.mul(Pn,j),$m=c.mul(Pn,U);we=c.create(Km*c.create(qm+$m*fe))}else{let Pn=Ud(ve,u);we=c.create(Pn*c.create(j+fe*U))}if(we===Pt)return;let za=F(Ze.x,Ze.y,fe),Af=we;return E&&v(we)&&(Af=c.neg(we),za^=1),new O(fe,Af,w?void 0:za)}return{seed:Q,k2sig:be}}function N(_,p,x={}){let{seed:E,k2sig:C}=V(_,p,x);return Dd(n.outputLen,c.BYTES,i)(E,C).toBytes(x.format)}function ue(_,p,x,E={}){let{lowS:C,prehash:D,format:R}=Iu(E,S);if(x=J(x,void 0,"publicKey"),p=z(p,D),!Gt(_)){let U=_ instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}P(_,R);try{let U=O.fromBytes(_,R),K=r.fromBytes(x);if(K.is0()||C&&U.hasHighS())return!1;let{r:Q,s:j}=U,be=W(p),le=c.inv(j),ve=c.create(be*le),Ze=c.create(Q*le),fe=r.BASE.mulAddUnsafe(ve,K,Ze);if(fe.is0())return!1;let we=fe.toAffine();return!(c.create(we.x)!==Q||R==="recovered"&&U.recovery!==F(we.x,we.y,Q))}catch{return!1}}function he(_,p,x={}){let{prehash:E}=Iu(x,S);return p=z(p,E),O.fromBytes(_,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:h,getPublicKey:b,getSharedSecret:m,utils:g,lengths:y,Point:r,sign:N,verify:ue,recoverPublicKey:he,Signature:O,hash:n})}var Du={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},k0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ph=BigInt(2);function O0(r){let e=Du.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=de(l,t,e)*l%e,d=de(f,t,e)*l%e,h=de(d,Ph,e)*u%e,b=de(h,o,e)*h%e,m=de(b,s,e)*b%e,g=de(m,a,e)*m%e,y=de(g,c,e)*g%e,S=de(y,a,e)*m%e,w=de(S,t,e)*l%e,v=de(w,i,e)*b%e,A=de(v,n,e)*u%e,M=de(A,Ph,e);if(!Pu.eql(Pu.sqr(M),r))throw new Error("Cannot find square root");return M}var Pu=Yr(Du.p,{sqrt:O0}),N0=Ch(Du,{Fp:Pu,endo:k0}),ft=Lh(N0,Vr);function Dh(r,e,t){let n=$r.digest(e instanceof Uint8Array?e:e.subarray());if(Qr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ft.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new eo(String(o))});try{return ft.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new eo(String(o))}}function Rh(r,e,t,n){let o=$r.digest(t instanceof Uint8Array?t:t.subarray());if(Qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ft.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new to(String(s))});try{return n?.signal?.throwIfAborted(),ft.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new to(String(s))}}var fo=class{type="secp256k1";raw;_key;constructor(e){this._key=Nh(e),this.raw=kh(this._key)}toMultihash(){return at.digest(rt(this))}toCID(){return xe.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return Rh(this._key,t,e,n)}},zs=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Oh(e),this.publicKey=new fo(t??Mh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return Dh(this.raw,e,t)}};function Ru(r){return new fo(r)}async function Bh(){let r=M0();return new zs(r)}function kh(r){return ft.Point.fromBytes(r).toBytes()}function Oh(r){try{return ft.getPublicKey(r,!0),r}catch(e){throw new Rn(String(e))}}function Nh(r){try{return ft.Point.fromBytes(r),r}catch(e){throw new mt(String(e))}}function Mh(r){try{return ft.getPublicKey(r,!0)}catch(e){throw new Rn(String(e))}}function M0(){return ft.utils.randomSecretKey()}async function Fh(r,e){if(r==="Ed25519")return ah();if(r==="secp256k1")return Bh();if(r==="RSA")return _u(B0(e));if(r==="ECDSA")return ud(F0(e));throw new Ft}function ho(r,e){let{Type:t,Data:n}=wt.decode(r),o=n??new Uint8Array;switch(t){case ge.RSA:return vu(o,e);case ge.Ed25519:return Zc(o);case ge.secp256k1:return Ru(o);case ge.ECDSA:return _c(o);default:throw new Ft}}function Uh(r){let{Type:e,Data:t}=wt.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Zc(n);case ge.secp256k1:return Ru(n);case ge.ECDSA:return _c(n);default:throw new Ft}}function rt(r){return wt.encode({Type:ge[r.type],Data:r.raw})}async function Kh(r,e,t){if(t?.signal?.throwIfAborted(),e!=null){let n;try{n=e instanceof Uint8Array?ho(e):e}catch(o){throw new mt(`Could not decode public key - ${o.message}`)}if(!X(n.toMultihash().bytes,r.toMultihash().bytes))throw new mt("Public key does not match peer id");return n}if(r.publicKey==null)throw new mt("No public key available for peer id");return r.publicKey}function B0(r){return r==null?2048:parseInt(r,10)}function F0(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 I("Unsupported curve, should be P-256, P-384 or P-521")}var qh=Symbol.for("nodejs.util.inspect.custom"),U0=114,po=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()})`}[os]=!0;toString(){return this.string==null&&(this.string=se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return xe.createV1(U0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return X(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[qh](){return`PeerId(${this.toString()})`}},mo=class extends po{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},go=class extends po{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},yo=class extends po{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},K0=2336,bo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=at.digest(T(this.url))}[qh](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return xe.createV1(K0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var q0=114,$h=2336;function xt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=_t(se.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ku(xe.parse(r));if(e==null)throw new I('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=_t(e.decode(r))}return tn(t)}function wo(r){if(r.type==="Ed25519")return new go({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new yo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new mo({multihash:r.toCID().multihash,publicKey:r});throw new Ft}function zh(r){return wo(r.publicKey)}function tn(r){if(z0(r))return new mo({multihash:r});if($0(r))try{let e=Uh(r);if(e.type==="Ed25519")return new go({multihash:r,publicKey:e});if(e.type==="secp256k1")return new yo({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new bo(new URL(t))}throw new Zo("Supplied PeerID Multihash is invalid")}function ku(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==q0&&r.code!==$h)throw new Xo("Supplied PeerID CID is invalid");if(r.code===$h){let e=q(r.multihash.digest);return new bo(new URL(e))}return tn(r.multihash)}function $0(r){return r.code===at.code}function z0(r){return r.code===$r.code}async function Vh(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new I("Private network is enforced, but no protector was provided");return r}function Vs(r,e){if(typeof r=="string")return V0(r);if(typeof r=="number")return G0(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function V0(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 H0(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function W0(r){let e=Math.abs(r);return e>=315576e5?gr(r,e,315576e5,"year"):e>=26298e5?gr(r,e,26298e5,"month"):e>=6048e5?gr(r,e,6048e5,"week"):e>=864e5?gr(r,e,864e5,"day"):e>=36e5?gr(r,e,36e5,"hour"):e>=6e4?gr(r,e,6e4,"minute"):e>=1e3?gr(r,e,1e3,"second"):`${r} ms`}function G0(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?W0(r):H0(r)}function gr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Ou(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Vs,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,b,m;function g(...y){if(!g.enabled)return;let S=g,w=Number(new Date),v=w-(d||w);S.diff=v,S.prev=d,S.curr=w,d=w,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,(F,B)=>{if(F==="%%")return"%";A++;let P=t.formatters[B];if(typeof P=="function"){let O=y[A];F=P.call(S,O),y.splice(A,1),A--}return F}),t.formatArgs.call(S,y),f?.onLog!=null&&f.onLog(...y),(S.log||t.log).apply(S,y)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(b!==t.namespaces&&(b=t.namespaces,m=t.enabled(l)),m),set:y=>{h=y}}),typeof t.init=="function"&&t.init(g),g}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 Hs=eb(),j0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Y0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function X0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Vs(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 Z0=console.debug??console.log??(()=>{});function Q0(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function J0(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function eb(){try{return localStorage}catch{}}function tb(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Hh=Ou({formatArgs:X0,save:Q0,load:J0,useColors:Y0,setupFormatters:tb,colors:j0,storage:Hs,log:Z0});var We=Hh;We.formatters.b=r=>r==null?"undefined":se.baseEncode(r);We.formatters.t=r=>r==null?"undefined":et.baseEncode(r);We.formatters.m=r=>r==null?"undefined":dc.baseEncode(r);We.formatters.p=r=>r==null?"undefined":r.toString();We.formatters.c=r=>r==null?"undefined":r.toString();We.formatters.k=r=>r==null?"undefined":r.toString();We.formatters.a=r=>r==null?"undefined":r.toString();function Wh(r,e=""){let t=Gh(r.message),n=Gh(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 eb(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function jh(r,e=""){if(eb(r)){let t=Hh(r,e);return r.errors.length>0?(e=`${e} `,t+=`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function rb(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function jh(r,e=""){if(rb(r)){let t=Wh(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
10
  ${e}${r.errors.map(n=>`${jh(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return Hh(r,e)}We.formatters.e=r=>r==null?"undefined":jh(r);function tb(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 Ws(r){return{forComponent(e){return Gh(e,r)}}}function Gh(r,e){let t=tb(`${r}:trace`);return We.enabled(`${r}:trace`)&&We.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=We(`${r}:trace`,e)),Object.assign(We(r,e),{error:We(`${r}:error`,e),trace:t,newScope:n=>Gh(`${r}:${n}`,e)})}function Wh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function yr(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 js(r){let e=At(se.decode(`z${r}`));return rn(e)}var it=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 yr(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 yr(this.map.values(),e=>e.key)}values(){return yr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=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 yr(this.set.entries(),e=>{let t=js(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=js(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return yr(this.set.values(),e=>js(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 Nl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Yh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Xh=new globalThis.TextEncoder;function rb(r,e){let t=Nl[e],n=Yh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function nb(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Nl[e],o=Yh[e],s=r;for(;s.length>0;){let i=Xh.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 Ml(r,{size:e=32,utf8Buffer:t}={}){if(!Nl[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 nb(r,e,t);r=Xh.encode(r)}return rb(r,e)}var xo={hash:r=>Number(Ml(r,{size:32})),hashV:(r,e)=>ob(xo.hash(r,e))};function ob(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var Bl=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Bl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function wr(r,e){return Math.floor(Math.random()*(e-r))+r}var xr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=wr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var sb=500,Eo=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??xo,this.seed=e.seed??wr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new dt(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 xr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[wr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xr(this.bucketSize));for(let a=0;a<sb;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 xr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new dt(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=T(e));let t=new dt(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}},ib={1:.5,2:.84,4:.95,8:.98};function ab(r=.001){return r>.002?2:r>1e-5?4:8}function Zh(r,e=.001){let t=ab(e),n=ib[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Bl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Gs=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??xo,this.seed=e.seed??wr(0,Math.pow(2,10)),this.filterSeries=[new Eo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Eo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function vo(r,e=.001,t){return new Gs({...Zh(r,e),...t??{}})}function Fl(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 Y(r){let e=Fl(r);if(e==null)throw new C(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Ys=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Qh=45,cb=15,nn=new Ys;function Xs(r){if(!(r.length>cb))return nn.new(r).parseWith(()=>nn.readIPv4Addr())}function Zs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qh))return nn.new(r).parseWith(()=>nn.readIPv6Addr())}function on(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Qh)return;let t=nn.new(r).parseWith(()=>nn.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 Jh(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 ep(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 Ul(r){switch(r.length){case Er:return r.join(".");case vr:{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 tp(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 rp(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Er=4,vr=16,$A=parseInt("0xFFFF",16),lb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function So(r,e){e.length===vr&&r.length===Er&&Jh(e,0,11)&&(e=e.slice(12)),e.length===Er&&r.length===vr&&ep(r,lb,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 np(r,e){if(typeof e=="string"&&(e=on(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 Kl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Er,o=Xs(e);if(o==null&&(n=vr,o=Zs(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=ql(s,8*n);return{network:So(o,i),mask:i}}function ql(r,e){if(e!==8*Er&&e!==8*vr)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 sn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Kl(e));else{let n=on(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=on(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=ql(o,8*n.length);this.network=So(n,this.mask)}}contains(e){return np({network:this.network,mask:this.mask},e)}toString(){let e=tp(this.mask),t=e!==-1?String(e):rp(this.mask);return Ul(this.network)+"/"+t}};function op(r){try{let e=Y(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 sp(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let o=n.split(".");return o.length===4&&o[0]==="127"&&o.every(s=>/^\d{1,3}$/.test(s))}function Ao(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return sp(e.host);default:return!1}}catch{return!1}}function Te(r){return Fl(r)!==null}function ht(r){return!!Xs(r)}function Qs(r){return!!Zs(r)}var lp=Va(cp(),1),gb=["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"],yb=gb.map(r=>new lp.Netmask(r));function Gl(r){for(let e of yb)if(e.contains(r))return!0;return!1}function bb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function wb(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 Gl(o)}function xb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Eb(r){let e=r.split(":"),t=e[e.length-1];return Gl(t)}function vb(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 un(r){if(ht(r))return Gl(r);if(bb(r))return wb(r);if(xb(r))return Eb(r);if(Qs(r))return vb(r)}function Pt(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return un(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var Le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Dt=class extends Error{static name="ValidationError";name="ValidationError"},ei=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ti=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Xl(r){return e=>q(e,r)}function Zl(r){return e=>T(e,r)}function fn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ar(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function up(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ar(n);return tt([t,o],t.length+o.length)}function fp(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=Ar(n);return tt([t,o],t.length+o.length)}function Ql(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=q(e,"base32"),o=fn(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 Le("Invalid byte value in IP address");e[n]=o}),e},dp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ht(t[n]),i;s&&(i=Jl(t[n]),t[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,q(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 Le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},hp=function(r){if(r.byteLength!==4)throw new Le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},pp=function(r){if(r.byteLength!==16)throw new Le("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 Le(`Invalid IPv6 address "${t}"`)}};function mp(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${r}"`)}}var Yl=Object.values(qn).map(r=>r.decoder),Sb=(function(){let r=Yl[0].or(Yl[1]);return Yl.slice(2).forEach(e=>r=r.or(e)),r})();function gp(r){return Sb.decode(r)}function yp(r){return e=>r.encoder.encode(e)}function Ab(r){if(parseInt(r).toString()!==r)throw new Dt("Value must be an integer")}function _b(r){if(r<0)throw new Dt("Value must be a positive integer, or zero")}function Ib(r){return e=>{if(e>r)throw new Dt(`Value must be smaller than or equal to ${r}`)}}function Cb(...r){return e=>{for(let t of r)t(e)}}var _o=Cb(Ab,_b,Ib(65535));var _e=-1,eu=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 ti(`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)}))}},kt=new eu,qb=[{code:4,name:"ip4",size:32,valueToBytes:Jl,bytesToValue:hp,validate:r=>{if(!ht(r))throw new Dt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:_o},{code:273,name:"udp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:_o},{code:33,name:"dccp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:_o},{code:41,name:"ip6",size:128,valueToBytes:dp,bytesToValue:pp,stringToValue:mp,validate:r=>{if(!Qs(r))throw new Dt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:_e},{code:43,name:"ipcidr",size:8,bytesToValue:Xl("base10"),valueToBytes:Zl("base10")},{code:53,name:"dns",size:_e},{code:54,name:"dns4",size:_e},{code:55,name:"dns6",size:_e},{code:56,name:"dnsaddr",size:_e},{code:132,name:"sctp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:_o},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:_e,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:_e,bytesToValue:Xl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Zl("base58btc")(r):xe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ql,valueToBytes:up},{code:445,name:"onion3",size:296,bytesToValue:Ql,valueToBytes:fp},{code:446,name:"garlic64",size:_e},{code:447,name:"garlic32",size:_e},{code:448,name:"tls"},{code:449,name:"sni",size:_e},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:_e,bytesToValue:yp(hc),valueToBytes:gp},{code:480,name:"http"},{code:481,name:"http-path",size:_e,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:_e}];qb.forEach(r=>{kt.addProtocol(r)});function bp(r){let e=[],t=0;for(;t<r.length;){let n=dr(r,t),o=kt.getProtocol(n),s=Ae(n),i=$b(o,r,t+s),a=0;i>0&&o.size===_e&&(a=Ae(i));let c=s+a+i,l={code:n,name:o.name,bytes:Ce(r.subarray(t,t+c))};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??q(f)}e.push(l),t+=c}return e}function wp(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=kt.getProtocol(n.code),s=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===_e&&(c=Ae(a)));let l=new Uint8Array(s+c+a),u=0;Jr(n.code,l,u),u+=s,i!=null&&(o.size===_e&&(Jr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function xp(r){if(r.charAt(0)!=="/")throw new Le('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=kt.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 Le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Le(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Le("Incomplete multiaddr");return e}function Ep(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=kt.getProtocol(e.code);if(t==null)throw new Le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function $b(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:dr(e,t)}var zb=Symbol.for("nodejs.util.inspect.custom"),pu=Symbol.for("@multiformats/multiaddr");function Vb(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return bp(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),xp(r);if(Array.isArray(r))return r;throw new Le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ai=class r{[pu]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=Vb(e),t.validate!==!1&&Hb(this)}get bytes(){return this.#n==null&&(this.#n=wp(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=Ep(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 ei(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[zb](){return`Multiaddr(${this.toString()})`}};function Hb(r){r.getComponents().forEach(e=>{let t=kt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function er(r){return!!r?.[pu]}function re(r){return new ai(r)}var ae=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),k=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),vp=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Re=(...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}}),X=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ce(...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 Wb=k(421),Sp=ce(Wb),li=k(54),ui=k(55),fi=k(56),gu=k(53),TI=ce(li,H(k(421))),LI=ce(ui,H(k(421))),PI=ce(fi,H(k(421))),DI=ce(Re(gu,fi,li,ui),H(k(421))),Ap=X(k(4),H(k(43))),_p=X(H(k(42)),k(41),H(k(43))),yu=Re(Ap,_p),yn=Re(yu,gu,li,ui,fi),RI=ce(Re(yu,X(Re(gu,fi,li,ui),H(k(421))))),bu=ce(Ap),wu=ce(_p),kI=ce(yu),xu=X(yn,k(6)),Io=X(yn,k(273)),Co=ce(X(xu,H(k(421)))),OI=ce(Io),Eu=X(Io,ae(460),H(k(421))),di=X(Io,ae(461),H(k(421))),jb=Re(Eu,di),NI=ce(Eu),Ip=ce(di),mu=Re(yn,xu,Io,Eu,di),Cp=Re(X(mu,ae(477),H(k(421)))),Ir=ce(Cp),Tp=Re(X(mu,ae(478),H(k(421))),X(mu,ae(448),H(k(449)),ae(477),H(k(421)))),To=ce(Tp),Lp=X(Io,ae(280),H(k(466)),H(k(466)),H(k(421))),vu=ce(Lp),Pp=X(di,ae(465),H(k(466)),H(k(466)),H(k(421))),Su=ce(Pp),ci=Re(Cp,Tp,X(xu,H(k(421))),X(jb,H(k(421))),X(yn,H(k(421))),Lp,Pp,k(421)),MI=ce(ci),Gb=X(H(ci),ae(290),vp(ae(281)),H(k(421))),Cr=ce(Gb),Yb=Re(X(ci,ae(290),ae(281),H(k(421))),X(ci,ae(281),H(k(421))),X(ae(281),H(k(421)))),Au=ce(Yb),Xb=X(yn,Re(X(k(6,"80")),X(k(6),ae(480)),ae(480)),H(k(481)),H(k(421))),BI=ce(Xb),Zb=X(yn,Re(X(k(6,"443")),X(k(6,"443"),ae(480)),X(k(6),ae(443)),X(k(6),ae(448),ae(480)),X(ae(448),ae(480)),ae(448),ae(443)),H(k(481)),H(k(421))),FI=ce(Zb),Qb=Re(X(k(777),H(k(421)))),UI=ce(Qb),Jb=Re(X(k(400),H(k(421)))),KI=ce(Jb);function Dp(r,e){let t=Co.exactMatch(r),n=Co.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=To.exactMatch(r),s=To.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=Ir.exactMatch(r),a=Ir.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=Au.exactMatch(r),l=Au.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=vu.exactMatch(r),f=vu.exactMatch(e);if(u&&!f)return-1;if(!u&&f)return 1;let d=Su.exactMatch(r),h=Su.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function Rp(r,e){let t=Ao(r),n=Ao(e);return t&&!n?1:!t&&n?-1:0}function kp(r,e){let t=Pt(r),n=Pt(e);return t&&!n?1:!t&&n?-1:0}function Op(r,e){let t=Cr.exactMatch(r),n=Cr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ie(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var hi=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}},bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hi(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 hi(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 _u=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 ew(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 ew(r,e){e=e??{};let t=e.onEnd,n=new bn,o,s,i,a=Ie(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=v=>{s=null,n.push(v);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ie()})}},l=g=>s!=null?s(g):(n.push(g),o),u=g=>(n=new bn,s!=null?s({error:g}):(n.push({error:g}),o)),f=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?u(g):l({done:!0})),h=()=>(n=new bn,d(),{done:!0}),b=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:b,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,w;y!=null&&(v=new Promise((A,S)=>{w=()=>{S(new _u)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,v])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Iu=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Np=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(Np(i)),r.then(f,d);return}if(i&&(c=()=>{d(Np(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Iu;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(b){d(b)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var tw=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 rw(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=tw(r),f=async(...h)=>{let b=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(b))return}catch(m){n(),i(m);return}c.push(b),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Lo(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function pt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=rw(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Po(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var pi=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}},mi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Tr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function nw(r){return r.reason}function Ge(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??nw;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var gi=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ie(),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 ow(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Mp=new WeakMap,yi=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=ow(),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 gi(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 Ge(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Mp.get(t);if(n==null&&(n=new WeakSet,Mp.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.deferred.reject(e.signal?.reason??new Qe),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var xn=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Po(this.emitEmpty.bind(this),1),this.emitIdle=Po(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new mi;let n=new yi(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 pt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pt(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 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 Et(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 En=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 sw=1.2,iw=2,aw=5e3,cw=6e4,lw=5e3,bi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??lw;this.success=new En(t),this.failure=new En(t),this.next=new En(t),this.failureMultiplier=e.failureMultiplier??iw,this.timeoutMultiplier=e.timeoutMultiplier??sw,this.minTimeout=e.minTimeout??aw,this.maxTimeout=e.maxTimeout??cw,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=Et([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 Cu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ie(),this.haveNext=Ie()}[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=Ie(),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=Ie(),await Ge(this.readNext.promise,t?.signal,t)}};function Bp(){return new Cu}function Fp(r){return r[Symbol.asyncIterator]!=null}async function uw(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;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*fw(r){let e=new AbortController,t=Bp(),n=r.map(o=>Fp(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());uw(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*dw(r){for(let e of r)yield*e}function hw(...r){let e=[];for(let t of r)Fp(t)||e.push(t);return e.length===r.length?dw(e):fw(r)}var vn=hw;var pw=4194304,wi=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Lu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Du=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function mw(r){return typeof r?.closeRead=="function"}function gw(r){return typeof r?.close=="function"}function Tu(r){return mw(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:gw(r)?r.status!=="open":!1}function yw(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Ru(r,e){let t=e?.maxBufferSize??pw,n=new ne,o,s=!1,i;if(!yw(r))throw new C("Argument should be a Stream or a Multiaddr");let a=f=>{if(!s&&i==null){if(n.append(f.data),n.byteLength>t){let d=n.byteLength;n.consume(d);let h=new Yo(`Read buffer overflow - ${d} > ${t}`);i=h,o?.reject(h),queueMicrotask(()=>{r.abort(h)});return}o?.resolve()}};r.addEventListener("message",a);let c=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",c);let l=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",l);let u={readBuffer:n,async read(f){if(s===!0)throw new wi("Stream was unwrapped");if(i!=null)throw i;if(Tu(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new Tr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let d=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ge(o.promise,f?.signal),Tu(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let h=f?.bytes??n.byteLength;if(n.byteLength<h){if(Tu(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Tr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return u.read(f)}let b=n.sublist(0,h);return n.consume(h),b},async write(f,d){if(s===!0)throw new wi("Stream was unwrapped");r.send(f)||await pt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",l),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n),n.consume(n.byteLength))),r}};return u}function xi(r,e={}){let t=Ru(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??dr,o=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new ne;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Lu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Du(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Pu(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Tr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Tr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){let c=new ne(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Ei=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},vi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Si(r){return r[Symbol.asyncIterator]!=null}function Up(r,e){if(r.byteLength>e)throw new Sn("Message length too long")}var _i=r=>{let e=Ae(r),t=Se(e);return Xt(r,t),_i.bytes=e,t};_i.bytes=0;function Ii(r,e){e=e??{};let t=e.lengthEncoder??_i,n=e?.maxDataLength??4194304;function*o(s){Up(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Si(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ii.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??_i,n=e?.maxDataLength??4194304;return Up(r,n),new ne(t(r.byteLength),r)};var Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Ou=r=>{let e=dr(r);return Ou.bytes=Ae(e),e};Ou.bytes=0;function ku(r,e){let t=new ne,n=Lr.LENGTH,o=-1,s=e?.lengthDecoder??Ou,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(t),o<0)throw new Ei("Invalid message length");if(o>a)throw new Sn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Lr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new vi("Message length length too long");break}throw l}if(n===Lr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Lr.LENGTH}}}return Si(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})()}ku.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 ku(n,{...e??{},onLength:s=>{t=s}})};var Ci=class extends xn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ti=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 Li=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 Nu}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 pi("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)}},Nu=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 Mu=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 ke(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Mu({name:e,metrics:t}):n=new Map,n}var Bu=class extends it{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 Fu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Bu({name:e,metrics:t}):n=new it,n}var Ro;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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:pe(0),payloadType:pe(0),payload:pe(0),signature:pe(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Ro||(Ro={}));var Pi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var An=class r{static createFromProtobuf=e=>{let t=Ro.decode(e),n=tn(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=Kp(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 Pi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({publicKey:rt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Q(this.marshal(),e.marshal())}async validate(e,t){let n=Kp(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Kp=(r,e,t)=>{let n=T(r),o=Xt(n.byteLength),s=Xt(e.length),i=Xt(t.length);return new ne(o,n,s,e,i,t)};var qp="libp2p-peer-record",$p=Uint8Array.from([3,1]);var ko;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ke((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 b={multiaddr:pe(0)},m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();g>>>3===1?b.multiaddr=f.bytes():f.skipType(g&7)}return b},function*(f,d,h,b={}){let m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(g&7)}})),a);function c(f){return Fe(f,i.codec())}i.encode=c;function l(f,d){return Be(f,i.codec(),d)}i.decode=l;function u(f,d){return Ue(f,i.codec(),d)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:pe(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Fe(i,r.codec())}r.encode=n;function o(i,a){return Be(i,r.codec(),a)}r.decode=o;function s(i,a){return Ue(i,r.codec(),a)}r.stream=s})(ko||(ko={}));function zp(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 Pr=class r{static createFromProtobuf=e=>{let t=ko.decode(e),n=rn(At(t.peerId)),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=qp;static CODEC=$p;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=ko.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||!zp(this.multiaddrs,e.multiaddrs))}};function ww(r){return r[Symbol.asyncIterator]!=null}function xw(r){if(ww(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 Oo=xw;var Ye=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Di(r,e,t,n){let o=new Ye(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(){Ku(t,"abort",f),Ku(r,e,l),Ku(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Uu(t,"abort",f),Uu(r,e,l),Uu(r,s,u)})}function Uu(r,e,t){r!=null&&(Vp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Ku(r,e,t){r!=null&&(Vp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Vp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Ri=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ki=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 Ye)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ew(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Oi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ew(),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 Ye),this.cleanup())}async join(e={}){let t=new ki(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 Ge(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 qu(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 No=class extends Ne{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=qu(this.emitEmpty.bind(this),1),this.emitIdle=qu(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 Ri;let n=new Oi(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 Ye)}),this.clear()}async onEmpty(e){this.size!==0&&await Di(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Di(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Di(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 Ye("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 Ni="lock:worker:request-read",Mi="lock:worker:abort-read-request",Bi="lock:worker:release-read",Fi="lock:master:grant-read",Ui="lock:master:error-read",Ki="lock:worker:request-write",qi="lock:worker:abort-write-request",$i="lock:worker:release-write",zi="lock:master:grant-write",Vi="lock:master:error-write",Hi="lock:worker:finalize",Wi="mortice",Hp={singleProcess:!1};var $u=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let b={type:h.data.type,name:h.data.name,identifier:h.data.identifier};b.type===a&&b.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Hi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var Wp=(r=10)=>Math.random().toString().substring(2,r+2);var ji=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Wi)}readLock(e){return this.sendRequest(Ni,Mi,Fi,Ui,Bi,e)}writeLock(e){return this.sendRequest(Ki,qi,zi,Vi,$i,e)}finalize(){this.channel.postMessage({type:Hi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Wp();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var jp=r=>{if(r=Object.assign({},Hp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Wi),n=new Ne;return t.addEventListener("message",$u(n,t,"requestReadLock","abortReadLockRequest",Ni,Mi,Ui,Bi,Fi)),t.addEventListener("message",$u(n,t,"requestWriteLock","abortWriteLockRequest",Ki,qi,Vi,$i,zi)),n}return new ji(r.name)};var Dr=new Map,Mo;function Gp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function vw(r){if(Mo==null&&(Mo=jp(r),!Gp(Mo))){let e=Mo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Dr.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=Dr.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=Dr.get(n);o?.finalize()})}return Mo}async function zu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ye)};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 Yp=(r,e)=>{let t=Dr.get(r);if(t!=null)return t;let n=vw(e);if(Gp(n))return t=n,Dr.set(r,t),t;let o=new No({concurrency:1}),s;return t={async readLock(i){if(s!=null)return zu(s,i);s=new No({concurrency:e.concurrency,autoStart:!1});let a=s,c=zu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,zu(o,i)},finalize:()=>{Dr.delete(r)},queue:o},Dr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Sw={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Vu(r){let e=Object.assign({},Sw,r);return Yp(e.name,e)}var Ot;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,b={})=>{b.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)),b.lengthDelimited!==!1&&h.ldelim()},(d,h,b={})=>{let m={key:"",value:pe(0)},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{m.key=d.string();break}case 2:{m.value=d.bytes();break}default:{d.skipType(y&7);break}}}return m},function*(d,h,b,m={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${b}.key`,value:d.string()};break}case 2:{yield{field:`${b}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Fe(d,a.codec())}a.encode=l;function u(d,h){return Be(d,a.codec(),h)}a.decode=u;function f(d,h){return Ue(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=Ke((d,h,b={})=>{b.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Fo.codec().encode(d.value,h)),b.lengthDelimited!==!1&&h.ldelim()},(d,h,b={})=>{let m={key:""},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{m.key=d.string();break}case 2:{m.value=Fo.codec().decode(d,d.uint32(),{limits:b.limits?.value});break}default:{d.skipType(y&7);break}}}return m},function*(d,h,b,m={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${b}.key`,value:d.string()};break}case 2:{yield*Fo.codec().stream(d,d.uint32(),`${b}.value`,{limits:m.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Fe(d,a.codec())}a.encode=l;function u(d,h){return Be(d,a.codec(),h)}a.decode=u;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),Bo.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[u,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Bo.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new st('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new lo('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new lo('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return u},function*(a,c,l,u={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&f.addresses===u.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let b of Bo.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...b,index:f.addresses};f.addresses++;break}case 2:{if(u.limits?.protocols!=null&&f.protocols===u.limits.protocols)throw new st('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&f.metadata===u.limits.metadata)throw new st('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),f.metadata++;break}case 7:{if(u.limits?.tags!=null&&f.tags===u.limits.tags)throw new st('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Fe(a,r.codec())}r.encode=o;function s(a,c){return Be(a,r.codec(),c)}r.decode=s;function i(a,c){return Ue(a,r.codec(),c)}r.stream=i})(Ot||(Ot={}));var Bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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:pe(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Bo||(Bo={}));var Fo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Fo||(Fo={}));function Aw(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=tn(e.publicKey,t);return kl(n)}function Xp(r,e,t){let n=Ot.decode(e);return _n(r,n,t)}function _n(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:Aw(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Zp(r,e){return _w(r.addresses,e.addresses)&&Iw(r.protocols,e.protocols)&&Cw(r.publicKey,e.publicKey)&&Tw(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Lw(r.metadata,e.metadata)&&Pw(r.tags,e.tags)}function _w(r,e){return Jp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Q(t.multiaddr,n.multiaddr)))}function Iw(r,e){return Jp(r,e,(t,n)=>t===n)}function Cw(r,e){return Qp(r,e)}function Tw(r,e){return Qp(r,e)}function Lw(r,e){return em(r,e,(t,n)=>Q(t,n))}function Pw(r,e){return em(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Qp(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Q(r,e):!1}function Jp(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 em(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 Nt="/",tm=new TextEncoder().encode(Nt),Gi=tm[0],Rr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Gi)throw new Error("Invalid key")}toString(e="utf8"){return q(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Nt))}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=tm),this._buf[0]!==Gi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Gi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Gi;)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(Nt).slice(1)}type(){return Dw(this.baseNamespace())}name(){return Rw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Nt)||(e+=Nt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Nt):new r(e.slice(0,-1).join(Nt))}child(e){return this.toString()===Nt?e:e.toString()===Nt?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(),...kw(e.map(t=>t.namespaces()))])}};function Dw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Rw(r){let e=r.split(":");return e[e.length-1]}function kw(r){return[].concat(...r)}var Hu="/peers/";function Uo(r){if(!Ut(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new Rr(`${Hu}${e}`)}async function rm(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=re(i.multiaddr)),!er(i.multiaddr))throw new C("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(re(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Xi(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new C("publicKey does not match peer id");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new C("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Yi(d,{validate:nm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Yi(d,{validate:om,map:sm})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,b]of d)b==null?a.delete(h):a.set(h,b);a=Yi([...a.entries()],{validate:nm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[b,m]of d)m==null?h.delete(b):h.set(b,m);c=Yi([...h.entries()],{validate:om,map:sm})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=rt(o.id.publicKey):e.publicKey!=null?u=rt(e.publicKey):r.publicKey!=null&&(u=rt(r.publicKey));let f={addresses:await rm(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Q(h.multiaddr,d.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Yi(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 nm(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function om(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function sm(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 im(r){let e=r.toString().split("/")[2],t=xe.parse(e,et);return wo(t)}function Wu(r,e,t){let n=im(r);return Xp(n,e,t)}function Ow(r,e){return{prefix:Hu,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Wu(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Wu(n.key,n.value,e),Wu(o.key,o.value,e)))}}var Zi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Fu({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:Vu({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(Uo(e),t)}async load(e,t){let n=Uo(e),o=await this.datastore.get(n,t),s=Ot.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new nr;return _n(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Xi(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 Xi(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 Xi(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(Ow(e??{},this.maxAddressAge),e)){let o=im(t);if(o.equals(this.peerId))continue;let s=Ot.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield _n(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Uo(e),o=await this.datastore.get(n,t),s=Ot.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new nr;return{peerPB:s,peer:_n(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=Ot.encode(t);return await this.datastore.put(Uo(e),s,o),{peer:_n(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Zp(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 ju=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Zi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Oo(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=Ut(t)?t:Ut(t?.expectedPeer)?t.expectedPeer:void 0,s=Ut(t)||t===void 0?n:t,i=await An.openAndCertify(e,Pr.DOMAIN,s),a=wo(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=Pr.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=An.createFromProtobuf(l.peerRecordEnvelope),f=Pr.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function am(r,e={}){return new ju(r,e)}var Qi=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 Nw(r){return r[Symbol.asyncIterator]!=null}function Mw(r){if(Nw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gu=Mw;function Bw(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 cm=Bw;function Fw(r){return r[Symbol.asyncIterator]!=null}function Uw(r,e){let t=0;if(Fw(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=cm(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 kr=Uw;function Kw(r){return r[Symbol.asyncIterator]!=null}function qw(r,e){return Kw(r)?(async function*(){yield*(await Oo(r)).sort(e)})():(function*(){yield*Oo(r).sort(e)})()}var Yu=qw;function $w(r){return r[Symbol.asyncIterator]!=null}function zw(r,e){return $w(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 Xu=zw;var Ji=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 Gu(this.putMany(e,n)),e=[],await Gu(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=kr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>kr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=kr(n,()=>o++>=s)}return e.limit!=null&&(n=Xu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=kr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>kr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=kr(n,()=>s++>=o)}return e.limit!=null&&(n=Xu(n,e.limit)),n}};var ea=class extends Ji{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 Qi;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 Rr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Rr(n),t?.signal?.throwIfAborted()}};var lm=864e13;var ta=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=ke({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=Y(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=un(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?lm-Date.now():0,lastVerified:o?lm-Date.now():void 0})})}remove(e){let t=Y(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(!Te(o))continue;let s=Y(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}),re(n)}confirm(e,t){let n=Y(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=Y(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 ra=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=ke({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=Y(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:ht(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=Y(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(!Te(n))continue;let o=Y(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,re(i)):e}confirm(e,t){if(!Te(e))return!1;let n=Y(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(!Te(e))return!1;let n=Y(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 Vw={maxObservedAddresses:10},na=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=ke({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Vw.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&&(Pt(e)||op(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:re(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 Hw={maxObservedAddresses:10},oa=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=ke({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Hw.maxObservedAddresses}get(e,t){if(Pt(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:!Te(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(!Te(e))return e.toString();let t=Y(e);return`${t.host}-${t.port}-${t.protocol}`}};var um=6e4,fm={maxObservedAddresses:10,addressVerificationTTL:um*10,addressVerificationRetry:um*5},Ww=r=>r;function Zu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&wt(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var sa=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 na(e,t),this.dnsMappings=new ta(e,t),this.ipMappings=new ra(e,t),this.transportAddresses=new oa(e,t),this.announceFilter=t.announceFilter??Ww,this.observedAddressFilter=vo(1024),this.addressVerificationTTL=t.addressVerificationTTL??fm.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??fm.addressVerificationRetry,this._updatePeerStoreAddresses=Po(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>re(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=Y(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=Zu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Zu(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=Zu(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=re(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(re(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ht(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(re(`/ip${ht(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Te(e))return!1;let t=Y(e);if(t.type!=="ip4"||un(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Ir.exactMatch(s)||To.exactMatch(s),s=>Co.exactMatch(s),s=>Ip.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>Y(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Ao(l)).pop();if(a==null)continue;let c=Y(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 dm;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(dm||(dm={}));var ia=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},aa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},In=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ko=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ca=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},la=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ua=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},qo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},fa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},da=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ha=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},pa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ma=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},tr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Or=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ga=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},ya=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Qu=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=Ws())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>ss(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")}},jw=["metrics","connectionProtector","dns"],Gw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function hm(r={}){let e=new Qu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Gw.includes(o)){let i=e.components[o];if(i==null&&!jw.includes(o))throw new ia(`${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 pm(r){let e={};for(let t of Object.values(r.components))for(let n of Yw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Xw(t))if(e[n]!==!0)throw new aa(`Service "${Zw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Yw(r){return Array.isArray(r?.[Mn])?r[Mn]:[]}function Xw(r){return Array.isArray(r?.[Xa])?r[Xa]:[]}function Zw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function mm(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Ir.matches(e)?!0:Pt(e)),r}var oe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ba(r){if(Ut(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:wt(n),e.forEach(o=>{if(!er(o))throw new Bt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=wt(s);if(t?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Sp.exactMatch(n)),{peerId:t,multiaddrs:e}}var Qw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function gm(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Qw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function $o(r){let e=Y(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new sn(e.host,t)}function Ju(r){return!Cr.exactMatch(r)}function wa(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Ju(s)))return n}var xa=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>$o(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 it;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Te(c.remoteAddr)){let f=Y(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await gm(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 ym="last-dial-failure",bm="last-dial-success";var wm=100,Ea=50;function Jw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function xm(r){return r.sort((e,t)=>Rp(e.multiaddr,t.multiaddr)||kp(e.multiaddr,t.multiaddr)||Op(e.multiaddr,t.multiaddr)||Jw(e,t)||Dp(e.multiaddr,t.multiaddr))}var va=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},Sa=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var tf=Va(vm(),1);function rf(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 rx=100,Cn=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=rf(this.#e,i,(c,l)=>l.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>rx&&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 Vo=class extends tf.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#l;#x=0;#c;#u;#a;#i=[];#s=0;#r;#I;#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:Cn,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#l=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#I=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#l)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#k(e){this.#a?this.#i.push(e):this.#n++}#O(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#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")}#F(){this.#u=void 0,this.#P(),this.#L()}#U(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#l-(e-n);return this.#C(o),!0}return!1}if(this.#c===void 0){let t=this.#x-e;if(t<0)this.#n=this.#e?this.#o:0;else return this.#C(t),!0}return!1}#C(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#F()},e))}#A(){this.#c&&(clearInterval(this.#c),this.#c=void 0)}#T(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#T(),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.#U(t);if(this.#N&&this.#M){let o=this.#r.dequeue();this.#t||(this.#k(t),this.#p()),n&&this.#L(),o(),this.emit("active"),e=!0}}return e}#L(){this.#t||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#P()},this.#l),this.#x=Date.now()+this.#l)}#P(){this.#a||(this.#c!==void 0&&(this.#n===0&&this.#o===0?this.#A():this.#x=Date.now()+this.#l),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){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.#_()}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={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#y.delete(s),d}let u=e({signal:t.signal});if(t.timeout!==void 0&&(u=Lo(Promise.resolve(u),{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;u=Promise.race([u,new Promise((h,b)=>{l=()=>{b(d.reason)},d.addEventListener("abort",l,{once:!0}),d.aborted&&l()})])}let f=await u;n(f),this.emit("completed",f)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof Cn){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#_(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#I,this.#A(),this.#D(),this.emit("empty"),this.#o===0&&(this.#T(),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","active"],()=>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){let n=Array.isArray(e)?e:[e];return new Promise(o=>{let s=()=>{if(!(t&&!t())){for(let i of n)this.off(i,s);o()}};for(let i of n)this.on(i,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#K(){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.#D()}))}#q(){this.#t||(this.#O(),this.#p())}#D(){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 _a(r){let e=[Xe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var nf=60;function Ia(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:Xe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Xe[e.type],TTL:e.TTL??e.ttl??nf,data:e.data instanceof Uint8Array?q(e.data):e.data}))}}var nx=4;function of(r,e={}){let t=new Vo({concurrency:e.queryConcurrency??nx});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),_a(o.types).forEach(c=>{i.append("type",Xe[c])}),o.onProgress?.(new oe("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Ia(await c.json());return o.onProgress?.(new oe("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function Sm(){return[of("https://cloudflare-dns.com/dns-query"),of("https://dns.google/resolve")]}var Im=Va(_m(),1);var sf=class{lru;constructor(e){this.lru=(0,Im.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 Ia({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:Xe[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??nf)*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 Cm(r){return new sf(r)}var ox=1e3,sx=()=>Math.random()>.5?-1:1,Ca=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=Cm(e.cacheSize??ox),this.logger=e.logger,this.sorter=e.sorter??sx,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["."]=Sm())}async query(e,t={}){let n=_a(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new oe("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});if(l.Answer.length===0)throw new Sa("Query result had no answers");for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new oe("dns:error",l))}}throw new va(a,`DNS lookup of ${e} ${n} failed`)}};var Xe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Xe||(Xe={}));function Tm(r={}){return new Ca(r)}var af=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 o=this.getDNS(t),s;try{s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Xe.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(u=>u.name==="EmptyDNSAnswerError"))return[];throw c}let i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(re(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Tm()),this.dns)}},Nr=new af;async function cf(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new ya("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 cf(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Tn={maxParallelDials:Ea,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Nr}},Ta=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Tn.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Tn.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Tn.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Tn.addressDialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Tn.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ti({concurrency:t.maxParallelDials??Tn.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}=ba(e);if(n!=null&&t.force!==!0){let i=wa(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new oe("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 oe("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Br("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new oe("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new oe("dial-queue:start-dial"));let a=Et([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??hf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new oe("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Br("Peer had more than maxPeerAddrsToDial");a++;let b=Et([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let m=await this.components.transportManager.dial(h.multiaddr,{...e,signal:b});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[bm]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return m}catch(m){if(this.log.error("dial failed to %a - %e",h.multiaddr,m),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[ym]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new es(m.message);l.push(m)}finally{b.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:re(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Br("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new qo("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 cf(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 ha(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?xm(l):l.sort(this.addressSorter);if(u.length===0)throw new qo(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Cr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var ix=Object.prototype.toString,ax=r=>ix.call(r)==="[object Error]",cx=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 pf(r){if(!(r&&ax(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:cx.has(t)}function lx(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function La(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 mf(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var gf=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 ux(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 Pa(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function fx(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 dx({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 gf)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=ux(t,o);if(Pa(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(u),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Pa(n,a)<=0||Pa(n,a)<=0||i<=0||s instanceof TypeError&&!pf(s)||!await o.shouldRetry(h))throw s;let m=Pa(n,a);if(m<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let g=Math.min(d,m);return o.signal?.throwIfAborted(),await fx(g,o),o.signal?.throwIfAborted(),!0}async function yf(r,e={}){if(e={...e},lx(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,mf("onFailedAttempt",e.onFailedAttempt),mf("shouldRetry",e.shouldRetry),mf("shouldConsumeRetry",e.shouldConsumeRetry),La("factor",e.factor,{min:0,allowInfinity:!1}),La("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),La("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),La("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 dx({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Da=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 Ci({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);Lm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await yf(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(Ga)&&(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=>Lm(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 Lm(r){for(let e of r.tags.keys())if(e.startsWith(Ga))return!0;return!1}var hf=50,bf={maxConnections:wm,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ra=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??bf.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new it,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=>$o(re(n))),this.deny=(t.deny??[]).map(n=>$o(re(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??bf.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Li({points:t.inboundConnectionThreshold??bf.inboundConnectionThreshold,duration:1}),this.connectionPruner=new xa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>re(n))}),this.dialQueue=new Ta(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ea,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Nr},connections:this.connections}),this.reconnectQueue=new Da({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 Cf(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 Tf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([pt(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 C("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new St("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new oe("connection:open",e));let{peerId:n,multiaddrs:o}=ba(e);if(this.peerId.equals(n))throw new Mr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=wa(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 oe("dial-queue:already-connected")),t.onProgress?.(new oe("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??hf});if(s.status!=="open")throw new rr("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 oe("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([pt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Te(e.remoteAddr)){let s=Y(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(Te(e.remoteAddr)){let s=Y(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(Te(e.remoteAddr)){let o=Y(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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var mx=1e4,gx="1.0.0",yx="ping",bx="ipfs",Pm=32,wx=!0,ka=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??bx}/${yx}/${gx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??mx,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??wx,this.timeout=new bi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Mn]=["@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=Ru(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(Pm)),{signal:n}),s.read({bytes:Pm,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 Oa=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:q(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:q(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 In("No content routers available");let n=this,o=new br;for await(let s of vn(...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 In("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 In("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 St;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 St;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Na=globalThis.CustomEvent??Event;async function*wf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Ie(),a=Ie(),c=!1,l,u=!1,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(s.length===t&&(i=Ie(),await i.promise),u||f)break;let g={done:!1};s.push(g),m().then(y=>{g.done=!0,g.ok=!0,g.value=y,o.dispatchEvent(new Na("task-complete"))},y=>{g.done=!0,g.err=y,o.dispatchEvent(new Na("task-complete"))})}c=!0,o.dispatchEvent(new Na("task-complete"))}catch(m){l=m,o.dispatchEvent(new Na("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(m=>m.done)}function*h(){for(;s.length>0&&s[0].done;){let m=s[0];if(s.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*b(){for(;d();)for(let m=0;m<s.length;m++)if(s[m].done){let g=s[m];if(s.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}try{for(;;){if(d()||(a=Ie(),await a.promise),l!=null||(n?yield*h():yield*b(),l!=null))throw l;if(c&&s.length===0)break}}finally{f=!0,i.resolve()}}var Ma=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:q(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 Ko("No peer routers available");if(e.toString()===this.peerId.toString())throw new ca("Should not try to find self");let n=this,o=vn(...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 nr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ko("No peer routers available");let n=this,o=vo(1024);for await(let s of wf((async function*(){let i=vn(...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 Ba=class extends Ne{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=Et([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ie(),yield(await pt(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=Et([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=crypto.getRandomValues(new Uint8Array(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 Ge(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 xf=32,Ef=64,Fa=class{log;topologies;handlers;components;middleware;globalMiddleware=[];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=ke({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 la(`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 ua(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:xf,maxOutboundStreams:Ef,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new C("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){if(typeof e=="function"){this.globalMiddleware.push(e);return}if(t==null)throw new C("Protocol middleware is required");this.middleware.set(e,t)}unuse(e){typeof e=="function"?this.globalMiddleware=this.globalMiddleware.filter(t=>t!==e):this.middleware.delete(e)}getMiddleware(e){return[...this.globalMiddleware,...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 Ua=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=ke({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=ke({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Nn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ga(`No transport available for address ${String(e)}`);return t?.onProgress?.(new oe("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 St("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 fa)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),bu.matches(c)?t.ipv4.attempts++:wu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),bu.matches(c)&&t.ipv4.success++,wu.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===Nn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new da(`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 Wh(r,e)}We.formatters.e=r=>r==null?"undefined":jh(r);function nb(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 Ws(r){return{forComponent(e){return Yh(e,r)}}}function Yh(r,e){let t=nb(`${r}:trace`);return We.enabled(`${r}:trace`)&&We.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=We(`${r}:trace`,e)),Object.assign(We(r,e),{error:We(`${r}:error`,e),trace:t,newScope:n=>Yh(`${r}:${n}`,e)})}function Gh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function yr(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 Gs(r){let e=_t(se.decode(`z${r}`));return tn(e)}var it=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 yr(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 yr(this.map.values(),e=>e.key)}values(){return yr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=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 yr(this.set.entries(),e=>{let t=Gs(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Gs(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return yr(this.set.values(),e=>Gs(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 Nu={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Zh=new globalThis.TextEncoder;function ob(r,e){let t=Nu[e],n=Xh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function sb(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Nu[e],o=Xh[e],s=r;for(;s.length>0;){let i=Zh.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 Mu(r,{size:e=32,utf8Buffer:t}={}){if(!Nu[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 sb(r,e,t);r=Zh.encode(r)}return ob(r,e)}var xo={hash:r=>Number(Mu(r,{size:32})),hashV:(r,e)=>ib(xo.hash(r,e))};function ib(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var Bu=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Bu)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pe(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?X(this.fp,e.fp):!1}};function wr(r,e){return Math.floor(Math.random()*(e-r))+r}var xr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=wr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var ab=500,Eo=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??xo,this.seed=e.seed??wr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new dt(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 xr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[wr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xr(this.bucketSize));for(let a=0;a<ab;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 xr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new dt(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=T(e));let t=new dt(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}},cb={1:.5,2:.84,4:.95,8:.98};function ub(r=.001){return r>.002?2:r>1e-5?4:8}function Qh(r,e=.001){let t=ub(e),n=cb[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Bu);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var js=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??xo,this.seed=e.seed??wr(0,Math.pow(2,10)),this.filterSeries=[new Eo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Eo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function vo(r,e=.001,t){return new js({...Qh(r,e),...t??{}})}function Fu(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 Y(r){let e=Fu(r);if(e==null)throw new I(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Ys=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 Jh=45,lb=15,rn=new Ys;function Xs(r){if(!(r.length>lb))return rn.new(r).parseWith(()=>rn.readIPv4Addr())}function Zs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return rn.new(r).parseWith(()=>rn.readIPv6Addr())}function nn(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Jh)return;let t=rn.new(r).parseWith(()=>rn.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 ep(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 tp(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 Uu(r){switch(r.length){case Er:return r.join(".");case vr:{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 rp(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 np(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Er=4,vr=16,ZA=parseInt("0xFFFF",16),fb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function So(r,e){e.length===vr&&r.length===Er&&ep(e,0,11)&&(e=e.slice(12)),e.length===Er&&r.length===vr&&tp(r,fb,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 op(r,e){if(typeof e=="string"&&(e=nn(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 Ku(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Er,o=Xs(e);if(o==null&&(n=vr,o=Zs(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=qu(s,8*n);return{network:So(o,i),mask:i}}function qu(r,e){if(e!==8*Er&&e!==8*vr)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 on=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Ku(e));else{let n=nn(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=nn(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=qu(o,8*n.length);this.network=So(n,this.mask)}}contains(e){return op({network:this.network,mask:this.mask},e)}toString(){let e=rp(this.mask),t=e!==-1?String(e):np(this.mask);return Uu(this.network)+"/"+t}};function sp(r){try{let e=Y(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 ip(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let o=n.split(".");return o.length===4&&o[0]==="127"&&o.every(s=>/^\d{1,3}$/.test(s))}function Ao(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return ip(e.host);default:return!1}}catch{return!1}}function Te(r){return Fu(r)!==null}function ht(r){return!!Xs(r)}function Qs(r){return!!Zs(r)}var lp=Va(up(),1),bb=["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"],wb=bb.map(r=>new lp.Netmask(r));function ju(r){for(let e of wb)if(e.contains(r))return!0;return!1}function xb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Eb(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 ju(o)}function vb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Sb(r){let e=r.split(":"),t=e[e.length-1];return ju(t)}function Ab(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 un(r){if(ht(r))return ju(r);if(xb(r))return Eb(r);if(vb(r))return Sb(r);if(Qs(r))return Ab(r)}function Dt(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return un(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var Le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Rt=class extends Error{static name="ValidationError";name="ValidationError"},ei=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ti=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Xu(r){return e=>q(e,r)}function Zu(r){return e=>T(e,r)}function ln(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ar(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function fp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ar(n);return tt([t,o],t.length+o.length)}function dp(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=Ar(n);return tt([t,o],t.length+o.length)}function Qu(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=q(e,"base32"),o=ln(t);return`${n}:${o}`}var Ju=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 Le("Invalid byte value in IP address");e[n]=o}),e},hp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ht(t[n]),i;s&&(i=Ju(t[n]),t[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,q(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 Le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},pp=function(r){if(r.byteLength!==4)throw new Le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},mp=function(r){if(r.byteLength!==16)throw new Le("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 Le(`Invalid IPv6 address "${t}"`)}};function gp(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${r}"`)}}var Yu=Object.values(Kn).map(r=>r.decoder),_b=(function(){let r=Yu[0].or(Yu[1]);return Yu.slice(2).forEach(e=>r=r.or(e)),r})();function yp(r){return _b.decode(r)}function bp(r){return e=>r.encoder.encode(e)}function Cb(r){if(parseInt(r).toString()!==r)throw new Rt("Value must be an integer")}function Ib(r){if(r<0)throw new Rt("Value must be a positive integer, or zero")}function Tb(r){return e=>{if(e>r)throw new Rt(`Value must be smaller than or equal to ${r}`)}}function Lb(...r){return e=>{for(let t of r)t(e)}}var _o=Lb(Cb,Ib,Tb(65535));var _e=-1,el=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 ti(`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)}))}},Ot=new el,zb=[{code:4,name:"ip4",size:32,valueToBytes:Ju,bytesToValue:pp,validate:r=>{if(!ht(r))throw new Rt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ar,bytesToValue:ln,validate:_o},{code:273,name:"udp",size:16,valueToBytes:Ar,bytesToValue:ln,validate:_o},{code:33,name:"dccp",size:16,valueToBytes:Ar,bytesToValue:ln,validate:_o},{code:41,name:"ip6",size:128,valueToBytes:hp,bytesToValue:mp,stringToValue:gp,validate:r=>{if(!Qs(r))throw new Rt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:_e},{code:43,name:"ipcidr",size:8,bytesToValue:Xu("base10"),valueToBytes:Zu("base10")},{code:53,name:"dns",size:_e},{code:54,name:"dns4",size:_e},{code:55,name:"dns6",size:_e},{code:56,name:"dnsaddr",size:_e},{code:132,name:"sctp",size:16,valueToBytes:Ar,bytesToValue:ln,validate:_o},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:_e,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:_e,bytesToValue:Xu("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Zu("base58btc")(r):xe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Qu,valueToBytes:fp},{code:445,name:"onion3",size:296,bytesToValue:Qu,valueToBytes:dp},{code:446,name:"garlic64",size:_e},{code:447,name:"garlic32",size:_e},{code:448,name:"tls"},{code:449,name:"sni",size:_e},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:_e,bytesToValue:bp(hc),valueToBytes:yp},{code:480,name:"http"},{code:481,name:"http-path",size:_e,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:_e}];zb.forEach(r=>{Ot.addProtocol(r)});function wp(r){let e=[],t=0;for(;t<r.length;){let n=dr(r,t),o=Ot.getProtocol(n),s=Ae(n),i=Vb(o,r,t+s),a=0;i>0&&o.size===_e&&(a=Ae(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ie(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??q(f)}e.push(u),t+=c}return e}function xp(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===_e&&(c=Ae(a)));let u=new Uint8Array(s+c+a),l=0;Jr(n.code,u,l),l+=s,i!=null&&(o.size===_e&&(Jr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function Ep(r){if(r.charAt(0)!=="/")throw new Le('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=Ot.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 Le(`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 Le(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Le("Incomplete multiaddr");return e}function vp(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ot.getProtocol(e.code);if(t==null)throw new Le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Vb(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:dr(e,t)}var Hb=Symbol.for("nodejs.util.inspect.custom"),pl=Symbol.for("@multiformats/multiaddr");function Wb(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return wp(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Ep(r);if(Array.isArray(r))return r;throw new Le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ai=class r{[pl]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=Wb(e),t.validate!==!1&&Gb(this)}get bytes(){return this.#n==null&&(this.#n=xp(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=vp(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 ei(`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 X(this.bytes,e.bytes)}[Hb](){return`Multiaddr(${this.toString()})`}};function Gb(r){r.getComponents().forEach(e=>{let t=Ot.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function er(r){return!!r?.[pl]}function re(r){return new ai(r)}var ae=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),k=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Sp=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Re=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ce(...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 jb=k(421),Ap=ce(jb),ui=k(54),li=k(55),fi=k(56),gl=k(53),BC=ce(ui,H(k(421))),FC=ce(li,H(k(421))),UC=ce(fi,H(k(421))),KC=ce(Re(gl,fi,ui,li),H(k(421))),_p=Z(k(4),H(k(43))),Cp=Z(H(k(42)),k(41),H(k(43))),yl=Re(_p,Cp),gn=Re(yl,gl,ui,li,fi),qC=ce(Re(yl,Z(Re(gl,fi,ui,li),H(k(421))))),bl=ce(_p),wl=ce(Cp),$C=ce(yl),xl=Z(gn,k(6)),Co=Z(gn,k(273)),Io=ce(Z(xl,H(k(421)))),zC=ce(Co),El=Z(Co,ae(460),H(k(421))),di=Z(Co,ae(461),H(k(421))),Yb=Re(El,di),VC=ce(El),Ip=ce(di),ml=Re(gn,xl,Co,El,di),Tp=Re(Z(ml,ae(477),H(k(421)))),Cr=ce(Tp),Lp=Re(Z(ml,ae(478),H(k(421))),Z(ml,ae(448),H(k(449)),ae(477),H(k(421)))),To=ce(Lp),Pp=Z(Co,ae(280),H(k(466)),H(k(466)),H(k(421))),vl=ce(Pp),Dp=Z(di,ae(465),H(k(466)),H(k(466)),H(k(421))),Sl=ce(Dp),ci=Re(Tp,Lp,Z(xl,H(k(421))),Z(Yb,H(k(421))),Z(gn,H(k(421))),Pp,Dp,k(421)),HC=ce(ci),Xb=Z(H(ci),ae(290),Sp(ae(281)),H(k(421))),Ir=ce(Xb),Zb=Re(Z(ci,ae(290),ae(281),H(k(421))),Z(ci,ae(281),H(k(421))),Z(ae(281),H(k(421)))),Al=ce(Zb),Qb=Z(gn,Re(Z(k(6,"80")),Z(k(6),ae(480)),ae(480)),H(k(481)),H(k(421))),WC=ce(Qb),Jb=Z(gn,Re(Z(k(6,"443")),Z(k(6,"443"),ae(480)),Z(k(6),ae(443)),Z(k(6),ae(448),ae(480)),Z(ae(448),ae(480)),ae(448),ae(443)),H(k(481)),H(k(421))),GC=ce(Jb),ew=Re(Z(k(777),H(k(421)))),jC=ce(ew),tw=Re(Z(k(400),H(k(421)))),YC=ce(tw);function Rp(r,e){let t=Io.exactMatch(r),n=Io.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=To.exactMatch(r),s=To.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=Cr.exactMatch(r),a=Cr.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=Al.exactMatch(r),u=Al.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=vl.exactMatch(r),f=vl.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=Sl.exactMatch(r),h=Sl.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function kp(r,e){let t=Ao(r),n=Ao(e);return t&&!n?1:!t&&n?-1:0}function Op(r,e){let t=Dt(r),n=Dt(e);return t&&!n?1:!t&&n?-1:0}function Np(r,e){let t=Ir.exactMatch(r),n=Ir.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var hi=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}},yn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hi(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 hi(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 _l=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function bn(r={}){return rw(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 rw(r,e){e=e??{};let t=e.onEnd,n=new yn,o,s,i,a=Ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=S=>{s=null,n.push(S);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ce()})}},u=g=>s!=null?s(g):(n.push(g),o),l=g=>(n=new yn,s!=null?s({error:g}):(n.push({error:g}),o)),f=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?l(g):u({done:!0})),h=()=>(n=new yn,d(),{done:!0}),b=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:b,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let S,w;y!=null&&(S=new Promise((v,A)=>{w=()=>{A(new _l)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,S])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Cl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Mp=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,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(Mp(i)),r.then(f,d);return}if(i&&(c=()=>{d(Mp(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Cl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(b){d(b)}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 Bp=r=>typeof r=="function"?{filter:r}:{...r},nw=r=>r===1/0||Number.isSafeInteger(r)&&r>=0,ow=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],sw=r=>{for(let[e,t]of ow){let n=r?.[e],o=r?.[t];if(typeof n=="function"&&typeof o=="function")return{addListener:n.bind(r),removeListener:o.bind(r)}}throw new TypeError("Emitter is not compatible")},iw=r=>{let e=new Map;for(let[t,n]of r)for(let o of Array.isArray(t)?t:[t])e.has(o)||e.set(o,n);return e},aw=({addListener:r,removeListener:e,handlers:t,signal:n,abortHandler:o,isDone:s})=>{n?.addEventListener("abort",o,{once:!0});for(let[i,a]of t)if(r(i,a),s()){e(i,a);return}},cw=({removeListener:r,handlers:e,signal:t,abortHandler:n})=>{for(let[o,s]of e)r(o,s);t?.removeEventListener("abort",n)},uw=(r,e,t)=>{let n=Promise.resolve();return(o,s)=>{n=n.then(async()=>{if(e())return;let i;try{i=r?await r(o):!0}catch(a){e()||t(a);return}e()||s(i)})}};function lw(r,e,t){let n=()=>{},o=!1,s,i=new Promise((a,c)=>{t=Bp(t);let{filter:u}=t;if(!nw(t.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof t.timeout=="number"&&!(t.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${t.timeout}\``);t.signal?.throwIfAborted();let{addListener:l,removeListener:f}=sw(r);if(t.count===0){a([]);return}let d=[],h=v=>{n(),c(v)},b=uw(u,()=>o,h),m=v=>{d.push(v),t.count===d.length&&(n(),a(d))},g=(...v)=>{if(o)return;let A=t.multiArgs?v:v[0];if(!u){m(A);return}b(A,M=>{M&&m(A)})},y=(...v)=>{h(t.rejectionMultiArgs?v:v[0])},S=()=>{h(t.signal.reason)},w={addListener:l,removeListener:f,handlers:iw([[e,g],[t.rejectionEvents??["error"],y]]),signal:t.signal,abortHandler:S,isDone:()=>o};n=()=>{o=!0,clearTimeout(s),cw(w)},aw(w),!(o||!t.resolveImmediately)&&(Number.isFinite(t.timeout)&&(s=setTimeout(n,t.timeout)),a(d))});if(i.cancel=n,typeof t.timeout=="number"&&t.timeout>0&&!t.resolveImmediately){let a=Lo(i,{milliseconds:t.timeout});return a.cancel=()=>{n(),a.clear()},a}return i}function pt(r,e,t){let n=lw(r,e,{...Bp(t),count:1,resolveImmediately:!1}),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Po(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var pi=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}},mi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Tr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function fw(r){return r.reason}function je(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??fw;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var gi=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ce(),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 dw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Fp=new WeakMap,yi=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=dw(),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 gi(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 je(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Fp.get(t);if(n==null&&(n=new WeakSet,Fp.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.deferred.reject(e.signal?.reason??new Qe),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var wn=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Po(this.emitEmpty.bind(this),1),this.emitIdle=Po(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new mi;let n=new yi(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 pt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pt(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=bn({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 vt(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var xn=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 hw=1.2,pw=2,mw=5e3,gw=6e4,yw=5e3,bi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??yw;this.success=new xn(t),this.failure=new xn(t),this.next=new xn(t),this.failureMultiplier=e.failureMultiplier??pw,this.timeoutMultiplier=e.timeoutMultiplier??hw,this.minTimeout=e.minTimeout??mw,this.maxTimeout=e.maxTimeout??gw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=vt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){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 Il=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ce(),this.haveNext=Ce()}[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=Ce(),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=Ce(),await je(this.readNext.promise,t?.signal,t)}};function Up(){return new Il}function Kp(r){return r[Symbol.asyncIterator]!=null}async function bw(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;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*ww(r){let e=new AbortController,t=Up(),n=r.map(o=>Kp(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());bw(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*xw(r){for(let e of r)yield*e}function Ew(...r){let e=[];for(let t of r)Kp(t)||e.push(t);return e.length===r.length?xw(e):ww(r)}var En=Ew;var vw=4194304,wi=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ll=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Dl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Sw(r){return typeof r?.closeRead=="function"}function Aw(r){return typeof r?.close=="function"}function Tl(r){return Sw(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Aw(r)?r.status!=="open":!1}function _w(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Rl(r,e){let t=e?.maxBufferSize??vw,n=new ne,o,s=!1,i;if(!_w(r))throw new I("Argument should be a Stream or a Multiaddr");let a=f=>{if(!s&&i==null){if(n.append(f.data),n.byteLength>t){let d=n.byteLength;n.consume(d);let h=new Yo(`Read buffer overflow - ${d} > ${t}`);i=h,o?.reject(h),queueMicrotask(()=>{r.abort(h)});return}o?.resolve()}};r.addEventListener("message",a);let c=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",c);let u=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",u);let l={readBuffer:n,async read(f){if(s===!0)throw new wi("Stream was unwrapped");if(i!=null)throw i;if(Tl(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new Tr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let d=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await je(o.promise,f?.signal),Tl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let h=f?.bytes??n.byteLength;if(n.byteLength<h){if(Tl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Tr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(f)}let b=n.sublist(0,h);return n.consume(h),b},async write(f,d){if(s===!0)throw new wi("Stream was unwrapped");r.send(f)||await pt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n),n.consume(n.byteLength))),r}};return l}function xi(r,e={}){let t=Rl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??dr,o=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new ne;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 Ll("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Dl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Pl(`Message length too long - ${a} > ${e.maxDataLength}`);let 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 Tr(`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 Tr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){let c=new ne(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Ei=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},vn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},vi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Si(r){return r[Symbol.asyncIterator]!=null}function qp(r,e){if(r.byteLength>e)throw new vn("Message length too long")}var _i=r=>{let e=Ae(r),t=Se(e);return Xt(r,t),_i.bytes=e,t};_i.bytes=0;function Ci(r,e){e=e??{};let t=e.lengthEncoder??_i,n=e?.maxDataLength??4194304;function*o(s){qp(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Si(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ci.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??_i,n=e?.maxDataLength??4194304;return qp(r,n),new ne(t(r.byteLength),r)};var Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Ol=r=>{let e=dr(r);return Ol.bytes=Ae(e),e};Ol.bytes=0;function kl(r,e){let t=new ne,n=Lr.LENGTH,o=-1,s=e?.lengthDecoder??Ol,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(t),o<0)throw new Ei("Invalid message length");if(o>a)throw new vn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Lr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new vi("Message length length too long");break}throw u}if(n===Lr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Lr.LENGTH}}}return Si(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})()}kl.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return kl(n,{...e??{},onLength:s=>{t=s}})};var Ii=class extends wn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ti=class extends wn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Li=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Nl}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new pi("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Nl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Ml=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ke(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ml({name:e,metrics:t}):n=new Map,n}var Bl=class extends it{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Bl({name:e,metrics:t}):n=new it,n}var Ro;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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:pe(0),payloadType:pe(0),payload:pe(0),signature:pe(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 Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Ro||(Ro={}));var Pi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Sn=class r{static createFromProtobuf=e=>{let t=Ro.decode(e),n=ho(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=$p(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 Pi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({publicKey:rt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:X(this.marshal(),e.marshal())}async validate(e,t){let n=$p(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},$p=(r,e,t)=>{let n=T(r),o=Xt(n.byteLength),s=Xt(e.length),i=Xt(t.length);return new ne(o,n,s,e,i,t)};var zp="libp2p-peer-record",Vp=Uint8Array.from([3,1]);var ko;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ke((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 b={multiaddr:pe(0)},m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();g>>>3===1?b.multiaddr=f.bytes():f.skipType(g&7)}return b},function*(f,d,h,b={}){let m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(g&7)}})),a);function c(f){return Fe(f,i.codec())}i.encode=c;function u(f,d){return Be(f,i.codec(),d)}i.decode=u;function l(f,d){return Ue(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((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:pe(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 st('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 st('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 Fe(i,r.codec())}r.encode=n;function o(i,a){return Be(i,r.codec(),a)}r.decode=o;function s(i,a){return Ue(i,r.codec(),a)}r.stream=s})(ko||(ko={}));function Hp(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 Pr=class r{static createFromProtobuf=e=>{let t=ko.decode(e),n=tn(_t(t.peerId)),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=zp;static CODEC=Vp;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=ko.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||!Hp(this.multiaddrs,e.multiaddrs))}};function Iw(r){return r[Symbol.asyncIterator]!=null}function Tw(r){if(Iw(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 Oo=Tw;var Ye=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Di(r,e,t,n){let o=new Ye(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Kl(t,"abort",f),Kl(r,e,u),Kl(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)};Ul(t,"abort",f),Ul(r,e,u),Ul(r,s,l)})}function Ul(r,e,t){r!=null&&(Wp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Kl(r,e,t){r!=null&&(Wp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Wp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Ri=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ki=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 Ye)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Lw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Oi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Lw(),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 Ye),this.cleanup())}async join(e={}){let t=new ki(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 je(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function ql(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var No=class extends Ne{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=ql(this.emitEmpty.bind(this),1),this.emitIdle=ql(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ri;let n=new Oi(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 Ye)}),this.clear()}async onEmpty(e){this.size!==0&&await Di(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Di(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Di(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=bn({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 Ye("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 Ni="lock:worker:request-read",Mi="lock:worker:abort-read-request",Bi="lock:worker:release-read",Fi="lock:master:grant-read",Ui="lock:master:error-read",Ki="lock:worker:request-write",qi="lock:worker:abort-write-request",$i="lock:worker:release-write",zi="lock:master:grant-write",Vi="lock:master:error-write",Hi="lock:worker:finalize",Wi="mortice",Gp={singleProcess:!1};var $l=(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 b={type:h.data.type,name:h.data.name,identifier:h.data.identifier};b.type===a&&b.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===Hi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var jp=(r=10)=>Math.random().toString().substring(2,r+2);var Gi=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Wi)}readLock(e){return this.sendRequest(Ni,Mi,Fi,Ui,Bi,e)}writeLock(e){return this.sendRequest(Ki,qi,zi,Vi,$i,e)}finalize(){this.channel.postMessage({type:Hi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=jp();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 Yp=r=>{if(r=Object.assign({},Gp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Wi),n=new Ne;return t.addEventListener("message",$l(n,t,"requestReadLock","abortReadLockRequest",Ni,Mi,Ui,Bi,Fi)),t.addEventListener("message",$l(n,t,"requestWriteLock","abortWriteLockRequest",Ki,qi,Vi,$i,zi)),n}return new Gi(r.name)};var Dr=new Map,Mo;function Xp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Pw(r){if(Mo==null&&(Mo=Yp(r),!Xp(Mo))){let e=Mo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Dr.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=Dr.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=Dr.get(n);o?.finalize()})}return Mo}async function zl(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ye)};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 Zp=(r,e)=>{let t=Dr.get(r);if(t!=null)return t;let n=Pw(e);if(Xp(n))return t=n,Dr.set(r,t),t;let o=new No({concurrency:1}),s;return t={async readLock(i){if(s!=null)return zl(s,i);s=new No({concurrency:e.concurrency,autoStart:!1});let a=s,c=zl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,zl(o,i)},finalize:()=>{Dr.delete(r)},queue:o},Dr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Dw={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Vl(r){let e=Object.assign({},Dw,r);return Zp(e.name,e)}var Nt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,b={})=>{b.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)),b.lengthDelimited!==!1&&h.ldelim()},(d,h,b={})=>{let m={key:"",value:pe(0)},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{m.key=d.string();break}case 2:{m.value=d.bytes();break}default:{d.skipType(y&7);break}}}return m},function*(d,h,b,m={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${b}.key`,value:d.string()};break}case 2:{yield{field:`${b}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(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=Ke((d,h,b={})=>{b.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Fo.codec().encode(d.value,h)),b.lengthDelimited!==!1&&h.ldelim()},(d,h,b={})=>{let m={key:""},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{m.key=d.string();break}case 2:{m.value=Fo.codec().decode(d,d.uint32(),{limits:b.limits?.value});break}default:{d.skipType(y&7);break}}}return m},function*(d,h,b,m={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${b}.key`,value:d.string()};break}case 2:{yield*Fo.codec().stream(d,d.uint32(),`${b}.value`,{limits:m.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((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),Bo.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 st('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Bo.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 st('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 co('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 co('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 st('Streaming decode error - repeated field "addresses" had too many elements');for(let b of Bo.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...b,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new st('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 st('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 st('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 Fe(a,r.codec())}r.encode=o;function s(a,c){return Be(a,r.codec(),c)}r.decode=s;function i(a,c){return Ue(a,r.codec(),c)}r.stream=i})(Nt||(Nt={}));var Bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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:pe(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 Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Bo||(Bo={}));var Fo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((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 Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Fo||(Fo={}));function Rw(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=ho(e.publicKey,t);return wo(n)}function Qp(r,e,t){let n=Nt.decode(e);return An(r,n,t)}function An(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:Rw(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Jp(r,e){return kw(r.addresses,e.addresses)&&Ow(r.protocols,e.protocols)&&Nw(r.publicKey,e.publicKey)&&Mw(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Bw(r.metadata,e.metadata)&&Fw(r.tags,e.tags)}function kw(r,e){return tm(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!X(t.multiaddr,n.multiaddr)))}function Ow(r,e){return tm(r,e,(t,n)=>t===n)}function Nw(r,e){return em(r,e)}function Mw(r,e){return em(r,e)}function Bw(r,e){return rm(r,e,(t,n)=>X(t,n))}function Fw(r,e){return rm(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function em(r,e){return r==null&&e==null?!0:r!=null&&e!=null?X(r,e):!1}function tm(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 rm(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 Mt="/",nm=new TextEncoder().encode(Mt),ji=nm[0],Rr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ji)throw new Error("Invalid key")}toString(e="utf8"){return q(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mt))}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=nm),this._buf[0]!==ji){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ji,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ji;)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(Mt).slice(1)}type(){return Uw(this.baseNamespace())}name(){return Kw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mt)||(e+=Mt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mt):new r(e.slice(0,-1).join(Mt))}child(e){return this.toString()===Mt?e:e.toString()===Mt?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(),...qw(e.map(t=>t.namespaces()))])}};function Uw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Kw(r){let e=r.split(":");return e[e.length-1]}function qw(r){return[].concat(...r)}var Hl="/peers/";function Uo(r){if(!Ut(r)||r.type==null)throw new I("Invalid PeerId");let e=r.toCID().toString();return new Rr(`${Hl}${e}`)}async function om(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=re(i.multiaddr)),!er(i.multiaddr))throw new I("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(re(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Xi(r,e,t,n){if(e==null)throw new I("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new I("publicKey does not match peer id");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new I("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=Yi(d,{validate:sm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Yi(d,{validate:im,map:am})}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,b]of d)b==null?a.delete(h):a.set(h,b);a=Yi([...a.entries()],{validate:sm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[b,m]of d)m==null?h.delete(b):h.set(b,m);c=Yi([...h.entries()],{validate:im,map:am})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=rt(o.id.publicKey):e.publicKey!=null?l=rt(e.publicKey):r.publicKey!=null&&(l=rt(r.publicKey));let f={addresses:await om(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=>X(h.multiaddr,d.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Yi(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 sm(r,e){if(typeof r!="string")throw new I("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new I("Metadata value must be a Uint8Array")}function im(r,e){if(typeof r!="string")throw new I("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new I("Tag value must be an integer");if(e.value<0||e.value>100)throw new I("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new I("Tag ttl must be an integer");if(e.ttl<0)throw new I("Tag ttl must be between greater than 0")}}function am(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 cm(r){let e=r.toString().split("/")[2],t=xe.parse(e,et);return ku(t)}function Wl(r,e,t){let n=cm(r);return Qp(n,e,t)}function $w(r,e){return{prefix:Hl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Wl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Wl(n.key,n.value,e),Wl(o.key,o.value,e)))}}var Zi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Fl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Vl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Uo(e),t)}async load(e,t){let n=Uo(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new nr;return An(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Xi(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 Xi(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 Xi(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($w(e??{},this.maxAddressAge),e)){let o=cm(t);if(o.equals(this.peerId))continue;let s=Nt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield An(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Uo(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new nr;return{peerPB:s,peer:An(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=Nt.encode(t);return await this.datastore.put(Uo(e),s,o),{peer:An(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Jp(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Gl=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Zi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Oo(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=Ut(t)?t:Ut(t?.expectedPeer)?t.expectedPeer:void 0,s=Ut(t)||t===void 0?n:t,i=await Sn.openAndCertify(e,Pr.DOMAIN,s),a=wo(i.publicKey);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=Pr.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=Sn.createFromProtobuf(u.peerRecordEnvelope),f=Pr.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 um(r,e={}){return new Gl(r,e)}var Qi=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 zw(r){return r[Symbol.asyncIterator]!=null}function Vw(r){if(zw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var jl=Vw;function Hw(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 lm=Hw;function Ww(r){return r[Symbol.asyncIterator]!=null}function Gw(r,e){let t=0;if(Ww(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=lm(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 kr=Gw;function jw(r){return r[Symbol.asyncIterator]!=null}function Yw(r,e){return jw(r)?(async function*(){yield*(await Oo(r)).sort(e)})():(function*(){yield*Oo(r).sort(e)})()}var Yl=Yw;function Xw(r){return r[Symbol.asyncIterator]!=null}function Zw(r,e){return Xw(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Xl=Zw;var Ji=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 jl(this.putMany(e,n)),e=[],await jl(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=kr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>kr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=kr(n,()=>o++>=s)}return e.limit!=null&&(n=Xl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=kr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>kr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=kr(n,()=>s++>=o)}return e.limit!=null&&(n=Xl(n,e.limit)),n}};var ea=class extends Ji{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 Qi;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 Rr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Rr(n),t?.signal?.throwIfAborted()}};var fm=864e13;var ta=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=ke({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=Y(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=un(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?fm-Date.now():0,lastVerified:o?fm-Date.now():void 0})})}remove(e){let t=Y(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(!Te(o))continue;let s=Y(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}),re(n)}confirm(e,t){let n=Y(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=Y(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 ra=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=ke({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=Y(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:ht(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=Y(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(!Te(n))continue;let o=Y(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}`,re(i)):e}confirm(e,t){if(!Te(e))return!1;let n=Y(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(!Te(e))return!1;let n=Y(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 Qw={maxObservedAddresses:10},na=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=ke({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Qw.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&&(Dt(e)||sp(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:re(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 Jw={maxObservedAddresses:10},oa=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=ke({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Jw.maxObservedAddresses}get(e,t){if(Dt(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:!Te(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(!Te(e))return e.toString();let t=Y(e);return`${t.host}-${t.port}-${t.protocol}`}};var dm=6e4,hm={maxObservedAddresses:10,addressVerificationTTL:dm*10,addressVerificationRetry:dm*5},ex=r=>r;function Zl(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&xt(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var sa=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 na(e,t),this.dnsMappings=new ta(e,t),this.ipMappings=new ra(e,t),this.transportAddresses=new oa(e,t),this.announceFilter=t.announceFilter??ex,this.observedAddressFilter=vo(1024),this.addressVerificationTTL=t.addressVerificationTTL??hm.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??hm.addressVerificationRetry,this._updatePeerStoreAddresses=Po(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>re(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=Y(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=Zl(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Zl(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=Zl(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=re(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(re(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ht(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(re(`/ip${ht(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Te(e))return!1;let t=Y(e);if(t.type!=="ip4"||un(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Cr.exactMatch(s)||To.exactMatch(s),s=>Io.exactMatch(s),s=>Ip.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>Y(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!Ao(u)).pop();if(a==null)continue;let c=Y(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 pm;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(pm||(pm={}));var ia=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},aa=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"}},Ko=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ca=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ua=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},la=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},qo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},fa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},da=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ha=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},pa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ma=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},tr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Or=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ga=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},ya=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Ql=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=Ws())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>ss(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")}},tx=["metrics","connectionProtector","dns"],rx=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mm(r={}){let e=new Ql(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!rx.includes(o)){let i=e.components[o];if(i==null&&!tx.includes(o))throw new ia(`${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 gm(r){let e={};for(let t of Object.values(r.components))for(let n of nx(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of ox(t))if(e[n]!==!0)throw new aa(`Service "${sx(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function nx(r){return Array.isArray(r?.[Nn])?r[Nn]:[]}function ox(r){return Array.isArray(r?.[Xa])?r[Xa]:[]}function sx(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function ym(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Cr.matches(e)?!0:Dt(e)),r}var oe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ba(r){if(Ut(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:xt(n),e.forEach(o=>{if(!er(o))throw new Bt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new I("Multiaddrs must all have the same peer id or have no peer id")}else{let i=xt(s);if(t?.equals(i)!==!0)throw new I("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Ap.exactMatch(n)),{peerId:t,multiaddrs:e}}var ix=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function bm(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??ix;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function $o(r){let e=Y(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new I(`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 I(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new on(e.host,t)}function Jl(r){return!Ir.exactMatch(r)}function wa(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=>Jl(s)))return n}var xa=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>$o(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 it;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(Te(c.remoteAddr)){let f=Y(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await bm(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 wm="last-dial-failure",xm="last-dial-success";var Em=100,Ea=50;function ax(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function vm(r){return r.sort((e,t)=>kp(e.multiaddr,t.multiaddr)||Op(e.multiaddr,t.multiaddr)||Np(e.multiaddr,t.multiaddr)||ax(e,t)||Rp(e.multiaddr,t.multiaddr))}var va=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},Sa=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var tf=Va(Am(),1);function rf(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 lx=100,Cn=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=rf(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>lx&&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 Vo=class extends tf.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#u;#x=0;#c;#l;#a;#i=[];#s=0;#r;#C;#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:Cn,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.#u=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#u)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#k(e){this.#a?this.#i.push(e):this.#n++}#O(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#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")}#F(){this.#l=void 0,this.#P(),this.#L()}#U(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#u-(e-n);return this.#I(o),!0}return!1}if(this.#c===void 0){let t=this.#x-e;if(t<0)this.#n=this.#e?this.#o:0;else return this.#I(t),!0}return!1}#I(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#F()},e))}#A(){this.#c&&(clearInterval(this.#c),this.#c=void 0)}#T(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#b(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#T(),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.#U(t);if(this.#N&&this.#M){let o=this.#r.dequeue();this.#t||(this.#k(t),this.#p()),n&&this.#L(),o(),this.emit("active"),e=!0}}return e}#L(){this.#t||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#P()},this.#u),this.#x=Date.now()+this.#u)}#P(){this.#a||(this.#c!==void 0&&(this.#n===0&&this.#o===0?this.#A():this.#x=Date.now()+this.#u),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){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.#_()}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={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,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}let l=e({signal:t.signal});if(t.timeout!==void 0&&(l=Lo(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,b)=>{u=()=>{b(d.reason)},d.addEventListener("abort",u,{once:!0}),d.aborted&&u()})])}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 Cn){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.#_(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#C,this.#A(),this.#D(),this.emit("empty"),this.#o===0&&(this.#T(),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","active"],()=>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){let n=Array.isArray(e)?e:[e];return new Promise(o=>{let s=()=>{if(!(t&&!t())){for(let i of n)this.off(i,s);o()}};for(let i of n)this.on(i,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#K(){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.#D()}))}#q(){this.#t||(this.#O(),this.#p())}#D(){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 _a(r){let e=[Xe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var nf=60;function Ca(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:Xe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Xe[e.type],TTL:e.TTL??e.ttl??nf,data:e.data instanceof Uint8Array?q(e.data):e.data}))}}var fx=4;function of(r,e={}){let t=new Vo({concurrency:e.queryConcurrency??fx});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),_a(o.types).forEach(c=>{i.append("type",Xe[c])}),o.onProgress?.(new oe("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=Ca(await c.json());return o.onProgress?.(new oe("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function _m(){return[of("https://cloudflare-dns.com/dns-query"),of("https://dns.google/resolve")]}var Tm=Va(Im(),1);var sf=class{lru;constructor(e){this.lru=(0,Tm.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 Ca({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:Xe[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??nf)*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 Lm(r){return new sf(r)}var dx=1e3,hx=()=>Math.random()>.5?-1:1,Ia=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=Lm(e.cacheSize??dx),this.logger=e.logger,this.sorter=e.sorter??hx,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["."]=_m())}async query(e,t={}){let n=_a(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new oe("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,logger:this.logger,types:n});if(u.Answer.length===0)throw new Sa("Query result had no answers");for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new oe("dns:error",u))}}throw new va(a,`DNS lookup of ${e} ${n} failed`)}};var Xe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Xe||(Xe={}));function Pm(r={}){return new Ia(r)}var af=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 o=this.getDNS(t),s;try{s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Xe.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(l=>l.name==="EmptyDNSAnswerError"))return[];throw c}let 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(re(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Pm()),this.dns)}},Nr=new af;async function cf(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new ya("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 cf(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var In={maxParallelDials:Ea,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Nr}},Ta=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??In.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??In.maxDialQueueLength,this.dialTimeout=t.dialTimeout??In.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??In.addressDialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??In.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ti({concurrency:t.maxParallelDials??In.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}=ba(e);if(n!=null&&t.force!==!0){let i=wa(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new oe("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 oe("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Br("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new oe("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new oe("dial-queue:start-dial"));let a=vt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??hf,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 oe("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 Br("Peer had more than maxPeerAddrsToDial");a++;let b=vt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let m=await this.components.transportManager.dial(h.multiaddr,{...e,signal:b});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[xm]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return m}catch(m){if(this.log.error("dial failed to %a - %e",h.multiaddr,m),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[wm]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new es(m.message);u.push(m)}finally{b.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:re(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Br("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new qo("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 cf(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 ha(`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?vm(u):u.sort(this.addressSorter);if(l.length===0)throw new qo(`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=>!Ir.matches(o.multiaddr))!=null:!0}catch{}return!1}};var px=Object.prototype.toString,mx=r=>px.call(r)==="[object Error]",gx=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 pf(r){if(!(r&&mx(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:gx.has(t)}function yx(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function La(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 mf(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var gf=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 bx(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 Pa(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function wx(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 xx({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 gf)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=bx(t,o);if(Pa(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),Pa(n,a)<=0||Pa(n,a)<=0||i<=0||s instanceof TypeError&&!pf(s)||!await o.shouldRetry(h))throw s;let m=Pa(n,a);if(m<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let g=Math.min(d,m);return o.signal?.throwIfAborted(),await wx(g,o),o.signal?.throwIfAborted(),!0}async function yf(r,e={}){if(e={...e},yx(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,mf("onFailedAttempt",e.onFailedAttempt),mf("shouldRetry",e.shouldRetry),mf("shouldConsumeRetry",e.shouldConsumeRetry),La("factor",e.factor,{min:0,allowInfinity:!1}),La("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),La("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),La("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 xx({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Da=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 Ii({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Dm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await yf(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(ja)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Dm(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function Dm(r){for(let e of r.tags.keys())if(e.startsWith(ja))return!0;return!1}var hf=50,bf={maxConnections:Em,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ra=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??bf.maxConnections,this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");this.connections=new it,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=>$o(re(n))),this.deny=(t.deny??[]).map(n=>$o(re(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??bf.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Li({points:t.inboundConnectionThreshold??bf.inboundConnectionThreshold,duration:1}),this.connectionPruner=new xa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>re(n))}),this.dialQueue=new Ta(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ea,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Nr},connections:this.connections}),this.reconnectQueue=new Da({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 If(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 Tf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([pt(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 I("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 At("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new oe("connection:open",e));let{peerId:n,multiaddrs:o}=ba(e);if(this.peerId.equals(n))throw new Mr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=wa(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 oe("dial-queue:already-connected")),t.onProgress?.(new oe("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??hf});if(s.status!=="open")throw new rr("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 oe("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([pt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Te(e.remoteAddr)){let s=Y(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(Te(e.remoteAddr)){let s=Y(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(Te(e.remoteAddr)){let o=Y(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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Sx=1e4,Ax="1.0.0",_x="ping",Cx="ipfs",Rm=32,Ix=!0,ka=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Cx}/${_x}/${Ax}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Sx,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Ix,this.timeout=new bi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Nn]=["@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=Rl(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(Rm)),{signal:n}),s.read({bytes:Rm,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 Oa=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:q(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:q(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 br;for await(let s of En(...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 At;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 At;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Na=globalThis.CustomEvent??Event;async function*wf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Ce(),a=Ce(),c=!1,u,l=!1,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(s.length===t&&(i=Ce(),await i.promise),l||f)break;let g={done:!1};s.push(g),m().then(y=>{g.done=!0,g.ok=!0,g.value=y,o.dispatchEvent(new Na("task-complete"))},y=>{g.done=!0,g.err=y,o.dispatchEvent(new Na("task-complete"))})}c=!0,o.dispatchEvent(new Na("task-complete"))}catch(m){u=m,o.dispatchEvent(new Na("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(m=>m.done)}function*h(){for(;s.length>0&&s[0].done;){let m=s[0];if(s.shift(),m.ok)yield m.value;else throw l=!0,i.resolve(),m.err;i.resolve()}}function*b(){for(;d();)for(let m=0;m<s.length;m++)if(s[m].done){let g=s[m];if(s.splice(m,1),m--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}try{for(;;){if(d()||(a=Ce(),await a.promise),u!=null||(n?yield*h():yield*b(),u!=null))throw u;if(c&&s.length===0)break}}finally{f=!0,i.resolve()}}var Ma=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:q(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 Ko("No peer routers available");if(e.toString()===this.peerId.toString())throw new ca("Should not try to find self");let n=this,o=En(...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 nr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ko("No peer routers available");let n=this,o=vo(1024);for await(let s of wf((async function*(){let i=En(...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 Ba=class extends Ne{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=vt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ce(),yield(await pt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=vt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=crypto.getRandomValues(new Uint8Array(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 je(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 xf=32,Ef=64,Fa=class{log;topologies;handlers;components;middleware;globalMiddleware=[];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=ke({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 ua(`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 la(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:xf,maxOutboundStreams:Ef,...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 I("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){if(typeof e=="function"){this.globalMiddleware.push(e);return}if(t==null)throw new I("Protocol middleware is required");this.middleware.set(e,t)}unuse(e){typeof e=="function"?this.globalMiddleware=this.globalMiddleware.filter(t=>t!==e):this.middleware.delete(e)}getMiddleware(e){return[...this.globalMiddleware,...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 Ua=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=ke({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=ke({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??On.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new I("Transport must have a valid tag");if(this.transports.has(t))throw new I(`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 ga(`No transport available for address ${String(e)}`);return t?.onProgress?.(new oe("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 At("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 fa)});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})}),bl.matches(c)?t.ipv4.attempts++:wl.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),bl.matches(c)&&t.ipv4.success++,wl.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===On.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new da(`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}: ${`${xx(i)}`.split(`
14
+ ${s}: ${`${Tx(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 xx(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var vt="/multistream/1.0.0";var Ex=T(`
18
- `);async function Ho(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Ex[0])throw new Jo("Missing newline");return q(n).trimEnd()}async function Ln(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=xi(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"]',vt,i);let c=T(`${vt}
19
- `),l=T(`${i}
20
- `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await Ho(o,t),n.trace('read "%s"',a),a!==vt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(T(`${i}
21
- `),t);if(n.trace("reading protocol response"),a=await Ho(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Qo(`Protocol selection failed - could not negotiate ${e}`)}async function Pn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=xi(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Ho(o,t);if(n.trace('read "%s"',s),s===vt){n.trace('respond with "%s" for "%s"',vt,s),await o.write(T(`${vt}
22
- `),t),n.trace('responded with "%s" for "%s"',vt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(T(`${s}
23
- `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new ne(...e.map(a=>Ii.single(T(`${a}
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 Tx(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var St="/multistream/1.0.0";var Lx=T(`
18
+ `);async function Ho(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Lx[0])throw new Jo("Missing newline");return q(n).trimEnd()}async function Tn(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=xi(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"]',St,i);let c=T(`${St}
19
+ `),u=T(`${i}
20
+ `);if(await o.writeV([c,u],t),n.trace("reading multistream-select header"),a=await Ho(o,t),n.trace('read "%s"',a),a!==St){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(T(`${i}
21
+ `),t);if(n.trace("reading protocol response"),a=await Ho(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Qo(`Protocol selection failed - could not negotiate ${e}`)}async function Ln(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=xi(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Ho(o,t);if(n.trace('read "%s"',s),s===St){n.trace('respond with "%s" for "%s"',St,s),await o.write(T(`${St}
22
+ `),t),n.trace('responded with "%s" for "%s"',St,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(T(`${s}
23
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new ne(...e.map(a=>Ci.single(T(`${a}
24
24
  `))),T(`
25
25
  `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(T(`na
26
- `),t),n('responded with "na" for "%s"',s)}}var Sf=class extends Ne{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Ju(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new ns(n.local,n.error))})}[Symbol.toStringTag]="Connection";[If]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new tr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new rr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new rr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new On("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new oe("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 Ln(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Ax(n.protocol,this.components.registrar,t),s=Om(n.protocol,"outbound",this);if(s>o){let c=new rs(`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 oe("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Pn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Sx(t.protocol,this.components.registrar);if(Om(t.protocol,"inbound",this)>o)throw new ts(`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 On("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Nm(r,e){return new Sf(r,e)}function Sx(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 xf}function Ax(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??Ef}function Om(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ka=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=ke({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=ke({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 pa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Et([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 ma("Connection denied");await Ge(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=wt(n),await Ge(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(_x(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;if(f!=null&&(d=wt(f)),n?.onProgress?.(new oe(`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})),d!=null&&!d.equals(s)){let h=new Go(`Expected remote peer ${d} but connected to ${s}`);throw e.abort(h),h}}if(s.equals(this.components.peerId)){let f=new Mr("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 oe(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=Nm(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 Pn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`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 Or(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 Ln(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`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 Or(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 Ln(e,o,n),i=t.get(s);if(i==null)throw new tr(`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 tr(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 Pn(e,o,n),i=t.get(s);if(i==null)throw new tr(`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 _x(r){return r.skipEncryption===!0}var qa="3.4.0",$a="js-libp2p";function Bm(r,e){return`${r??$a}/${e??qa} browser/${globalThis.navigator.userAgent}`}var Wo=class extends Ne{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ne,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??Ws(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??$a,s=e.nodeInfo?.version??qa,i=this.components=hm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Bm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ea,connectionGater:mm(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",am(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ka(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ua(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ra(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ka(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Fa(this.components)),this.configureComponent("addressManager",new sa(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ma(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Oa(this.components,{routers:c})),this.configureComponent("randomWalk",new Ba(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ha]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ha])),f[ja]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[ja])),f[Wa]!=null&&(this.log("registering service %s for peer discovery",l),f[Wa].addEventListener?.("peer",d=>{this.#e(d)}))}pm(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 br;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new C("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new C("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){er(e)&&(e=wt(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=tt([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=tn(o);if(!e.equals(s.toMultihash().bytes))throw new Mt("public key did not match requested peer");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){if(typeof e=="function"){this.components.registrar.use(e);return}if(t==null)throw new C("Protocol middleware is required");this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){if(typeof e=="function"){this.components.registrar.unuse(e);return}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 Ix(r={}){r.privateKey??=await Fh("Ed25519");let e=new Wo({...await zh(r),peerId:$h(r.privateKey)});return r.start!==!1&&await e.start(),e}var Cx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Tx(r){return r==null?!1:r instanceof Wo?!0:Cx.every(e=>typeof r[e]=="function")}return Wm(Lx);})();
26
+ `),t),n('responded with "na" for "%s"',s)}}var Sf=class extends Ne{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=Jl(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 ns(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Cf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new tr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new rr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new rr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new kn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new oe("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 Tn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Rx(n.protocol,this.components.registrar,t),s=Mm(n.protocol,"outbound",this);if(s>o){let c=new rs(`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 oe("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 Ln(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Dx(t.protocol,this.components.registrar);if(Mm(t.protocol,"inbound",this)>o)throw new ts(`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 kn("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 Bm(r,e){return new Sf(r,e)}function Dx(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 xf}function Rx(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??Ef}function Mm(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ka=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=ke({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=ke({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 pa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=vt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ma("Connection denied");await je(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=xt(n),await je(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(kx(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;if(f!=null&&(d=xt(f)),n?.onProgress?.(new oe(`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})),d!=null&&!d.equals(s)){let h=new jo(`Expected remote peer ${d} but connected to ${s}`);throw e.abort(h),h}}if(s.equals(this.components.peerId)){let f=new Mr("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 oe(`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=Bm(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Ln(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`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 Or(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 Tn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`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 Or(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 Tn(e,o,n),i=t.get(s);if(i==null)throw new tr(`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 tr(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 Ln(e,o,n),i=t.get(s);if(i==null)throw new tr(`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 kx(r){return r.skipEncryption===!0}var qa="3.5.0",$a="js-libp2p";function Um(r,e){return`${r??$a}/${e??qa} browser/${globalThis.navigator.userAgent}`}var Wo=class extends Ne{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ne,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??Ws(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??$a,s=e.nodeInfo?.version??qa,i=this.components=mm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Um(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ea,connectionGater:ym(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",um(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 Ka(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 Ua(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ra(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ka(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Fa(this.components)),this.configureComponent("addressManager",new sa(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 Ma(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 Oa(this.components,{routers:c})),this.configureComponent("randomWalk",new Ba(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[Ha]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Ha])),f[Ga]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ga])),f[Wa]!=null&&(this.log("registering service %s for peer discovery",u),f[Wa].addEventListener?.("peer",d=>{this.#e(d)}))}gm(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 br;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 I("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new I("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={}){er(e)&&(e=xt(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=tt([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=await Kh(e,o,t);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){if(typeof e=="function"){this.components.registrar.use(e);return}if(t==null)throw new I("Protocol middleware is required");this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){if(typeof e=="function"){this.components.registrar.unuse(e);return}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 Ox(r={}){r.privateKey??=await Fh("Ed25519");let e=new Wo({...await Vh(r),peerId:zh(r.privateKey)});return r.start!==!1&&await e.start(),e}var Nx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Mx(r){return r==null?!1:r instanceof Wo?!0:Nx.every(e=>typeof r[e]=="function")}return jm(Bx);})();
27
27
  /*! Bundled license information:
28
28
 
29
29
  @noble/curves/utils.js: