@libp2p/circuit-relay-v2 4.2.5-29797a5bb → 4.2.5-5b8813abc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PCircuitRelayV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PCircuitRelayV2=(()=>{var Ts=Object.defineProperty;var yd=Object.getOwnPropertyDescriptor;var gd=Object.getOwnPropertyNames;var bd=Object.prototype.hasOwnProperty;var Q=(r,e)=>{for(var t in e)Ts(r,t,{get:e[t],enumerable:!0})},wd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gd(e))!bd.call(r,s)&&s!==t&&Ts(r,s,{get:()=>e[s],enumerable:!(n=yd(e,s))||n.enumerable});return r};var xd=r=>wd(Ts({},"__esModule",{value:!0}),r);var Dy={};Q(Dy,{RELAY_V2_HOP_CODEC:()=>Me,RELAY_V2_STOP_CODEC:()=>ur,circuitRelayServer:()=>Ay,circuitRelayTransport:()=>Ty});function Ed(r){return typeof r?.handleEvent=="function"}function Sd(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ae=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=Sd(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Ed(t)?t.handleEvent(i):t(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:s})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ot=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},dr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var jn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var bt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Xr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Wn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Gn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Yn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Zn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},qt=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var hr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Xn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},pr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Qn=class extends pr{constructor(e,t){super(!0,e,t)}},Jn=class extends pr{constructor(e,t){super(!1,e,t)}};var Ds=Symbol.for("@libp2p/peer-id");var Fc="keep-alive";function Kc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function qc(...r){let e=[];for(let t of r)Kc(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 zc(...r){let e=[];for(let t of r)Kc(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 Hc=Symbol.for("@libp2p/transport");var Vc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Vc||(Vc={}));var $c=Symbol.for("@libp2p/service-capabilities"),jc=Symbol.for("@libp2p/service-dependencies");var Rs={};Q(Rs,{base58btc:()=>re,base58flickr:()=>Cd});var ag=new Uint8Array(0);function Wc(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 st(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Gc(r){return new TextEncoder().encode(r)}function Yc(r){return new TextDecoder().decode(r)}function vd(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,g=0,E=p.length;g!==E&&p[g]===0;)g++,b++;for(var v=(E-g)*l+1>>>0,I=new Uint8Array(v);g!==E;){for(var D=p[g],P=0,B=v-1;(D!==0||P<h)&&B!==-1;B--,P++)D+=256*I[B]>>>0,I[B]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=P,g++}for(var T=v-h;T!==v&&I[T]===0;)T++;for(var U=c.repeat(b);T<v;++T)U+=r.charAt(I[T]);return U}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,g=0;p[b]===c;)h++,b++;for(var E=(p.length-b)*u+1>>>0,v=new Uint8Array(E);p[b];){var I=t[p.charCodeAt(b)];if(I===255)return;for(var D=0,P=E-1;(I!==0||D<g)&&P!==-1;P--,D++)I+=a*v[P]>>>0,v[P]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=D,b++}if(p[b]!==" "){for(var B=E-g;B!==E&&v[B]===0;)B++;for(var T=new Uint8Array(h+(E-B)),U=h;B!==E;)T[U++]=v[B++];return T}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var _d=vd,Ad=_d,Xc=Ad;var Is=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")}},Cs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Qc(this,e)}},Ls=class{decoders;constructor(e){this.decoders=e}or(e){return Qc(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 Qc(r,e){return new Ls({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Bs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Is(e,t,n),this.decoder=new Cs(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function mr({name:r,prefix:e,encode:t,decode:n}){return new Bs(r,e,t,n)}function wt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Xc(t,r);return mr({prefix:e,name:r,encode:n,decode:o=>st(s(o))})}function Td(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let u=0;u<s;++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,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Dd(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Id(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Id(n);return mr({prefix:e,name:r,encode(o){return Dd(o,n,t)},decode(o){return Td(o,s,t,r)}})}var re=wt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Cd=wt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Os={};Q(Os,{base32:()=>xt,base32hex:()=>Od,base32hexpad:()=>Nd,base32hexpadupper:()=>Ud,base32hexupper:()=>Pd,base32pad:()=>Bd,base32padupper:()=>Rd,base32upper:()=>Ld,base32z:()=>kd});var xt=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ld=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bd=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rd=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Od=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pd=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nd=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ud=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kd=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ps={};Q(Ps,{base36:()=>Qr,base36upper:()=>Md});var Qr=wt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Md=wt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Fd=tu,Jc=128,Kd=127,qd=~Kd,zd=Math.pow(2,31);function tu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zd;)e[t++]=r&255|Jc,r/=128;for(;r&qd;)e[t++]=r&255|Jc,r>>>=7;return e[t]=r|0,tu.bytes=t-n+1,e}var Vd=Ns,Hd=128,eu=127;function Ns(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ns.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&eu)<<s:(i&eu)*Math.pow(2,s),s+=7}while(i>=Hd);return Ns.bytes=o-n,t}var $d=Math.pow(2,7),jd=Math.pow(2,14),Wd=Math.pow(2,21),Gd=Math.pow(2,28),Yd=Math.pow(2,35),Zd=Math.pow(2,42),Xd=Math.pow(2,49),Qd=Math.pow(2,56),Jd=Math.pow(2,63),eh=function(r){return r<$d?1:r<jd?2:r<Wd?3:r<Gd?4:r<Yd?5:r<Zd?6:r<Xd?7:r<Qd?8:r<Jd?9:10},th={encode:Fd,decode:Vd,encodingLength:eh},rh=th,Jr=rh;function en(r,e=0){return[Jr.decode(r,e),Jr.decode.bytes]}function yr(r,e,t=0){return Jr.encode(r,e,t),e}function gr(r){return Jr.encodingLength(r)}function Ge(r,e){let t=e.byteLength,n=gr(r),s=n+gr(t),o=new Uint8Array(s+t);return yr(r,o,0),yr(t,o,n),o.set(e,s),new br(r,t,e,o)}function Ye(r){let e=st(r),[t,n]=en(e),[s,o]=en(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new br(t,s,i,e)}function ru(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Wc(r.bytes,t.bytes)}}var br=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function nu(r,e){let{bytes:t,version:n}=r;return n===0?oh(t,Us(r),e??re.encoder):sh(t,Us(r),e??xt.encoder)}var ou=new WeakMap;function Us(r){let e=ou.get(r);if(e==null){let t=new Map;return ou.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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!==tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ih)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=Ge(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&&ru(e.multihash,n.multihash)}toString(e){return nu(this,e)}toJSON(){return{"/":nu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??su(n,s,o.bytes))}else if(t[ah]===!0){let{version:n,multihash:s,code:o}=t,i=Ye(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==tn)throw new Error(`Version 0 CID must use dag-pb (code: ${tn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=su(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=st(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new br(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=en(e.subarray(t));return t+=m,f},s=n(),o=tn;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,s]=nh(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Us(o).set(n,e),o}};function nh(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case xt.prefix:{let t=e??xt;return[xt.prefix,t.decode(r)]}case Qr.prefix:{let t=e??Qr;return[Qr.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 oh(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function sh(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var tn=112,ih=18;function su(r,e,t){let n=gr(r),s=n+gr(e),o=new Uint8Array(s+t.byteLength);return yr(r,o,0),yr(e,o,n),o.set(t,s),o}var ah=Symbol.for("@ipld/js-cid/CID");var ks={};Q(ks,{identity:()=>Fe});var iu=0,ch="identity",au=st;function uh(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 Ge(iu,au(r))}var Fe={code:iu,name:ch,encode:au,digest:uh};function xe(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 lh(r){return r.buffer instanceof ArrayBuffer}function Ze(r){return lh(r)?r:r.slice()}async function cu(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,Ze(e),Ze(t.subarray()));return n?.signal?.throwIfAborted(),o}function at(r=0){return new Uint8Array(r)}function rn(r=0){return new Uint8Array(r)}function Ms(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=rn(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function uu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var fu=Symbol.for("@achingbrain/uint8arraylist");function lu(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function to(r){return!!r?.[fu]}var ee=class r{bufs;length;[fu]=!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(to(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(to(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=lu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=lu(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(to(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ms(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ms(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let 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(!to(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;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 m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);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=rn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=at(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=at(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=at(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=rn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=at(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=at(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=at(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=at(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=at(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!uu(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var Vs={};Q(Vs,{base10:()=>bh});var Kg=new Uint8Array(0);function du(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 ct(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return zt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return zt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function hu(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}function fh(r){return r?.buffer instanceof ArrayBuffer}function zt(r){return fh(r)?r:r.slice()}function dh(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,g=0,E=p.length;g!==E&&p[g]===0;)g++,b++;for(var v=(E-g)*l+1>>>0,I=new Uint8Array(v);g!==E;){for(var D=p[g],P=0,B=v-1;(D!==0||P<h)&&B!==-1;B--,P++)D+=256*I[B]>>>0,I[B]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=P,g++}for(var T=v-h;T!==v&&I[T]===0;)T++;for(var U=c.repeat(b);T<v;++T)U+=r.charAt(I[T]);return U}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,g=0;p[b]===c;)h++,b++;for(var E=(p.length-b)*u+1>>>0,v=new Uint8Array(E);p[b];){var I=t[p.charCodeAt(b)];if(I===255)return;for(var D=0,P=E-1;(I!==0||D<g)&&P!==-1;P--,D++)I+=a*v[P]>>>0,v[P]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=D,b++}if(p[b]!==" "){for(var B=E-g;B!==E&&v[B]===0;)B++;for(var T=new Uint8Array(h+(E-B)),U=h;B!==E;)T[U++]=v[B++];return T}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var hh=dh,ph=hh,yu=ph;var Fs=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")}},Ks=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return gu(this,e)}},qs=class{decoders;constructor(e){this.decoders=e}or(e){return gu(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 gu(r,e){return new qs({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var zs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Fs(e,t,n),this.decoder=new Ks(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function wr({name:r,prefix:e,encode:t,decode:n}){return new zs(r,e,t,n)}function Et({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=yu(t,r);return wr({prefix:e,name:r,encode:n,decode:o=>ct(s(o))})}function mh(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let u=0;u<s;++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,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function yh(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function gh(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ie({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=gh(n);return wr({prefix:e,name:r,encode(o){return yh(o,n,t)},decode(o){return mh(o,s,t,r)}})}var bh=Et({prefix:"9",name:"base10",alphabet:"0123456789"});var Hs={};Q(Hs,{base16:()=>wh,base16upper:()=>xh});var wh=ie({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xh=ie({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $s={};Q($s,{base2:()=>Eh});var Eh=ie({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var js={};Q(js,{base256emoji:()=>Th});var bu=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}"),Sh=bu.reduce((r,e,t)=>(r[t]=e,r),[]),vh=bu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function _h(r){return r.reduce((e,t)=>(e+=Sh[t],e),"")}function Ah(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=vh[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Th=wr({prefix:"\u{1F680}",name:"base256emoji",encode:_h,decode:Ah});var Ws={};Q(Ws,{base32:()=>xr,base32hex:()=>Lh,base32hexpad:()=>Rh,base32hexpadupper:()=>Oh,base32hexupper:()=>Bh,base32pad:()=>Ih,base32padupper:()=>Ch,base32upper:()=>Dh,base32z:()=>Ph});var xr=ie({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Dh=ie({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ih=ie({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ch=ie({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Lh=ie({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Bh=ie({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Rh=ie({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Oh=ie({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ph=ie({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Gs={};Q(Gs,{base36:()=>nn,base36upper:()=>Nh});var nn=Et({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nh=Et({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ys={};Q(Ys,{base58btc:()=>Xe,base58flickr:()=>Uh});var Xe=Et({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Uh=Et({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zs={};Q(Zs,{base64:()=>kh,base64pad:()=>Mh,base64url:()=>Fh,base64urlpad:()=>Kh});var kh=ie({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Mh=ie({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fh=ie({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Kh=ie({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xs={};Q(Xs,{base8:()=>qh});var qh=ie({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qs={};Q(Qs,{identity:()=>zh});var zh=wr({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>hu(r)});var rb=new TextEncoder,nb=new TextDecoder;var ei={};Q(ei,{identity:()=>fp});var $h=Eu,wu=128,jh=127,Wh=~jh,Gh=Math.pow(2,31);function Eu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Gh;)e[t++]=r&255|wu,r/=128;for(;r&Wh;)e[t++]=r&255|wu,r>>>=7;return e[t]=r|0,Eu.bytes=t-n+1,e}var Yh=Js,Zh=128,xu=127;function Js(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Js.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&xu)<<s:(i&xu)*Math.pow(2,s),s+=7}while(i>=Zh);return Js.bytes=o-n,t}var Xh=Math.pow(2,7),Qh=Math.pow(2,14),Jh=Math.pow(2,21),ep=Math.pow(2,28),tp=Math.pow(2,35),rp=Math.pow(2,42),np=Math.pow(2,49),op=Math.pow(2,56),sp=Math.pow(2,63),ip=function(r){return r<Xh?1:r<Qh?2:r<Jh?3:r<ep?4:r<tp?5:r<rp?6:r<np?7:r<op?8:r<sp?9:10},ap={encode:$h,decode:Yh,encodingLength:ip},cp=ap,on=cp;function sn(r,e=0){return[on.decode(r,e),on.decode.bytes]}function Er(r,e,t=0){return on.encode(r,e,t),e}function Sr(r){return on.encodingLength(r)}function _r(r,e){let t=e.byteLength,n=Sr(r),s=n+Sr(t),o=new Uint8Array(s+t);return Er(r,o,0),Er(t,o,n),o.set(e,s),new vr(r,t,e,o)}function Su(r){let e=ct(r),[t,n]=sn(e),[s,o]=sn(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new vr(t,s,i,e)}function vu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&du(r.bytes,t.bytes)}}var vr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=zt(n),this.bytes=zt(s)}};var _u=0,up="identity",Au=ct;function lp(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 _r(_u,Au(r))}var fp={code:_u,name:up,encode:Au,digest:lp};var ni={};Q(ni,{sha256:()=>hp,sha512:()=>pp});var dp=20;function ri({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ti(r,e,t,n,s)}var ti=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??dp,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Tu(n,this.code,t?.truncate):n.then(s=>Tu(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Tu(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 _r(e,r)}function Iu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var hp=ri({name:"sha2-256",code:18,encode:Iu("SHA-256")}),pp=ri({name:"sha2-512",code:19,encode:Iu("SHA-512")});function Cu(r,e){let{bytes:t,version:n}=r;return n===0?yp(t,oi(r),e??Xe.encoder):gp(t,oi(r),e??xr.encoder)}var Lu=new WeakMap;function oi(r){let e=Lu.get(r);if(e==null){let t=new Map;return Lu.set(r,t),t}return e}var no=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=zt(s),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==cn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bp)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=_r(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&&vu(e.multihash,n.multihash)}toString(e){return Cu(this,e)}toJSON(){return{"/":Cu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Bu(n,s,o.bytes))}else if(t[wp]===!0){let{version:n,multihash:s,code:o}=t,i=Su(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==cn)throw new Error(`Version 0 CID must use dag-pb (code: ${cn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Bu(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ct(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new vr(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=sn(e.subarray(t));return t+=m,f},s=n(),o=cn;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,s]=mp(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return oi(o).set(n,e),o}};function mp(r,e){switch(r[0]){case"Q":{let t=e??Xe;return[Xe.prefix,t.decode(`${Xe.prefix}${r}`)]}case Xe.prefix:{let t=e??Xe;return[Xe.prefix,t.decode(r)]}case xr.prefix:{let t=e??xr;return[xr.prefix,t.decode(r)]}case nn.prefix:{let t=e??nn;return[nn.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 yp(r,e,t){let{prefix:n}=t;if(n!==Xe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function gp(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var cn=112,bp=18;function Bu(r,e,t){let n=Sr(r),s=n+Sr(e),o=new Uint8Array(s+t.byteLength);return Er(r,o,0),Er(e,o,n),o.set(t,s),o}var wp=Symbol.for("@ipld/js-cid/CID");var si={...Qs,...$s,...Xs,...Vs,...Hs,...Ws,...Gs,...Ys,...Zs,...js},Ab={...ni,...ei};function Te(r=0){return new Uint8Array(r)}function ii(r=0){return new Uint8Array(r)}function Ou(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ru=Ou("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ai=Ou("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=ii(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),xp={utf8:Ru,"utf-8":Ru,hex:si.base16,latin1:ai,ascii:ai,binary:ai,...si},oo=xp;function j(r,e="utf8"){let t=oo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function J(r,e="utf8"){let t=oo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ep=parseInt("11111",2),ci=parseInt("10000000",2),Sp=parseInt("01111111",2),Pu={0:un,1:un,2:vp,3:Tp,4:Dp,5:Ap,6:_p,16:un,22:un,48:un};function ut(r,e={offset:0}){let t=r[e.offset]&Ep;if(e.offset++,Pu[t]!=null)return Pu[t](r,e);throw new Error("No decoder for tag "+t)}function ln(r,e){let t=0;if((r[e.offset]&ci)===ci){let n=r[e.offset]&Sp,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function un(r,e){ln(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ut(r,e);if(n===null)break;t.push(n)}return t}function vp(r,e){let t=ln(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function _p(r,e){let t=ln(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let 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 Ap(r,e){return e.offset++,null}function Tp(r,e){let t=ln(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Dp(r,e){let t=ln(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Ip(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ee;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function ui(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Ip(r.byteLength);return new ee(Uint8Array.from([e.byteLength|ci]),e)}function De(r){let e=new ee,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ee(Uint8Array.from([2]),ui(e),e)}function so(r){let e=Uint8Array.from([0]),t=new ee(e,r);return new ee(Uint8Array.from([3]),ui(t),t)}function St(r,e=48){let t=new ee;for(let n of r)t.append(n);return new ee(Uint8Array.from([e]),ui(t),t)}var Cp=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Lp=Uint8Array.from([6,5,43,129,4,0,34]),Bp=Uint8Array.from([6,5,43,129,4,0,35]),Rp={ext:!0,kty:"EC",crv:"P-256"},Op={ext:!0,kty:"EC",crv:"P-384"},Pp={ext:!0,kty:"EC",crv:"P-521"},li=32,fi=48,di=66;function hi(r){let e=ut(r);return Nu(e)}function Nu(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===li*2+1)return n=J(e.subarray(t,t+li),"base64url"),s=J(e.subarray(t+li),"base64url"),new Ar({...Rp,key_ops:["verify"],x:n,y:s});if(e.byteLength===fi*2+1)return n=J(e.subarray(t,t+fi),"base64url"),s=J(e.subarray(t+fi),"base64url"),new Ar({...Op,key_ops:["verify"],x:n,y:s});if(e.byteLength===di*2+1)return n=J(e.subarray(t,t+di),"base64url"),s=J(e.subarray(t+di),"base64url"),new Ar({...Pp,key_ops:["verify"],x:n,y:s});throw new oe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Uu(r){return St([De(Uint8Array.from([1])),St([Np(r.crv)],160),St([so(new ee(Uint8Array.from([4]),j(r.x??"","base64url"),j(r.y??"","base64url")))],161)]).subarray()}function Np(r){if(r==="P-256")return Cp;if(r==="P-384")return Lp;if(r==="P-521")return Bp;throw new oe(`Invalid curve ${r}`)}var Ar=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Uu(this.jwk)),this._raw}toMultihash(){return Fe.digest(Qe(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:xe(this.raw,e.raw)}async verify(e,t,n){return cu(this.jwk,t,e,n)}};function pi(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function vt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Oe(r,e,t=""){let n=pi(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function io(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(vt(r.outputLen),vt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Tr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ao(r,e){Oe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function ft(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function co(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ke(r,e){return r<<32-e|r>>>e}var Mu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Up=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function uo(r){if(Oe(r),Mu)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Up[r[t]];return e}var lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ku(r){if(r>=lt._0&&r<=lt._9)return r-lt._0;if(r>=lt.A&&r<=lt.F)return r-(lt.A-10);if(r>=lt.a&&r<=lt.f)return r-(lt.a-10)}function fn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Mu)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=ku(r.charCodeAt(o)),a=ku(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function mi(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Oe(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function yi(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Fu(r=32){vt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var gi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ku(r,e,t){return r&e^~r&t}function qu(r,e,t){return r&e^r&t^e&t}var dn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=co(this.buffer)}update(e){Tr(this),Oe(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=co(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Tr(this),ao(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ft(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},dt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ge=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lo=BigInt(4294967295),zu=BigInt(32);function kp(r,e=!1){return e?{h:Number(r&lo),l:Number(r>>zu&lo)}:{h:Number(r>>zu&lo)|0,l:Number(r&lo)|0}}function Vu(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=kp(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var bi=(r,e,t)=>r>>>t,wi=(r,e,t)=>r<<32-t|e>>>t,Vt=(r,e,t)=>r>>>t|e<<32-t,Ht=(r,e,t)=>r<<32-t|e>>>t,hn=(r,e,t)=>r<<64-t|e>>>t-32,pn=(r,e,t)=>r>>>t-32|e<<64-t;function Je(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var Hu=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),$u=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,ju=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Wu=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,Gu=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Yu=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Fp=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),xi=class extends dn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}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 m=_t[f-15],d=_t[f-2],p=Ke(m,7)^Ke(m,18)^m>>>3,b=Ke(d,17)^Ke(d,19)^d>>>10;_t[f]=b+_t[f-7]+p+_t[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=Ke(a,6)^Ke(a,11)^Ke(a,25),d=l+m+Ku(a,c,u)+Fp[f]+_t[f]|0,b=(Ke(n,2)^Ke(n,13)^Ke(n,22))+qu(n,s,o)|0;l=u,u=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+b|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,o,i,a,c,u,l)}roundClean(){ft(_t)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ft(this.buffer)}},Ei=class extends xi{A=dt[0]|0;B=dt[1]|0;C=dt[2]|0;D=dt[3]|0;E=dt[4]|0;F=dt[5]|0;G=dt[6]|0;H=dt[7]|0;constructor(){super(32)}};var Zu=Vu(["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))),Kp=Zu[0],qp=Zu[1],At=new Uint32Array(80),Tt=new Uint32Array(80),Si=class extends dn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:p,Hh:b,Hl:h}=this;return[e,t,n,s,o,i,a,c,u,l,f,m,d,p,b,h]}set(e,t,n,s,o,i,a,c,u,l,f,m,d,p,b,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=m|0,this.Gh=d|0,this.Gl=p|0,this.Hh=b|0,this.Hl=h|0}process(e,t){for(let v=0;v<16;v++,t+=4)At[v]=e.getUint32(t),Tt[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let I=At[v-15]|0,D=Tt[v-15]|0,P=Vt(I,D,1)^Vt(I,D,8)^bi(I,D,7),B=Ht(I,D,1)^Ht(I,D,8)^wi(I,D,7),T=At[v-2]|0,U=Tt[v-2]|0,Y=Vt(T,U,19)^hn(T,U,61)^bi(T,U,6),k=Ht(T,U,19)^pn(T,U,61)^wi(T,U,6),y=ju(B,k,Tt[v-7],Tt[v-16]),w=Wu(y,P,Y,At[v-7],At[v-16]);At[v]=w|0,Tt[v]=y|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:p,Gh:b,Gl:h,Hh:g,Hl:E}=this;for(let v=0;v<80;v++){let I=Vt(f,m,14)^Vt(f,m,18)^hn(f,m,41),D=Ht(f,m,14)^Ht(f,m,18)^pn(f,m,41),P=f&d^~f&b,B=m&p^~m&h,T=Gu(E,D,B,qp[v],Tt[v]),U=Yu(T,g,I,P,Kp[v],At[v]),Y=T|0,k=Vt(n,s,28)^hn(n,s,34)^hn(n,s,39),y=Ht(n,s,28)^pn(n,s,34)^pn(n,s,39),w=n&o^n&a^o&a,_=s&i^s&c^i&c;g=b|0,E=h|0,b=d|0,h=p|0,d=f|0,p=m|0,{h:f,l:m}=Je(u|0,l|0,U|0,Y|0),u=a|0,l=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let S=Hu(Y,y,_);n=$u(S,U,k,w),s=S|0}({h:n,l:s}=Je(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Je(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Je(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Je(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=Je(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:p}=Je(this.Fh|0,this.Fl|0,d|0,p|0),{h:b,l:h}=Je(this.Gh|0,this.Gl|0,b|0,h|0),{h:g,l:E}=Je(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,s,o,i,a,c,u,l,f,m,d,p,b,h,g,E)}roundClean(){ft(At,Tt)}destroy(){this.destroyed=!0,ft(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},vi=class extends Si{Ah=ge[0]|0;Al=ge[1]|0;Bh=ge[2]|0;Bl=ge[3]|0;Ch=ge[4]|0;Cl=ge[5]|0;Dh=ge[6]|0;Dl=ge[7]|0;Eh=ge[8]|0;El=ge[9]|0;Fh=ge[10]|0;Fl=ge[11]|0;Gh=ge[12]|0;Gl=ge[13]|0;Hh=ge[14]|0;Hl=ge[15]|0;constructor(){super(64)}};var Dr=yi(()=>new Ei,gi(1));var fo=yi(()=>new vi,gi(3));var z=(r,e,t)=>Oe(r,e,t),Ai=vt,Ir=uo,de=(...r)=>mi(...r),Cr=r=>fn(r),$t=pi,mn=r=>Fu(r),po=BigInt(0),_i=BigInt(1);function qe(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function mo(r){if(typeof r=="bigint"){if(!ho(r))throw new RangeError("positive bigint expected, got "+r)}else Ai(r);return r}function ze(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=mo(r).toString(16);return e.length&1?"0"+e:e}function Xu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?po:BigInt("0x"+r)}function jt(r){return Xu(uo(r))}function et(r){return Xu(uo(gn(Oe(r)).reverse()))}function yo(r,e){if(vt(e),e===0)throw new RangeError("zero length");r=mo(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return fn(t.padStart(e*2,"0"))}function Ti(r,e){return yo(r,e).reverse()}function Qu(r,e){if(r=z(r),e=z(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function gn(r){return Uint8Array.from(z(r))}function go(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var ho=r=>typeof r=="bigint"&&po<=r;function zp(r,e,t){return ho(r)&&ho(e)&&ho(t)&&e<=r&&r<t}function Lr(r,e,t,n){if(!zp(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Br(r){if(r<po)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>po;r>>=_i,e+=1);return e}var bn=r=>(_i<<BigInt(r))-_i;function Ju(r,e,t){if(vt(r,"hashLen"),vt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),s=Uint8Array.of(),o=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},m=(...h)=>t(u,de(c,...h)),d=(h=s)=>{u=m(o,h),c=m(),h.length!==0&&(u=m(i,h),c=m())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,g=[];for(;h<e;){c=m();let E=c.slice();g.push(E),h+=c.length}return de(...g)};return(h,g)=>{f(),d(h);let E;for(;(E=g(p()))===void 0;)d();return f(),E}}function Ve(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let c=r[o];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}var Di=()=>{throw new Error("not implemented")};var be=BigInt(0),ae=BigInt(1),Wt=BigInt(2),nl=BigInt(3),ol=BigInt(4),sl=BigInt(5),Vp=BigInt(7),il=BigInt(8),Hp=BigInt(9),al=BigInt(16);function ue(r,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=be?t:e+t}function te(r,e,t){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >be;)n*=n,n%=t;return n}function el(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=ue(r,e),n=e,s=be,o=ae,i=ae,a=be;for(;t!==be;){let u=n/t,l=n-t*u,f=s-i*u,m=o-a*u;n=t,t=l,s=i,o=a,i=f,a=m}if(n!==ae)throw new Error("invert: does not exist");return ue(s,e)}function Ii(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function cl(r,e){let t=r,n=(t.ORDER+ae)/ol,s=t.pow(e,n);return Ii(t,s,e),s}function $p(r,e){let t=r,n=(t.ORDER-sl)/il,s=t.mul(e,Wt),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,Wt),o),c=t.mul(i,t.sub(a,t.ONE));return Ii(t,c,e),c}function jp(r){let e=Rr(r),t=ul(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+Vp)/al;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),m=u.mul(l,s),d=u.mul(l,o),p=u.eql(u.sqr(f),c),b=u.eql(u.sqr(m),c);l=u.cmov(l,f,p),f=u.cmov(d,m,b);let h=u.eql(u.sqr(f),c),g=u.cmov(l,f,h);return Ii(u,g,c),g})}function ul(r){if(r<nl)throw new Error("sqrt is not defined for small field");let e=r-ae,t=0;for(;e%Wt===be;)e/=Wt,t++;let n=Wt,s=Rr(r);for(;tl(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return cl;let o=s.pow(n,e),i=(e+ae)/Wt;return function(c,u){let l=c;if(l.is0(u))return u;if(tl(l,u)!==1)throw new Error("Cannot find square root");let f=t,m=l.mul(l.ONE,o),d=l.pow(u,e),p=l.pow(u,i);for(;!l.eql(d,l.ONE);){if(l.is0(d))return l.ZERO;let b=1,h=l.sqr(d);for(;!l.eql(h,l.ONE);)if(b++,h=l.sqr(h),b===f)throw new Error("Cannot find square root");let g=ae<<BigInt(f-b-1),E=l.pow(m,g);f=b,m=l.sqr(E),d=l.mul(d,m),p=l.mul(p,E)}return p}}function Wp(r){return r%ol===nl?cl:r%il===sl?$p:r%al===Hp?jp(r):ul(r)}var ht=(r,e)=>(ue(r,e)&ae)===ae,Gp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ci(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Gp.reduce((n,s)=>(n[s]="function",n),e);if(Ve(r,t),ze(r.BYTES,"BYTES"),ze(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Yp(r,e,t){let n=r;if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return n.ONE;if(t===ae)return e;let s=n.ONE,o=e;for(;t>be;)t&ae&&(s=n.mul(s,o)),o=n.sqr(o),t>>=ae;return s}function wn(r,e,t=!1){let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,u)=>n.is0(c)?a:(s[u]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,u)=>n.is0(c)?a:(s[u]=n.mul(a,s[u]),n.mul(a,c)),i),s}function tl(r,e){let t=r,n=(t.ORDER-ae)/Wt,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Zp(r,e){if(e!==void 0&&Ai(e),r<=be)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=Br(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var rl=new WeakMap,bo=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=ae;_lengths;_mod;constructor(e,t={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=Zp(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return Yp(this,e,t)}div(e,t){return ue(e*el(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 el(e,this.ORDER)}sqrt(e){let t=rl.get(this);return t||rl.set(this,t=Wp(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ti(e,this.BYTES):yo(e,this.BYTES)}fromBytes(e,t=!1){z(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(s);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?et(e):jt(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return wn(this,e)}cmov(e,t,n){return qe(n,"condition"),n?t:e}};Object.freeze(bo.prototype);function Rr(r,e={}){return new bo(r,e)}function ll(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ae)throw new Error("field order must be greater than 1");let e=Br(r-ae);return Math.ceil(e/8)}function Li(r){let e=ll(r);return e+Math.ceil(e/2)}function Bi(r,e,t=!1){z(r);let n=r.length,s=ll(e),o=Math.max(Li(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?et(r):jt(r),a=ue(i,e-ae)+ae;return t?Ti(a,s):yo(a,s)}var Or=BigInt(0),Gt=BigInt(1);function xn(r,e){let t=e.negate();return r?t:e}function Yt(r,e){let t=wn(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function pl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ri(r,e){pl(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=bn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function fl(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Gt);let u=e*n,l=u+Math.abs(a)-1,f=a===0,m=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:m,isNegF:d,offsetF:u}}var Oi=new WeakMap,ml=new WeakMap;function Pi(r){return ml.get(r)||1}function dl(r){if(r!==Or)throw new Error("invalid wNAF")}var Pr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>Or;)t&Gt&&(n=n.add(s)),s=s.double(),t>>=Gt;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Ri(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let u=1;u<s;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Ri(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:m,offsetF:d}=fl(n,a,i);n=c,l?o=o.add(xn(m,t[d])):s=s.add(xn(f,t[u]))}return dl(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Ri(e,this.bits);for(let i=0;i<o.windows&&n!==Or;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=fl(n,i,o);if(n=a,!u){let f=t[c];s=s.add(l?f.negate():f)}}return dl(n),s}getPrecomputes(e,t,n){let s=Oi.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Oi.set(t,s))),s}cached(e,t,n){let s=Pi(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=Pi(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){pl(t,this.bits),ml.set(e,t),Oi.delete(e)}hasCache(e){return Pi(e)!==1}};function yl(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>Or||n>Or;)t&Gt&&(o=o.add(s)),n&Gt&&(i=i.add(s)),s=s.double(),t>>=Gt,n>>=Gt;return{p1:o,p2:i}}function hl(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ci(e),e}else return Rr(r,{isLE:t})}function wo(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Or))throw new Error(`CURVE.${c} must be positive bigint`)}let s=hl(e.p,t.Fp,n),o=hl(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function xo(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var Dt=BigInt(0),me=BigInt(1),Ni=BigInt(2),Xp=BigInt(8);function Qp(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function gl(r,e={}){let t=e,n=wo("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;Ve(t,{},{uvRatio:"function"});let c=Ni<<BigInt(o.BYTES*8)-me,u=b=>s.create(b),l=t.uvRatio===void 0?(b,h)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,h))}}catch{return{isValid:!1,value:Dt}}}:t.uvRatio;if(!Qp(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(b,h,g=!1){let E=g?me:Dt;return Lr("coordinate "+b,h,E,c),h}function m(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,me,u(i.Gx*i.Gy));static ZERO=new d(Dt,me,me,Dt);static Fp=s;static Fn=o;X;Y;Z;T;constructor(h,g,E,v){this.X=f("x",h),this.Y=f("y",g),this.Z=f("z",E,!0),this.T=f("t",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:g,y:E}=h||{};return f("x",g),f("y",E),new d(g,E,me,u(g*E))}static fromBytes(h,g=!1){let E=s.BYTES,{a:v,d:I}=i;h=gn(z(h,E,"point")),qe(g,"zip215");let D=gn(h),P=h[E-1];D[E-1]=P&-129;let B=et(D),T=g?c:s.ORDER;Lr("point.y",B,Dt,T);let U=u(B*B),Y=u(U-me),k=u(I*U-v),{isValid:y,value:w}=l(Y,k);if(!y)throw new Error("bad point: invalid y coordinate");let _=(w&me)===me,S=(P&128)!==0;if(!g&&w===Dt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==_&&(w=u(-w)),d.fromAffine({x:w,y:B})}static fromHex(h,g=!1){return d.fromBytes(Cr(h),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,g=!0){return p.createCache(this,h),g||this.multiply(Ni),this}assertValidity(){let h=this,{a:g,d:E}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:v,Y:I,Z:D,T:P}=h,B=u(v*v),T=u(I*I),U=u(D*D),Y=u(U*U),k=u(B*g),y=u(U*u(k+T)),w=u(Y+u(E*u(B*T)));if(y!==w)throw new Error("bad point: equation left != right (1)");let _=u(v*I),S=u(D*P);if(_!==S)throw new Error("bad point: equation left != right (2)")}equals(h){m(h);let{X:g,Y:E,Z:v}=this,{X:I,Y:D,Z:P}=h,B=u(g*P),T=u(I*v),U=u(E*P),Y=u(D*v);return B===T&&U===Y}is0(){return this.equals(d.ZERO)}negate(){return new d(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:h}=i,{X:g,Y:E,Z:v}=this,I=u(g*g),D=u(E*E),P=u(Ni*u(v*v)),B=u(h*I),T=g+E,U=u(u(T*T)-I-D),Y=B+D,k=Y-P,y=B-D,w=u(U*k),_=u(Y*y),S=u(U*y),x=u(k*Y);return new d(w,_,x,S)}add(h){m(h);let{a:g,d:E}=i,{X:v,Y:I,Z:D,T:P}=this,{X:B,Y:T,Z:U,T:Y}=h,k=u(v*B),y=u(I*T),w=u(P*E*Y),_=u(D*U),S=u((v+I)*(B+T)-k-y),x=_-w,A=_+w,L=u(y-g*k),C=u(S*x),R=u(A*L),N=u(S*L),q=u(x*A);return new d(C,R,q,N)}subtract(h){return m(h),this.add(h.negate())}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=p.cached(this,h,v=>Yt(d,v));return Yt(d,[g,E])[0]}multiplyUnsafe(h){if(!o.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Dt?d.ZERO:this.is0()||h===me?this:p.unsafe(this,h,g=>Yt(d,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(h){let g=this,E=h,{X:v,Y:I,Z:D}=g,P=g.is0();E==null&&(E=P?Xp:s.inv(D));let B=u(v*E),T=u(I*E),U=s.mul(D,E);if(P)return{x:Dt,y:me};if(U!==me)throw new Error("invZ was invalid");return{x:B,y:T}}clearCofactor(){return a===me?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:g}=this.toAffine(),E=s.toBytes(g);return E[E.length-1]|=h&me?128:0,E}toHex(){return Ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new Pr(d,o.BITS);return o.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Eo=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Di()}static fromHex(e){Di()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Ir(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function bl(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;Ve(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(ze(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=s.randomBytes===void 0?mn:s.randomBytes,m=s.adjustScalarBytes===void 0?y=>y:s.adjustScalarBytes,d=s.domain===void 0?(y,w,_)=>{if(qe(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return y}:s.domain;function p(y){return c.create(et(y))}function b(y){let w=B.secretKey;z(y,B.secretKey,"secretKey");let _=z(n(y),2*w,"hashedSecretKey"),S=m(_.slice(0,w)),x=_.slice(w,2*w),A=p(S);return{head:S,prefix:x,scalar:A}}function h(y){let{head:w,prefix:_,scalar:S}=b(y),x=i.multiply(S),A=x.toBytes();return{head:w,prefix:_,scalar:S,point:x,pointBytes:A}}function g(y){return h(y).pointBytes}function E(y=Uint8Array.of(),...w){let _=de(...w);return p(n(d(_,z(y,void 0,"context"),!!o)))}function v(y,w,_={}){y=z(y,void 0,"message"),o&&(y=o(y));let{prefix:S,scalar:x,pointBytes:A}=h(w),L=E(_.context,S,y),C=i.multiply(L).toBytes(),R=E(_.context,C,A,y),N=c.create(L+R*x);if(!c.isValid(N))throw new Error("sign failed: invalid s");let q=de(C,c.toBytes(N));return z(q,B.signature,"result")}let I={zip215:s.zip215};function D(y,w,_,S=I){let{context:x}=S,A=S.zip215===void 0?!!I.zip215:S.zip215,L=B.signature;y=z(y,L,"signature"),w=z(w,void 0,"message"),_=z(_,B.publicKey,"publicKey"),A!==void 0&&qe(A,"zip215"),o&&(w=o(w));let C=L/2,R=y.subarray(0,C),N=et(y.subarray(C,L)),q,$,F;try{q=r.fromBytes(_,A),$=r.fromBytes(R,A),F=i.multiplyUnsafe(N)}catch{return!1}if(!A&&q.isSmallOrder())return!1;let fe=E(x,R,_,w);return $.add(q.multiplyUnsafe(fe)).subtract(F).clearCofactor().is0()}let P=a.BYTES,B={secretKey:P,publicKey:P,signature:2*P,seed:P};function T(y){return y=y===void 0?f(B.seed):y,z(y,B.seed,"seed")}function U(y){return $t(y)&&y.length===B.secretKey}function Y(y,w){try{return!!r.fromBytes(y,w===void 0?I.zip215:w)}catch{return!1}}let k={getExtendedPublicKey:h,randomSecretKey:T,isValidSecretKey:U,isValidPublicKey:Y,toMontgomery(y){let{y:w}=r.fromBytes(y),_=B.publicKey,S=_===32;if(!S&&_!==57)throw new Error("only defined for 25519 and 448");let x=S?a.div(me+w,me-w):a.div(w-me,w+me);return a.toBytes(x)},toMontgomerySecret(y){let w=B.secretKey;z(y,w);let _=n(y.subarray(0,w));return m(_).subarray(0,w)}};return Object.freeze(B),Object.freeze(k),Object.freeze({keygen:xo(T,g),getPublicKey:g,sign:v,verify:D,utils:k,Point:r,lengths:B})}function En(r,e){if(ze(r),ze(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Jp(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function em(r){if(!$t(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?go(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ui(r,e,t,n){z(r),ze(t),e=em(e),e.length>255&&(e=n(de(go("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=n,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=de(e,En(e.length,1)),c=new Uint8Array(o),u=En(t,2),l=new Array(i),f=n(de(c,r,u,En(0,1),a));l[0]=n(de(f,En(1,1),a));for(let d=1;d<i;d++){let p=[Jp(f,l[d-1]),En(d+1,1),a];l[d]=n(de(...p))}return de(...l).slice(0,t)}var wl="HashToScalar-";var tm=BigInt(0),pt=BigInt(1),xl=BigInt(2);var rm=BigInt(5),nm=BigInt(8),Nr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ki={p:Nr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:nm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function om(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Nr,a=r*r%o*r%o,c=te(a,xl,o)*a%o,u=te(c,pt,o)*r%o,l=te(u,rm,o)*u%o,f=te(l,e,o)*l%o,m=te(f,t,o)*f%o,d=te(m,n,o)*m%o,p=te(d,s,o)*d%o,b=te(p,s,o)*d%o,h=te(b,e,o)*l%o;return{pow_p_5_8:te(h,xl,o)*r%o,b2:a}}function sm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ki=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function qi(r,e){let t=Nr,n=ue(e*e*e,t),s=ue(n*n*e,t),o=om(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,u=ue(i*ki,t),l=a===r,f=a===ue(-r,t),m=a===ue(-r*ki,t);return l&&(i=c),(f||m)&&(i=u),ht(i,t)&&(i=ue(-i,t)),{isValid:l||f,value:i}}var Ct=gl(Ki,{uvRatio:qi}),It=Ct.Fp,vl=Ct.Fn;function im(r){return bl(Ct,fo,Object.assign({adjustScalarBytes:sm,zip215:!0},r))}var _l=im({});var Mi=ki,am=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),cm=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),um=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),lm=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),El=r=>qi(pt,r),fm=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fi=r=>It.create(et(r)&fm);function Sl(r){let{d:e}=Ki,t=Nr,n=g=>It.create(g),s=n(Mi*r*r),o=n((s+pt)*um),i=BigInt(-1),a=n((i-e*s)*n(s+e)),{isValid:c,value:u}=qi(o,a),l=n(u*r);ht(l,t)||(l=n(-l)),c||(u=l),c||(i=s);let f=n(i*(s-pt)*lm-a),m=u*u,d=n((u+u)*a),p=n(f*am),b=n(pt-m),h=n(pt+m);return new Ct(n(d*h),n(b*p),n(p*h),n(d*b))}var Lt=class r extends Eo{static BASE=new r(Ct.BASE);static ZERO=new r(Ct.ZERO);static Fp=It;static Fn=vl;constructor(e){super(e)}static fromAffine(e){return new r(Ct.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Oe(e,32);let{a:t,d:n}=Ki,s=Nr,o=I=>It.create(I),i=Fi(e);if(!Qu(It.toBytes(i),e)||ht(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(pt+t*a),u=o(pt-t*a),l=o(c*c),f=o(u*u),m=o(t*n*l-f),{isValid:d,value:p}=El(o(m*f)),b=o(p*u),h=o(p*b*m),g=o((i+i)*b);ht(g,s)&&(g=o(-g));let E=o(c*h),v=o(g*E);if(!d||ht(v,s)||E===tm)throw new Error("invalid ristretto255 encoding 2");return new r(new Ct(g,E,pt,v))}static fromHex(e){return r.fromBytes(fn(e))}toBytes(){let{X:e,Y:t,Z:n,T:s}=this.ep,o=Nr,i=h=>It.create(h),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=El(i(a*u)),f=i(l*a),m=i(l*c),d=i(f*m*s),p;if(ht(s*d,o)){let h=i(t*Mi),g=i(e*Mi);e=h,t=g,p=i(f*cm)}else p=m;ht(e*d,o)&&(t=i(-t));let b=i((n-t)*p);return ht(b,o)&&(b=i(-b)),It.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:s,Y:o}=e.ep,i=u=>It.create(u),a=i(t*o)===i(n*s),c=i(n*o)===i(t*s);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Lt.BASE);Object.freeze(Lt.ZERO);Object.freeze(Lt.prototype);Object.freeze(Lt);var dm=Object.freeze({Point:Lt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ui(r,t,64,fo);return dm.deriveToCurve(n)},hashToScalar(r,e={DST:wl}){let t=Ui(r,e.DST,64,fo);return vl.create(et(t))},deriveToCurve(r){Oe(r,64);let e=Fi(r.subarray(0,32)),t=Sl(e),n=Fi(r.subarray(32,64)),s=Sl(n);return new Lt(t.add(s))}});var Sn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},So=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ke={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new So("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 vo=32;var zi,hm=(async()=>{try{return await ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function pm(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await ke.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await ke.get().subtle.verify({name:"Ed25519"},n,Ze(e),Ze(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function mm(r,e,t){return _l.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Al(r,e,t){return zi==null&&(zi=await hm),zi?pm(r,e,t):mm(r,e,t)}function _o(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ao=class{type="Ed25519";raw;constructor(e){this.raw=Vi(e,vo)}toMultihash(){return Fe.digest(Qe(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:xe(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=Al(this.raw,t,e);return _o(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Hi(r){return r=Vi(r,vo),new Ao(r)}function Vi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function Dl(r=0){return new Uint8Array(r)}var gm=Math.pow(2,7),bm=Math.pow(2,14),wm=Math.pow(2,21),$i=Math.pow(2,28),ji=Math.pow(2,35),Wi=Math.pow(2,42),Gi=Math.pow(2,49),W=128,Ee=127;function Ie(r){if(r<gm)return 1;if(r<bm)return 2;if(r<wm)return 3;if(r<$i)return 4;if(r<ji)return 5;if(r<Wi)return 6;if(r<Gi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ur(r,e,t=0){switch(Ie(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function xm(r,e,t=0){switch(Ie(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Yi(r,e){let t=r[e],n=0;if(n+=t&Ee,t<W||(t=r[e+1],n+=(t&Ee)<<7,t<W)||(t=r[e+2],n+=(t&Ee)<<14,t<W)||(t=r[e+3],n+=(t&Ee)<<21,t<W)||(t=r[e+4],n+=(t&Ee)*$i,t<W)||(t=r[e+5],n+=(t&Ee)*ji,t<W)||(t=r[e+6],n+=(t&Ee)*Wi,t<W)||(t=r[e+7],n+=(t&Ee)*Gi,t<W))return n;throw new RangeError("Could not decode varint")}function Em(r,e){let t=r.get(e),n=0;if(n+=t&Ee,t<W||(t=r.get(e+1),n+=(t&Ee)<<7,t<W)||(t=r.get(e+2),n+=(t&Ee)<<14,t<W)||(t=r.get(e+3),n+=(t&Ee)<<21,t<W)||(t=r.get(e+4),n+=(t&Ee)*$i,t<W)||(t=r.get(e+5),n+=(t&Ee)*ji,t<W)||(t=r.get(e+6),n+=(t&Ee)*Wi,t<W)||(t=r.get(e+7),n+=(t&Ee)*Gi,t<W))return n;throw new RangeError("Could not decode varint")}function kr(r,e,t=0){return e==null&&(e=Dl(Ie(r))),e instanceof Uint8Array?Ur(r,e,t):xm(r,e,t)}function vn(r,e=0){return r instanceof Uint8Array?Yi(r,e):Em(r,e)}var Xi=new Float32Array([-0]),Bt=new Uint8Array(Xi.buffer);function Il(r,e,t){Xi[0]=r,e[t]=Bt[0],e[t+1]=Bt[1],e[t+2]=Bt[2],e[t+3]=Bt[3]}function Cl(r,e){return Bt[0]=r[e],Bt[1]=r[e+1],Bt[2]=r[e+2],Bt[3]=r[e+3],Xi[0]}var Qi=new Float64Array([-0]),Se=new Uint8Array(Qi.buffer);function Ll(r,e,t){Qi[0]=r,e[t]=Se[0],e[t+1]=Se[1],e[t+2]=Se[2],e[t+3]=Se[3],e[t+4]=Se[4],e[t+5]=Se[5],e[t+6]=Se[6],e[t+7]=Se[7]}function Bl(r,e){return Se[0]=r[e],Se[1]=r[e+1],Se[2]=r[e+2],Se[3]=r[e+3],Se[4]=r[e+4],Se[5]=r[e+5],Se[6]=r[e+6],Se[7]=r[e+7],Qi[0]}var Sm=BigInt(Number.MAX_SAFE_INTEGER),vm=BigInt(Number.MIN_SAFE_INTEGER),Pe=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 Zt;if(e<Sm&&e>vm)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Rl&&(s=0n,++n>Rl&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Zt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Zt}},Zt=new Pe(0,0);Zt.toBigInt=function(){return 0n};Zt.zzEncode=Zt.zzDecode=function(){return this};Zt.length=function(){return 1};var Rl=4294967296n;function Ol(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 Pl(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Ji(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function He(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function To(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ea=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,He(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 He(this,4);return To(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return To(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=Cl(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=Bl(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 He(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Pl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw He(this,e);this.pos+=e}else do if(this.pos>=this.len)throw He(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 Pe(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 He(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 He(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 He(this,8);let e=To(this.buf,this.pos+=4),t=To(this.buf,this.pos+=4);return new Pe(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=Yi(this.buf,this.pos);return this.pos+=Ie(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 _n(r){return new ea(r instanceof Uint8Array?r:r.subarray())}function Ce(r,e,t){let n=_n(r);return e.decode(n,void 0,t)}function Xt(r=0){return new Uint8Array(r)}var ta={};Q(ta,{base10:()=>_m});var _m=wt({prefix:"9",name:"base10",alphabet:"0123456789"});var ra={};Q(ra,{base16:()=>Am,base16upper:()=>Tm});var Am=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Tm=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var na={};Q(na,{base2:()=>Dm});var Dm=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oa={};Q(oa,{base256emoji:()=>Rm});var Ul=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}"),Im=Ul.reduce((r,e,t)=>(r[t]=e,r),[]),Cm=Ul.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Lm(r){return r.reduce((e,t)=>(e+=Im[t],e),"")}function Bm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Cm[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Rm=mr({prefix:"\u{1F680}",name:"base256emoji",encode:Lm,decode:Bm});var ia={};Q(ia,{base64:()=>Om,base64pad:()=>Pm,base64url:()=>sa,base64urlpad:()=>Nm});var Om=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pm=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sa=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nm=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var aa={};Q(aa,{base8:()=>Um});var Um=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ca={};Q(ca,{identity:()=>km});var km=mr({prefix:"\0",name:"identity",encode:r=>Yc(r),decode:r=>Gc(r)});var Dx=new TextEncoder,Ix=new TextDecoder;var fa={};Q(fa,{sha256:()=>Mr,sha512:()=>qm});var Km=20;function la({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ua(r,e,t,n,s)}var ua=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Km,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?kl(n,this.code,t?.truncate):n.then(s=>kl(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function kl(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 Ge(e,r)}function Fl(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Mr=la({name:"sha2-256",code:18,encode:Fl("SHA-256")}),qm=la({name:"sha2-512",code:19,encode:Fl("SHA-512")});var Rt={...ca,...na,...aa,...ta,...ra,...Os,...Ps,...Rs,...ia,...oa},Kx={...fa,...ks};function ql(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Kl=ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),da=ql("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=Xt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),zm={utf8:Kl,"utf-8":Kl,hex:Rt.base16,latin1:da,ascii:da,binary:da,...Rt},zl=zm;function Vl(r,e="utf8"){let t=zl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ha(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Xt(i);s+i>e&&(n=Xt(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Qt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function pa(){}var ya=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Vm=ha();function Hm(r){return globalThis.Buffer!=null?Xt(r):Vm(r)}var Tn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Qt(pa,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Qt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ga((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(Do,10,Pe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pe.fromBigInt(e);return this._push(Do,t.length(),t)}uint64Number(e){return this._push(Ur,Ie(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=Pe.fromBigInt(e).zzEncode();return this._push(Do,t.length(),t)}sint64Number(e){let t=Pe.fromNumber(e).zzEncode();return this._push(Do,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ma,1,e?1:0)}fixed32(e){return this._push(An,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pe.fromBigInt(e);return this._push(An,4,t.lo)._push(An,4,t.hi)}fixed64Number(e){let t=Pe.fromNumber(e);return this._push(An,4,t.lo)._push(An,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(Il,4,e)}double(e){return this._push(Ll,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ma,1,0):this.uint32(t)._push(jm,t,e)}string(e){let t=Ol(e);return t!==0?this.uint32(t)._push(Ji,t,e):this._push(ma,1,0)}fork(){return this.states=new ya(this),this.head=this.tail=new Qt(pa,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 Qt(pa,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=Hm(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function ma(r,e,t){e[t]=r&255}function $m(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ga=class extends Qt{next;constructor(e,t){super($m,e,t),this.next=void 0}};function Do(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 An(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 jm(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Tn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Wm,e,r),this},Tn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Gm,e,r),this});function Wm(r,e,t){e.set(r,t)}function Gm(r,e,t){r.length<40?Ji(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Vl(r),t)}function ba(){return new Tn}function Le(r,e){let t=ba();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Be(r,e,t){let n=_n(r);yield*e.stream(n,void 0,"$",t)}var Io={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Co(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function Jt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return Co("enum",Io.VARINT,t,n,s)}function Re(r,e,t){return Co("message",Io.LENGTH_DELIMITED,r,e,t)}var er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ne||(ne={}));var wa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(wa||(wa={}));(function(r){r.codec=()=>Jt(wa)})(ne||(ne={}));var tt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(tt||(tt={}));var xa;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(xa||(xa={}));var In={};Q(In,{MAX_RSA_KEY_SIZE:()=>Ea,generateRSAKeyPair:()=>Gl,jwkToJWKKeyPair:()=>Yl,jwkToPkcs1:()=>Qm,jwkToPkix:()=>Aa,jwkToRSAPrivateKey:()=>Ca,pkcs1MessageToJwk:()=>va,pkcs1MessageToRSAPrivateKey:()=>Ta,pkcs1ToJwk:()=>Xm,pkcs1ToRSAPrivateKey:()=>Wl,pkixMessageToJwk:()=>_a,pkixMessageToRSAPublicKey:()=>Ia,pkixToJwk:()=>Jm,pkixToRSAPublicKey:()=>Da});var Fr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=In.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:xe(this.raw,e.raw)}verify(e,t,n){return jl(this.jwk,t,e,n)}},Dn=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=In.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:xe(this.raw,e.raw)}sign(e,t){return $l(this.jwk,e,t)}};var Ea=8192,Sa=18,Ym=1062,Zm=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Xm(r){let e=ut(r);return va(e)}function va(r){return{n:J(r[1],"base64url"),e:J(r[2],"base64url"),d:J(r[3],"base64url"),p:J(r[4],"base64url"),q:J(r[5],"base64url"),dp:J(r[6],"base64url"),dq:J(r[7],"base64url"),qi:J(r[8],"base64url"),kty:"RSA"}}function Qm(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 oe("JWK was missing components");return St([De(Uint8Array.from([0])),De(j(r.n,"base64url")),De(j(r.e,"base64url")),De(j(r.d,"base64url")),De(j(r.p,"base64url")),De(j(r.q,"base64url")),De(j(r.dp,"base64url")),De(j(r.dq,"base64url")),De(j(r.qi,"base64url"))]).subarray()}function Jm(r){let e=ut(r,{offset:0});return _a(e)}function _a(r){let e=ut(r[1],{offset:0});return{kty:"RSA",n:J(e[0],"base64url"),e:J(e[1],"base64url")}}function Aa(r){if(r.n==null||r.e==null)throw new oe("JWK was missing components");return St([Zm,so(St([De(j(r.n,"base64url")),De(j(r.e,"base64url"))]))]).subarray()}function Wl(r){let e=ut(r);return Ta(e)}function Ta(r){let e=va(r);return Ca(e)}function Da(r,e){if(r.byteLength>=Ym)throw new dr("Key size is too large");let t=ut(r,{offset:0});return Ia(t,r,e)}function Ia(r,e,t){let n=_a(r);if(t==null){let s=Dr(tt.encode({Type:ne.RSA,Data:e}));t=Ge(Sa,s)}return new Fr(n,t)}function Ca(r){if(Xl(r)>Ea)throw new oe("Key size is too large");let e=Yl(r),t=Dr(tt.encode({Type:ne.RSA,Data:Aa(e.publicKey)})),n=Ge(Sa,t);return new Dn(e.privateKey,new Fr(e.publicKey,n))}async function Gl(r){if(r>Ea)throw new oe("Key size is too large");let e=await Zl(r),t=Dr(tt.encode({Type:ne.RSA,Data:Aa(e.publicKey)})),n=Ge(Sa,t);return new Dn(e.privateKey,new Fr(e.publicKey,n))}function Yl(r){if(r==null)throw new oe("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Zl(r,e){let t=await ke.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 e0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function $l(r,e,t){let n=await ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ze(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function jl(r,e,t,n){let s=await ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,Ze(e),Ze(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function e0(r,e){if(r.privateKey==null||r.publicKey==null)throw new oe("Private and public key are required");let t=await Promise.all([ke.get().subtle.exportKey("jwk",r.privateKey),ke.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Xl(r){if(r.kty!=="RSA")throw new oe("invalid key type");if(r.n==null)throw new oe("invalid key modulus");return j(r.n,"base64url").length*8}var Lo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(io(e),Oe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),ft(s)}update(e){return Tr(this),this.iHash.update(e),this}digestInto(e){Tr(this),ao(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ql=(()=>{let r=((e,t,n)=>new Lo(e,t).update(n).digest());return r.create=(e,t)=>new Lo(e,t),r})();var Jl=(r,e)=>(r+(r>=0?e:-e)/ef)/e;function t0(r,e,t){Lr("scalar",r,rt,t);let[[n,s],[o,i]]=e,a=Jl(i*r,t),c=Jl(-s*r,t),u=r-a*n-c*o,l=-a*s-c*i,f=u<rt,m=l<rt;f&&(u=-u),m&&(l=-l);let d=bn(Math.ceil(Br(t)/2))+Ot;if(u<rt||u>=d||l<rt||l>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:l}}function Ba(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function La(r,e){Ve(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return qe(t.lowS,"lowS"),qe(t.prehash,"prehash"),t.format!==void 0&&Ba(t.format),t}var Ra=class extends Error{constructor(e=""){super(e)}},$e={Err:Ra,_tlv:{encode:(r,e)=>{let{Err:t}=$e;if(ze(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=yn(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?yn(s.length/2|128):"";return yn(r)+o+s+e},decode(r,e){let{Err:t}=$e;e=z(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let 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}=$e;if(mo(r),r<rt)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}=$e;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 jt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=$e,s=z(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=$e,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}};Object.freeze($e._tlv);Object.freeze($e._int);Object.freeze($e);var rt=BigInt(0),Ot=BigInt(1),ef=BigInt(2),Bo=BigInt(3),r0=BigInt(4);function tf(r,e={}){let t=wo("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;Ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=nf(n,s);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(k,y,w){if(u&&y.is0())return Uint8Array.of(0);let{x:_,y:S}=y.toAffine(),x=n.toBytes(_);if(qe(w,"isCompressed"),w){f();let A=!n.isOdd(S);return de(rf(A),x)}else return de(Uint8Array.of(4),x,n.toBytes(S))}function d(k){z(k,void 0,"Point");let{publicKey:y,publicKeyUncompressed:w}=l,_=k.length,S=k[0],x=k.subarray(1);if(u&&_===1&&S===0)return{x:n.ZERO,y:n.ZERO};if(_===y&&(S===2||S===3)){let A=n.fromBytes(x);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let L=h(A),C;try{C=n.sqrt(L)}catch(q){let $=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+$)}f();let R=n.isOdd(C);return(S&1)===1!==R&&(C=n.neg(C)),{x:A,y:C}}else if(_===w&&S===4){let A=n.BYTES,L=n.fromBytes(x.subarray(0,A)),C=n.fromBytes(x.subarray(A,A*2));if(!g(L,C))throw new Error("bad point: is not on curve");return{x:L,y:C}}else throw new Error(`bad point: got length ${_}, expected compressed=${y} or uncompressed=${w}`)}let p=e.toBytes===void 0?m:e.toBytes,b=e.fromBytes===void 0?d:e.fromBytes;function h(k){let y=n.sqr(k),w=n.mul(y,k);return n.add(n.add(w,n.mul(k,o.a)),o.b)}function g(k,y){let w=n.sqr(y),_=h(k);return n.eql(w,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(o.a,Bo),r0),v=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(E,v)))throw new Error("bad curve params: a or b");function I(k,y,w=!1){if(!n.isValid(y)||w&&n.is0(y))throw new Error(`bad point coordinate ${k}`);return y}function D(k){if(!(k instanceof T))throw new Error("Weierstrass Point expected")}function P(k){if(!c||!c.basises)throw new Error("no endo");return t0(k,c.basises,s.ORDER)}function B(k,y,w,_,S){return w=new T(n.mul(w.X,k),w.Y,w.Z),y=xn(_,y),w=xn(S,w),y.add(w)}class T{static BASE=new T(o.Gx,o.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(y,w,_){this.X=I("x",y),this.Y=I("y",w,!0),this.Z=I("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){let{x:w,y:_}=y||{};if(!y||!n.isValid(w)||!n.isValid(_))throw new Error("invalid affine point");if(y instanceof T)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(_)?T.ZERO:new T(w,_,n.ONE)}static fromBytes(y){let w=T.fromAffine(b(z(y,void 0,"point")));return w.assertValidity(),w}static fromHex(y){return T.fromBytes(Cr(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,w=!0){return Y.createCache(this,y),w||this.multiply(Bo),this}assertValidity(){let y=this;if(y.is0()){if(e.allowInfinityPoint&&n.is0(y.X)&&n.eql(y.Y,n.ONE)&&n.is0(y.Z))return;throw new Error("bad point: ZERO")}let{x:w,y:_}=y.toAffine();if(!n.isValid(w)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!g(w,_))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(y)}equals(y){D(y);let{X:w,Y:_,Z:S}=this,{X:x,Y:A,Z:L}=y,C=n.eql(n.mul(w,L),n.mul(x,S)),R=n.eql(n.mul(_,L),n.mul(A,S));return C&&R}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:y,b:w}=o,_=n.mul(w,Bo),{X:S,Y:x,Z:A}=this,L=n.ZERO,C=n.ZERO,R=n.ZERO,N=n.mul(S,S),q=n.mul(x,x),$=n.mul(A,A),F=n.mul(S,x);return F=n.add(F,F),R=n.mul(S,A),R=n.add(R,R),L=n.mul(y,R),C=n.mul(_,$),C=n.add(L,C),L=n.sub(q,C),C=n.add(q,C),C=n.mul(L,C),L=n.mul(F,L),R=n.mul(_,R),$=n.mul(y,$),F=n.sub(N,$),F=n.mul(y,F),F=n.add(F,R),R=n.add(N,N),N=n.add(R,N),N=n.add(N,$),N=n.mul(N,F),C=n.add(C,N),$=n.mul(x,A),$=n.add($,$),N=n.mul($,F),L=n.sub(L,N),R=n.mul($,q),R=n.add(R,R),R=n.add(R,R),new T(L,C,R)}add(y){D(y);let{X:w,Y:_,Z:S}=this,{X:x,Y:A,Z:L}=y,C=n.ZERO,R=n.ZERO,N=n.ZERO,q=o.a,$=n.mul(o.b,Bo),F=n.mul(w,x),fe=n.mul(_,A),he=n.mul(S,L),pe=n.add(w,_),ce=n.add(x,A);pe=n.mul(pe,ce),ce=n.add(F,fe),pe=n.sub(pe,ce),ce=n.add(w,S);let _e=n.add(x,L);return ce=n.mul(ce,_e),_e=n.add(F,he),ce=n.sub(ce,_e),_e=n.add(_,S),C=n.add(A,L),_e=n.mul(_e,C),C=n.add(fe,he),_e=n.sub(_e,C),N=n.mul(q,ce),C=n.mul($,he),N=n.add(C,N),C=n.sub(fe,N),N=n.add(fe,N),R=n.mul(C,N),fe=n.add(F,F),fe=n.add(fe,F),he=n.mul(q,he),ce=n.mul($,ce),fe=n.add(fe,he),he=n.sub(F,he),he=n.mul(q,he),ce=n.add(ce,he),F=n.mul(fe,ce),R=n.add(R,F),F=n.mul(_e,ce),C=n.mul(pe,C),C=n.sub(C,F),F=n.mul(pe,fe),N=n.mul(_e,N),N=n.add(N,F),new T(C,R,N)}subtract(y){return D(y),this.add(y.negate())}is0(){return this.equals(T.ZERO)}multiply(y){let{endo:w}=e;if(!s.isValidNot0(y))throw new RangeError("invalid scalar: out of range");let _,S,x=A=>Y.cached(this,A,L=>Yt(T,L));if(w){let{k1neg:A,k1:L,k2neg:C,k2:R}=P(y),{p:N,f:q}=x(L),{p:$,f:F}=x(R);S=q.add(F),_=B(w.beta,N,$,A,C)}else{let{p:A,f:L}=x(y);_=A,S=L}return Yt(T,[_,S])[0]}multiplyUnsafe(y){let{endo:w}=e,_=this,S=y;if(!s.isValid(S))throw new RangeError("invalid scalar: out of range");if(S===rt||_.is0())return T.ZERO;if(S===Ot)return _;if(Y.hasCache(this))return this.multiply(S);if(w){let{k1neg:x,k1:A,k2neg:L,k2:C}=P(S),{p1:R,p2:N}=yl(T,_,A,C);return B(w.beta,R,N,x,L)}else return Y.unsafe(_,S)}toAffine(y){let w=this,_=y,{X:S,Y:x,Z:A}=w;if(n.eql(A,n.ONE))return{x:S,y:x};let L=w.is0();_==null&&(_=L?n.ONE:n.inv(A));let C=n.mul(S,_),R=n.mul(x,_),N=n.mul(A,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(N,n.ONE))throw new Error("invZ was invalid");return{x:C,y:R}}isTorsionFree(){let{isTorsionFree:y}=e;return i===Ot?!0:y?y(T,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:y}=e;return i===Ot?this:y?y(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ot?this.is0():this.clearCofactor().is0()}toBytes(y=!0){return qe(y,"isCompressed"),this.assertValidity(),p(T,this,y)}toHex(y=!0){return Ir(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=s.BITS,Y=new Pr(T,e.endo?Math.ceil(U/2):U);return U>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function rf(r){return Uint8Array.of(r?2:3)}function nf(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function n0(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?mn:e.randomBytes,s=Object.assign(nf(r.Fp,t),{seed:Math.max(Li(t.ORDER),16)});function o(d){try{let p=t.fromBytes(d);return t.isValidNot0(p)}catch{return!1}}function i(d,p){let{publicKey:b,publicKeyUncompressed:h}=s;try{let g=d.length;return p===!0&&g!==b||p===!1&&g!==h?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(s.seed):d,Bi(z(d,s.seed,"seed"),t.ORDER)}function c(d,p=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(p)}function u(d){let{secretKey:p,publicKey:b,publicKeyUncompressed:h}=s,g=t._lengths;if(!$t(d))return;let E=z(d,void 0,"key").length,v=E===b||E===h,I=E===p||!!g?.includes(E);if(!(v&&I))return v}function l(d,p,b=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let h=t.fromBytes(d);return r.fromBytes(p).multiply(h).toBytes(b)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=xo(a,c);return Object.freeze(f),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:m,Point:r,utils:f,lengths:s})}function of(r,e,t={}){let n=e;io(n),Ve(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes===void 0?mn:t.randomBytes,o=t.hmac===void 0?(S,x)=>Ql(n,S,x):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:p}=n0(r,t),b={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},h=c*ef+Ot<i.ORDER;function g(S){let x=c>>Ot;return S>x}function E(S,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return x}function v(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function I(S,x){Ba(x);let A=p.signature,L=x==="compact"?A:x==="recovered"?A+1:void 0;return z(S,L)}class D{r;s;recovery;constructor(x,A,L){if(this.r=E("r",x),this.s=E("s",A),L!=null){if(v(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,A=b.format){I(x,A);let L;if(A==="der"){let{r:q,s:$}=$e.toSig(z(x));return new D(q,$)}A==="recovered"&&(L=x[0],A="compact",x=x.subarray(1));let C=p.signature/2,R=x.subarray(0,C),N=x.subarray(C,C*2);return new D(a.fromBytes(R),a.fromBytes(N),L)}static fromHex(x,A){return this.fromBytes(Cr(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new D(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:L}=this,C=this.assertRecovery(),R=C===2||C===3?A+c:A;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let N=i.toBytes(R),q=r.fromBytes(de(rf((C&1)===0),N)),$=a.inv(R),F=B(z(x,void 0,"msgHash")),fe=a.create(-F*$),he=a.create(L*$),pe=r.BASE.multiplyUnsafe(fe).add(q.multiplyUnsafe(he));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return g(this.s)}toBytes(x=b.format){if(Ba(x),x==="der")return Cr($e.hexFromSig(this));let{r:A,s:L}=this,C=a.toBytes(A),R=a.toBytes(L);return x==="recovered"?(v(),de(Uint8Array.of(this.assertRecovery()),C,R)):de(C,R)}toHex(x){return Ir(this.toBytes(x))}}Object.freeze(D.prototype),Object.freeze(D);let P=t.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let A=jt(x),L=x.length*8-u;return L>0?A>>BigInt(L):A}:t.bits2int,B=t.bits2int_modN===void 0?function(x){return a.create(P(x))}:t.bits2int_modN,T=bn(u);function U(S){return Lr("num < 2^"+u,S,rt,T),a.toBytes(S)}function Y(S,x){return z(S,void 0,"message"),x?z(n(S),void 0,"prehashed message"):S}function k(S,x,A){let{lowS:L,prehash:C,extraEntropy:R}=La(A,b);S=Y(S,C);let N=B(S),q=a.fromBytes(x);if(!a.isValidNot0(q))throw new Error("invalid private key");let $=[U(q),U(N)];if(R!=null&&R!==!1){let pe=R===!0?s(p.secretKey):R;$.push(z(pe,void 0,"extraEntropy"))}let F=de(...$),fe=N;function he(pe){let ce=P(pe);if(!a.isValidNot0(ce))return;let _e=a.inv(ce),fr=r.BASE.multiply(ce).toAffine(),Zr=a.create(fr.x);if(Zr===rt)return;let $n=a.create(_e*a.create(fe+Zr*q));if($n===rt)return;let kc=(fr.x===Zr?0:2)|Number(fr.y&Ot),Mc=$n;return L&&g($n)&&(Mc=a.neg($n),kc^=1),new D(Zr,Mc,h?void 0:kc)}return{seed:F,k2sig:he}}function y(S,x,A={}){let{seed:L,k2sig:C}=k(S,x,A);return Ju(n.outputLen,a.BYTES,o)(L,C).toBytes(A.format)}function w(S,x,A,L={}){let{lowS:C,prehash:R,format:N}=La(L,b);if(A=z(A,void 0,"publicKey"),x=Y(x,R),!$t(S)){let q=S instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+q)}I(S,N);try{let q=D.fromBytes(S,N),$=r.fromBytes(A);if(C&&q.hasHighS())return!1;let{r:F,s:fe}=q,he=B(x),pe=a.inv(fe),ce=a.create(he*pe),_e=a.create(F*pe),fr=r.BASE.multiplyUnsafe(ce).add($.multiplyUnsafe(_e));return fr.is0()?!1:a.create(fr.x)===F}catch{return!1}}function _(S,x,A={}){let{prehash:L}=La(A,b);return x=Y(x,L),D.fromBytes(S,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:p,Point:r,sign:y,verify:w,recoverPublicKey:_,Signature:D,hash:n})}var Pa={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},o0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var sf=BigInt(2);function s0(r){let e=Pa.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=te(l,t,e)*l%e,m=te(f,t,e)*l%e,d=te(m,sf,e)*u%e,p=te(d,s,e)*d%e,b=te(p,o,e)*p%e,h=te(b,a,e)*b%e,g=te(h,c,e)*h%e,E=te(g,a,e)*b%e,v=te(E,t,e)*l%e,I=te(v,i,e)*p%e,D=te(I,n,e)*u%e,P=te(D,sf,e);if(!Oa.eql(Oa.sqr(P),r))throw new Error("Cannot find square root");return P}var Oa=Rr(Pa.p,{sqrt:s0}),i0=tf(Pa,{Fp:Oa,endo:o0}),Kr=of(i0,Dr);function af(r,e,t,n){let s=Mr.digest(t instanceof Uint8Array?t:t.subarray());if(_o(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Kr.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Sn(String(o))});try{return n?.signal?.throwIfAborted(),Kr.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Sn(String(o))}}var Ro=class{type="secp256k1";raw;_key;constructor(e){this._key=uf(e),this.raw=cf(this._key)}toMultihash(){return Fe.digest(Qe(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:xe(this.raw,e.raw)}verify(e,t,n){return af(this._key,t,e,n)}};function Na(r){return new Ro(r)}function cf(r){return Kr.Point.fromBytes(r).toBytes()}function uf(r){try{return Kr.Point.fromBytes(r),r}catch(e){throw new dr(String(e))}}function lf(r,e){let{Type:t,Data:n}=tt.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return Da(s,e);case ne.Ed25519:return Hi(s);case ne.secp256k1:return Na(s);case ne.ECDSA:return hi(s);default:throw new hr}}function ff(r){let{Type:e,Data:t}=tt.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return Hi(n);case ne.secp256k1:return Na(n);case ne.ECDSA:return hi(n);default:throw new hr}}function Qe(r){return tt.encode({Type:ne[r.type],Data:r.raw})}var df=Symbol.for("nodejs.util.inspect.custom"),a0=114,Cn=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()})`}[Ds]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(a0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return xe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return xe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[df](){return`PeerId(${this.toString()})`}},Oo=class extends Cn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Po=class extends Cn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},No=class extends Cn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},c0=2336,Ln=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Fe.digest(j(this.url))}[df](){return`PeerId(${this.url})`}[Ds]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(c0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=J(e)),e.toString()===this.toString())}};var u0=114,hf=2336;function Ua(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ye(re.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return l0(le.parse(r));if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ye(e.decode(r))}return qr(t)}function qr(r){if(d0(r))return new Oo({multihash:r});if(f0(r))try{let e=ff(r);if(e.type==="Ed25519")return new Po({multihash:r,publicKey:e});if(e.type==="secp256k1")return new No({multihash:r,publicKey:e})}catch{let t=J(r.digest);return new Ln(new URL(t))}throw new Gn("Supplied PeerID Multihash is invalid")}function l0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==u0&&r.code!==hf)throw new Wn("Supplied PeerID CID is invalid");if(r.code===hf){let e=J(r.multihash.digest);return new Ln(new URL(e))}return qr(r.multihash)}function f0(r){return r.code===Fe.code}function d0(r){return r.code===Mr.code}var Bn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:Te(0),payloadType:Te(0),payload:Te(0),signature:Te(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Bn||(Bn={}));var Uo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Rn=class r{static createFromProtobuf=e=>{let t=Bn.decode(e),n=lf(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=pf(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new Uo("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Bn.encode({publicKey:Qe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:xe(this.marshal(),e.marshal())}async validate(e,t){let n=pf(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},pf=(r,e,t)=>{let n=j(r),s=kr(n.byteLength),o=kr(e.length),i=kr(t.length);return new ee(s,n,o,e,i,t)};function mf(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 ko(r=0){return new Uint8Array(r)}function On(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=ko(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function gf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var yf=gf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ka=gf("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=ko(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),h0={utf8:yf,"utf-8":yf,hex:Rt.base16,latin1:ka,ascii:ka,binary:ka,...Rt},Mo=h0;function Pn(r,e="utf8"){let t=Mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function tr(r,e="utf8"){let t=Mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var we=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},mt=class extends Error{static name="ValidationError";name="ValidationError"},Fo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ko=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var qo=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(o*=e,o+=l,o>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var p0=45,m0=15,zo=new qo;function bf(r){if(!(r.length>m0))return zo.new(r).parseWith(()=>zo.readIPv4Addr())}function wf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>p0))return zo.new(r).parseWith(()=>zo.readIPv6Addr())}function Vo(r){return!!bf(r)}function xf(r){return!!wf(r)}function Fa(r){return e=>tr(e,r)}function Ka(r){return e=>Pn(e,r)}function zr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function rr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ef(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=Pn(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=rr(n);return On([t,s],t.length+s.length)}function Sf(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=xt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=rr(n);return On([t,s],t.length+s.length)}function qa(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=tr(e,"base32"),s=zr(t);return`${n}:${s}`}var za=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new we("Invalid byte value in IP address");e[n]=s}),e},vf=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Vo(t[n]),i;o&&(i=za(t[n]),t[n]=tr(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,tr(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new we("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},_f=function(r){if(r.byteLength!==4)throw new we("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Af=function(r){if(r.byteLength!==16)throw new we("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function Tf(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${r}"`)}}var Ma=Object.values(Rt).map(r=>r.decoder),y0=(function(){let r=Ma[0].or(Ma[1]);return Ma.slice(2).forEach(e=>r=r.or(e)),r})();function Df(r){return y0.decode(r)}function If(r){return e=>r.encoder.encode(e)}function g0(r){if(parseInt(r).toString()!==r)throw new mt("Value must be an integer")}function b0(r){if(r<0)throw new mt("Value must be a positive integer, or zero")}function w0(r){return e=>{if(e>r)throw new mt(`Value must be smaller than or equal to ${r}`)}}function x0(...r){return e=>{for(let t of r)t(e)}}var Nn=x0(g0,b0,w0(65535));var ye=-1,Va=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 Ko(`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)}))}},gt=new Va,P0=[{code:4,name:"ip4",size:32,valueToBytes:za,bytesToValue:_f,validate:r=>{if(!Vo(r))throw new mt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:rr,bytesToValue:zr,validate:Nn},{code:273,name:"udp",size:16,valueToBytes:rr,bytesToValue:zr,validate:Nn},{code:33,name:"dccp",size:16,valueToBytes:rr,bytesToValue:zr,validate:Nn},{code:41,name:"ip6",size:128,valueToBytes:vf,bytesToValue:Af,stringToValue:Tf,validate:r=>{if(!xf(r))throw new mt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:Fa("base10"),valueToBytes:Ka("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:rr,bytesToValue:zr,validate:Nn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:Fa("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ka("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:qa,valueToBytes:Ef},{code:445,name:"onion3",size:296,bytesToValue:qa,valueToBytes:Sf},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:If(sa),valueToBytes:Df},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];P0.forEach(r=>{gt.addProtocol(r)});function Cf(r){let e=[],t=0;for(;t<r.length;){let n=vn(r,t),s=gt.getProtocol(n),o=Ie(n),i=N0(s,r,t+o),a=0;i>0&&s.size===ye&&(a=Ie(i));let c=o+a+i,u={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let l=t+o+a,f=r.subarray(l,l+i);u.value=s.bytesToValue?.(f)??tr(f)}e.push(u),t+=c}return e}function Lf(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=gt.getProtocol(n.code),o=Ie(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Pn(n.value),a=i.byteLength,s.size===ye&&(c=Ie(a)));let u=new Uint8Array(o+c+a),l=0;Ur(n.code,u,l),l+=o,i!=null&&(s.size===ye&&(Ur(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return On(t,e)}function Bf(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=gt.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new we(`Component ${s} 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 we(`Component ${s} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function Rf(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=gt.getProtocol(e.code);if(t==null)throw new we(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function N0(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:vn(e,t)}var U0=Symbol.for("nodejs.util.inspect.custom"),ic=Symbol.for("@multiformats/multiaddr");function k0(r){if(r==null&&(r="/"),Of(r))return r.getComponents();if(r instanceof Uint8Array)return Cf(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Bf(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Go=class r{[ic]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=k0(e),t.validate!==!1&&M0(this)}get bytes(){return this.#r==null&&(this.#r=Lf(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Rf(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Fo(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return mf(this.bytes,e.bytes)}[U0](){return`Multiaddr(${this.toString()})`}};function M0(r){r.getComponents().forEach(e=>{let t=gt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Of(r){return!!r?.[ic]}function Ne(r){return new Go(r)}var ac={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Pf={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Nf=new globalThis.TextEncoder;function F0(r,e){let t=ac[e],n=Pf[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function K0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ac[e],s=Pf[e],o=r;for(;o.length>0;){let i=Nf.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function cc(r,{size:e=32,utf8Buffer:t}={}){if(!ac[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 K0(r,e,t);r=Nf.encode(r)}return F0(r,e)}var Un={hash:r=>Number(cc(r,{size:32})),hashV:(r,e)=>q0(Un.hash(r,e))};function q0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),j(e,"base16")}var uc=64,je=class{fp;h;seed;constructor(e,t,n,s=2){if(s>uc)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=Te(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?xe(this.fp,e.fp):!1}};function sr(r,e){return Math.floor(Math.random()*(e-r))+r}var ir=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof je))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 je))throw new TypeError("Invalid Fingerprint");let t=sr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var z0=500,kn=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??Un,this.seed=e.seed??sr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=j(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ir(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new ir(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[sr(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ir(this.bucketSize));for(let a=0;a<z0;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 ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=j(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=j(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},V0={1:.5,2:.84,4:.95,8:.98};function H0(r=.001){return r>.002?2:r>1e-5?4:8}function Uf(r,e=.001){let t=H0(e),n=V0[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),uc);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Yo=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??Un,this.seed=e.seed??sr(0,Math.pow(2,10)),this.filterSeries=[new kn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=j(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 kn({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=j(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=j(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 jr(r,e=.001,t){return new Yo({...Uf(r,e),...t??{}})}var Z=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),kf=r=>({match:e=>r.match(e)===!1?e:!1}),K=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),ve=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),V=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function X(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var $0=O(421),KS=X($0),Xo=O(54),Qo=O(55),Jo=O(56),fc=O(53),qS=X(Xo,K(O(421))),zS=X(Qo,K(O(421))),VS=X(Jo,K(O(421))),HS=X(ve(fc,Jo,Xo,Qo),K(O(421))),Mf=V(O(4),K(O(43))),Ff=V(K(O(42)),O(41),K(O(43))),dc=ve(Mf,Ff),Wr=ve(dc,fc,Xo,Qo,Jo),$S=X(ve(dc,V(ve(fc,Jo,Xo,Qo),K(O(421))))),jS=X(Mf),WS=X(Ff),GS=X(dc),hc=V(Wr,O(6)),Mn=V(Wr,O(273)),YS=X(V(hc,K(O(421)))),ZS=X(Mn),pc=V(Mn,Z(460),K(O(421))),es=V(Mn,Z(461),K(O(421))),j0=ve(pc,es),XS=X(pc),QS=X(es),lc=ve(Wr,hc,Mn,pc,es),Kf=ve(V(lc,Z(477),K(O(421)))),JS=X(Kf),qf=ve(V(lc,Z(478),K(O(421))),V(lc,Z(448),K(O(449)),Z(477),K(O(421)))),ev=X(qf),zf=V(Mn,Z(280),K(O(466)),K(O(466)),K(O(421))),tv=X(zf),Vf=V(es,Z(465),K(O(466)),K(O(466)),K(O(421))),rv=X(Vf),Zo=ve(Kf,qf,V(hc,K(O(421))),V(j0,K(O(421))),V(Wr,K(O(421))),zf,Vf,O(421)),Hf=X(Zo),W0=V(K(Zo),Z(290),kf(Z(281)),K(O(421))),ar=X(W0),G0=ve(V(Zo,Z(290),Z(281),K(O(421))),V(Zo,Z(281),K(O(421))),V(Z(281),K(O(421)))),nv=X(G0),Y0=V(Wr,ve(V(O(6,"80")),V(O(6),Z(480)),Z(480)),K(O(481)),K(O(421))),ov=X(Y0),Z0=V(Wr,ve(V(O(6,"443")),V(O(6,"443"),Z(480)),V(O(6),Z(443)),V(O(6),Z(448),Z(480)),V(Z(448),Z(480)),Z(448),Z(443)),K(O(481)),K(O(421))),sv=X(Z0),X0=ve(V(O(777),K(O(421)))),iv=X(X0),Q0=ve(V(O(400),K(O(421)))),av=X(Q0);function We(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ts=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}},Gr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ts(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 ts(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 mc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Pt(r={}){return J0(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 J0(r,e){e=e??{};let t=e.onEnd,n=new Gr,s,o,i,a=We(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{o=E=>{o=null,n.push(E);try{h(r(n))}catch(v){g(v)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=We()})}},u=h=>o!=null?o(h):(n.push(h),s),l=h=>(n=new Gr,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},m=h=>i?s:(i=!0,h!=null?l(h):u({done:!0})),d=()=>(n=new Gr,m(),{done:!0}),p=h=>(m(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:m,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,v;g!=null&&(E=new Promise((I,D)=>{v=()=>{D(new mc)},g.addEventListener("abort",v)}));try{await Promise.race([a.promise,E])}finally{v!=null&&g!=null&&g?.removeEventListener("abort",v)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return b.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},s}var yc=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},$f=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function gc(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){m($f(i));return}if(i&&(c=()=>{m($f(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,m),t===Number.POSITIVE_INFINITY)return;let d=new yc;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){m(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?m(s):(d.message=s??`Promise timed out after ${t} milliseconds`,m(d))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}var ey=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 ty(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=ey(r),f=async(...d)=>{let p=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),i(b);return}c.push(p),t.count===c.length&&(n(),o(c))},m=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)a.includes(d)||l(d,m)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)a.includes(d)||u(d,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=gc(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function nt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=ty(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function bc(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var rs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},cr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var ns=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function ry(r){return r.reason}async function Nt(r,e,t){if(e==null)return r;let n=t?.translateError??ry;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var os=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=We(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ny(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ss=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=ny(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ot),this.cleanup())}async join(e){let t=new os(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 Nt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var is=class extends Ae{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=bc(this.emitEmpty.bind(this),1),this.emitIdle=bc(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 rs;let n=new ss(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ot)}),this.clear()}async onEmpty(e){this.size!==0&&await nt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await nt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await nt(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=Pt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new ot("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var oy=Math.pow(2,20)*4,as=class extends Ae{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??oy,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ee,this.writeBuffer=new ee,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new ns)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Nt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Pt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new bt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Qn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new bt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new bt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new bt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new bt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new jn;this.dispatchEvent(new Jn(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new pr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new ee(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Xn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Xr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Xr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var cs=class extends as{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await nt(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await nt(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function us(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var wc=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=We(),this.haveNext=We()}[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=We(),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=We(),await Nt(this.readNext.promise,t?.signal,t)}};function jf(){return new wc}function sy(r){return r[Symbol.asyncIterator]!=null}async function iy(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*ay(r){let e=new AbortController,t=jf();iy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*cy(r){for(let e of r)yield*e}function uy(...r){let e=[];for(let t of r)sy(t)||e.push(t);return e.length===r.length?cy(e):ay(r)}var Wf=uy;function Gf(r,...e){if(r==null)throw new Error("Empty pipeline");if(xc(r)){let n=r;r=()=>n.source}else if(Zf(r)||Yf(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&xc(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)xc(t[n])&&(t[n]=fy(t[n]));return ly(...t)}var ly=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Yf=r=>r?.[Symbol.asyncIterator]!=null,Zf=r=>r?.[Symbol.iterator]!=null,xc=r=>r==null?!1:r.sink!=null&&r.source!=null,fy=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Pt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Yf(o))s=async function*(){yield*o,n.end()};else if(Zf(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Wf(n,s())}return r.source};var dy=4194304,ls=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Sc=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},vc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_c=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function hy(r){return typeof r?.closeRead=="function"}function py(r){return typeof r?.close=="function"}function Ec(r){return hy(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:py(r)?r.status!=="open":!1}function my(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function yy(r,e){let t=e?.maxBufferSize??dy,n=new ee,s,o=!1;if(!my(r))throw new oe("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?s?.reject(l.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(o===!0)throw new ls("Stream was unwrapped");if(Ec(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new cr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await Nt(s.promise,l?.signal),Ec(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}s=Promise.withResolvers()}let m=l?.bytes??n.byteLength;if(n.byteLength<m){if(Ec(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,m),new cr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return u.read(l)}let d=n.sublist(0,m);return n.consume(m),d},async write(l,f){if(o===!0)throw new ls("Stream was unwrapped");r.send(l)||await nt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function gy(r,e={}){let t=yy(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ie(e.maxDataLength));let n=e?.lengthDecoder??vn,s=e?.lengthEncoder??kr;return{async read(i){let a=-1,c=new ee;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 Sc("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new _c(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new vc(`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 cr(`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 cr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ee(s(i.byteLength),i),a)},async writeV(i,a){let c=new ee(...i.flatMap(u=>[s(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Ut(r,e){let t=gy(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function by(r){return r?.addEventListener!=null}function wy(r){let e=Pt(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(l!=null&&(r.send(l)||await Promise.race([nt(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function Xf(...r){let e=r.map(t=>by(t)?wy(t):t);return Gf(...e)}var Yr=class extends is{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ac=1e3,Qf=60*Ac,Jf=15,ed=120*Qf,td=1,fs=5e3,rd=100,Tc="circuit-relay-source",Fn=`${Fc}-circuit-relay`,nd=2*Qf,od=BigInt(1<<17),Me="/libp2p/circuit/relay/0.2.0/hop",ur="/libp2p/circuit/relay/0.2.0/stop",sd=30*Ac,d6=30*Ac,Kn=300,id=4096,ad=.001;var G;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),kt.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),qn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Mt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),M.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{l.type=r.Type.codec().decode(a);break}case 2:{l.peer=kt.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.reservation=qn.codec().decode(a,a.uint32(),{limits:u.limits?.reservation});break}case 4:{l.limit=Mt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 5:{l.status=M.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*kt.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*qn.codec().stream(a,a.uint32(),`${u}.reservation`,{limits:l.limits?.reservation});break}case 4:{yield*Mt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 5:{yield{field:`${u}.status`,value:M.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Be(a,r.codec(),c)}r.stream=i})(G||(G={}));var Ue;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),kt.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Mt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),M.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{l.type=r.Type.codec().decode(a);break}case 2:{l.peer=kt.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.limit=Mt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 4:{l.status=M.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*kt.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*Mt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 4:{yield{field:`${u}.status`,value:M.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Be(a,r.codec(),c)}r.stream=i})(Ue||(Ue={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:Te(0),addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new er('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new er('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(kt||(kt={}));var qn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),zn.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new er('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=zn.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new er('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}case 3:{yield*zn.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(qn||(qn={}));var Mt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Mt||(Mt={}));var M;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(M||(M={}));var Dc;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Dc||(Dc={}));(function(r){r.codec=()=>Jt(Dc)})(M||(M={}));var lr;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:Te(0),peer:Te(0),expiration:0n},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(lr||(lr={}));var zn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),lr.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:Te(0),payloadType:Te(0),signature:Te(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=lr.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*lr.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(zn||(zn={}));var ds=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},hs=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},Vn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},ps=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},ms=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function cd(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new ds(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ud(r,e,t,n,s){function o(l){r.abort(l),e.abort(l)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=us(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;t.aborted?l=t.reason:l=new hs(`duration limit of ${n.limit?.duration} ms exceeded`),o(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(cd(e,c,s),cd(r,c,s)),Xf(r,e,r).catch(l=>{o(l)}).finally(()=>{a.clear()})}function Ic(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var Hn=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},ys=X(V(Hf.matchers[0],Z(290))),gs=X(Z(290));function bs(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var Ft=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 bs(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 bs(this.map.values(),e=>e.key)}values(){return bs(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ws=class{filter;constructor(e,t){this.filter=jr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Cc(r,e=.001){return new ws(r,e)}var Lc=class extends Ft{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 Bc(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Lc({name:e,metrics:t}):n=new Ft,n}var Rc=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function ld(r,e){let t=new Rc(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var xs=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??Jf,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??ed,this.defaultDurationLimit=t.defaultDurationLimit??nd,this.defaultDataLimit=t.defaultDataLimit??od,this.reservations=Bc({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:M.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:ld(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:M.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Es=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return lr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var xy={maxOutboundStopStreams:Kn},Ss=class extends Ae{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??sd,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??xy.maxOutboundStopStreams,this.reservationStore=new xs(e,t.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(Me,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(Me),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=Ut(e);try{let i=await o.pb(G).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(G).write({type:G.Type.STATUS,status:M.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case G.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case G.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(G).write({type:G.Type.STATUS,status:M.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(G);if(this.log("hop reserve request from %p",t.remotePeer),ar.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:G.Type.STATUS,status:M.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:G.Type.STATUS,status:M.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==M.OK){await s.write({type:G.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[Tc]:{value:1,ttl:i}}},n)}await s.write({type:G.Type.STATUS,status:M.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[Tc]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await Rn.seal(new Es({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:Qe(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(G);if(ar.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:G.Type.STATUS,status:M.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Ne),i=qr(Ye(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:G.Type.STATUS,status:M.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,M.NO_RESERVATION),await o.write({type:G.Type.STATUS,status:M.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:G.Type.STATUS,status:M.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:G.Type.STATUS,status:M.NO_RESERVATION},s);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:Ue.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await o.write({type:G.Type.STATUS,status:M.CONNECTION_FAILED},s);return}await o.write({type:G.Type.STATUS,status:M.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ud(e.unwrap(),l,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(ur,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Ut(s),i=o.pb(Ue);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===M.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Kt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var vs=class extends Ae{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Me,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Me)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=fd(n),i=fd(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Yr({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=us([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function fd(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(J(e)).getTime()}var Pc=class extends Ae{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??fs,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(gs.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(ys.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new qt(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>Ne(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function dd(r){return new Pc(r)}var hd="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var pd=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=hd[t[r]&63];return e};var Ey=60*1e3*10,Sy=60*1e3*5,vy=30*1e3,_s=class extends Ae{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Ft,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??rd,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??fs,this.started=!1,this.relayFilter=jr(100),this.reserveQueue=new Yr({concurrency:t?.reservationConcurrency??td,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Fn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[Fn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=pd();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new qt("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new ms("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new qt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let p=this.connectionManager.getConnections(e),b=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(h=>h.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),b=!0),b&&Ic(o.reservation.expire)>Ey)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new Vn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(ar.matches(a.remoteAddr))throw new ps("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),u=Ic(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+u).toString());let l=Math.min(Math.max(u-Sy,vy),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},l),m;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new Vn("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:t,connection:a.id,id:p}}else m={timeout:f,reservation:c,type:t,connection:a.id};this.reservations.set(e,m),await this.peerStore.merge(e,{tags:{[Fn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Me,t),o=Ut(n).pb(G);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:G.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===M.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Ne(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Ne(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Ne(u).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[Fn]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=jr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Nc=class extends cs{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Uc(r){return new Nc(r)}var _y=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Ne)}catch{return!1}return!0},md={maxInboundStopStreams:Kn,maxOutboundStopStreams:Kn,stopTimeout:3e4},As=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??md.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??md.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new vs(e,{filter:t.discoveryFilter??Cc(id,ad)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new _s(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[$c]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[jc](){return this.discovery!=null?["@libp2p/identify"]:[]}[Hc]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(ur,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await qc(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await zc(this.discovery,this.reservationStore),await this.components.registrar.unhandle(ur),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=Ne(n[0]),o=Ne(n[n.length-1]),i=s.getComponents().find(d=>d.code===421)?.value,a=o.getComponents().find(d=>d.code===421)?.value;if(i==null||a==null){let d=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new Zn(`C${d}`)}let c=Ua(i),u=Ua(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Kt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Kt("circuit-relay:reuse-connection"));let m;try{t.onProgress?.(new Kt("circuit-relay:open-hop-stream")),m=await f.newStream(Me,t);let d=Ut(m).pb(G);t.onProgress?.(new Kt("circuit-relay:write-connect-message")),await d.write({type:G.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Ne(o).bytes]}},t),t.onProgress?.(new Kt("circuit-relay:read-connect-response"));let p=await d.read(t);if(p.status!==M.OK)throw new Yn(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let b=new Hn(p.limit),h=Uc({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:b.onData,onDataWrite:b.onData,log:m.log.newScope("circuit-relay:connection")}),g=await this.components.upgrader.upgradeOutbound(h,{...t,limits:b.getLimits()});return g.log("outbound relayed connection established to %p with limits %o, over connection %s",g.remotePeer,p.limit??"none",f.id),g}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,c,d),m?.abort(d),d}}createListener(e){return dd({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ys.exactMatch(t)||gs.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ar.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",f)}let s=Ut(e).pb(Ue),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:Ue.Type.STATUS,status:M.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==Ue.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ue.Type.STATUS,status:M.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!_y(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ue.Type.STATUS,status:M.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=qr(Ye(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:Ue.Type.STATUS,status:M.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Ue.Type.STATUS,status:M.OK},{signal:n});let a=new Hn(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Uc({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function Ay(r={}){return e=>new Ss(e,r)}function Ty(r={}){return e=>new As(e,r)}return xd(Dy);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var Ds=Object.defineProperty;var Dd=Object.getOwnPropertyDescriptor;var Cd=Object.getOwnPropertyNames;var Ld=Object.prototype.hasOwnProperty;var J=(t,e)=>{for(var r in e)Ds(t,r,{get:e[r],enumerable:!0})},Bd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Cd(e))!Ld.call(t,s)&&s!==r&&Ds(t,s,{get:()=>e[s],enumerable:!(n=Dd(e,s))||n.enumerable});return t};var Rd=t=>Bd(Ds({},"__esModule",{value:!0}),t);var ag={};J(ag,{RELAY_V2_HOP_CODEC:()=>ze,RELAY_V2_STOP_CODEC:()=>hr,circuitRelayServer:()=>sg,circuitRelayTransport:()=>ig});function Od(t){return typeof t?.handleEvent=="function"}function Pd(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Ce=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let s=Pd(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#e.set(i.type,a))}Od(r)?r.handleEvent(i):r(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:s})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==r),this.#e.set(e,s))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var at=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Yn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Et=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},en=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Zn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Xn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Qn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Jn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},$t=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var gr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var eo=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},br=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},to=class extends br{constructor(e,r){super(!0,e,r)}},ro=class extends br{constructor(e,r){super(!1,e,r)}};var Cs=Symbol.for("@libp2p/peer-id");var $c="keep-alive";function jc(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}async function Gc(...t){let e=[];for(let r of t)jc(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStart!=null&&await r.beforeStart()})),await Promise.all(e.map(async r=>{await r.start()})),await Promise.all(e.map(async r=>{r.afterStart!=null&&await r.afterStart()}))}async function Wc(...t){let e=[];for(let r of t)jc(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStop!=null&&await r.beforeStop()})),await Promise.all(e.map(async r=>{await r.stop()})),await Promise.all(e.map(async r=>{r.afterStop!=null&&await r.afterStop()}))}var Zc=Symbol.for("@libp2p/transport");var Yc;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Yc||(Yc={}));var Xc=Symbol.for("@libp2p/service-capabilities"),Qc=Symbol.for("@libp2p/service-dependencies");var Ps={};J(Ps,{base58btc:()=>re,base58flickr:()=>zd});var qg=new Uint8Array(0);function Jc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function ct(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return jt(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return jt(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function eu(t){return new TextEncoder().encode(t)}function tu(t){return new TextDecoder().decode(t)}function Nd(t){return t?.buffer instanceof ArrayBuffer}function jt(t){return Nd(t)?t:t.slice()}function Fd(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<t.length;s++){var o=t.charAt(s),i=o.charCodeAt(0);if(r[i]!==255)throw new TypeError(o+" is ambiguous");r[i]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,g=0,E=p.length;g!==E&&p[g]===0;)g++,b++;for(var v=(E-g)*l+1>>>0,D=new Uint8Array(v);g!==E;){for(var I=p[g],P=0,B=v-1;(I!==0||P<h)&&B!==-1;B--,P++)I+=256*D[B]>>>0,D[B]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");h=P,g++}for(var T=v-h;T!==v&&D[T]===0;)T++;for(var F=c.repeat(b);T<v;++T)F+=t.charAt(D[T]);return F}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,g=0;p[b]===c;)h++,b++;for(var E=(p.length-b)*u+1>>>0,v=new Uint8Array(E);p[b];){var D=r[p.charCodeAt(b)];if(D===255)return;for(var I=0,P=E-1;(D!==0||I<g)&&P!==-1;P--,I++)D+=a*v[P]>>>0,v[P]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");g=I,b++}if(p[b]!==" "){for(var B=E-g;B!==E&&v[B]===0;)B++;for(var T=new Uint8Array(h+(E-B)),F=h;B!==E;)T[F++]=v[B++];return T}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var Ud=Fd,Md=Ud,nu=Md;var Ls=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Bs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let s=r.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ou(this,e)}},Rs=class{decoders;constructor(e){this.decoders=e}or(e){return ou(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 ou(t,e){return new Rs({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Os=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,s){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=s,this.encoder=new Ls(e,r,n),this.decoder=new Bs(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function wr({name:t,prefix:e,encode:r,decode:n}){return new Os(t,e,r,n)}function St({name:t,prefix:e,alphabet:r}){let{encode:n,decode:s}=nu(r,t);return wr({prefix:e,name:t,encode:n,decode:o=>ct(s(o))})}function kd(t,e,r,n){let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),i=0,a=0,c=0;for(let u=0;u<s;++u){let l=e[t[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Kd(t,e,r){let n=e[e.length-1]==="=",s=(1<<r)-1,o="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<r-i]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function qd(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function ie({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let s=qd(n);return wr({prefix:e,name:t,encode(o){return Kd(o,n,r)},decode(o){return kd(o,s,r,t)}})}var re=St({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zd=St({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ns={};J(Ns,{base32:()=>vt,base32hex:()=>jd,base32hexpad:()=>Wd,base32hexpadupper:()=>Yd,base32hexupper:()=>Gd,base32pad:()=>Hd,base32padupper:()=>$d,base32upper:()=>Vd,base32z:()=>Zd});var vt=ie({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vd=ie({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hd=ie({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$d=ie({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jd=ie({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gd=ie({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wd=ie({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yd=ie({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zd=ie({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Fs={};J(Fs,{base36:()=>tn,base36upper:()=>Xd});var tn=St({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xd=St({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qd=au,su=128,Jd=127,eh=~Jd,th=Math.pow(2,31);function au(t,e,r){e=e||[],r=r||0;for(var n=r;t>=th;)e[r++]=t&255|su,t/=128;for(;t&eh;)e[r++]=t&255|su,t>>>=7;return e[r]=t|0,au.bytes=r-n+1,e}var rh=Us,nh=128,iu=127;function Us(t,n){var r=0,n=n||0,s=0,o=n,i,a=t.length;do{if(o>=a)throw Us.bytes=0,new RangeError("Could not decode varint");i=t[o++],r+=s<28?(i&iu)<<s:(i&iu)*Math.pow(2,s),s+=7}while(i>=nh);return Us.bytes=o-n,r}var oh=Math.pow(2,7),sh=Math.pow(2,14),ih=Math.pow(2,21),ah=Math.pow(2,28),ch=Math.pow(2,35),uh=Math.pow(2,42),lh=Math.pow(2,49),fh=Math.pow(2,56),dh=Math.pow(2,63),hh=function(t){return t<oh?1:t<sh?2:t<ih?3:t<ah?4:t<ch?5:t<uh?6:t<lh?7:t<fh?8:t<dh?9:10},ph={encode:Qd,decode:rh,encodingLength:hh},mh=ph,rn=mh;function nn(t,e=0){return[rn.decode(t,e),rn.decode.bytes]}function xr(t,e,r=0){return rn.encode(t,e,r),e}function Er(t){return rn.encodingLength(t)}function Qe(t,e){let r=e.byteLength,n=Er(t),s=n+Er(r),o=new Uint8Array(s+r);return xr(t,o,0),xr(r,o,n),o.set(e,s),new Sr(t,r,e,o)}function Je(t){let e=ct(t),[r,n]=nn(e),[s,o]=nn(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Sr(r,s,i,e)}function cu(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Jc(t.bytes,r.bytes)}}var Sr=class{code;size;digest;bytes;constructor(e,r,n,s){this.code=e,this.size=r,this.digest=jt(n),this.bytes=jt(s)}};function uu(t,e){let{bytes:r,version:n}=t;return n===0?gh(r,Ms(t),e??re.encoder):bh(r,Ms(t),e??vt.encoder)}var lu=new WeakMap;function Ms(t){let e=lu.get(t);if(e==null){let r=new Map;return lu.set(t,r),r}return e}var fe=class t{code;version;multihash;bytes;"/";constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=jt(s),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==on)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==wh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Qe(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&cu(e.multihash,n.multihash)}toString(e){return uu(this,e)}toJSON(){return{"/":uu(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:o,bytes:i}=r;return new t(n,s,o,i??fu(n,s,o.bytes))}else if(r[xh]===!0){let{version:n,multihash:s,code:o}=r,i=Je(s);return t.create(n,o,i)}else return null}static create(e,r,n){if(typeof r!="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(r!==on)throw new Error(`Version 0 CID must use dag-pb (code: ${on}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let s=fu(e,r,n.bytes);return new t(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,on,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,s=ct(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=s.subarray(r.multihashSize-r.digestSize),i=new Sr(r.multihashCode,r.digestSize,o,s);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,m]=nn(e.subarray(r));return r+=m,f},s=n(),o=on;if(s===18?(s=0,r=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=r,a=n(),c=n(),u=r+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,s]=yh(e,r),o=t.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ms(o).set(n,e),o}};function yh(t,e){switch(t[0]){case"Q":{let r=e??re;return[re.prefix,r.decode(`${re.prefix}${t}`)]}case re.prefix:{let r=e??re;return[re.prefix,r.decode(t)]}case vt.prefix:{let r=e??vt;return[vt.prefix,r.decode(t)]}case tn.prefix:{let r=e??tn;return[tn.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function gh(t,e,r){let{prefix:n}=r;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return s}function bh(t,e,r){let{prefix:n}=r,s=e.get(n);if(s==null){let o=r.encode(t);return e.set(n,o),o}else return s}var on=112,wh=18;function fu(t,e,r){let n=Er(t),s=n+Er(e),o=new Uint8Array(s+r.byteLength);return xr(t,o,0),xr(e,o,n),o.set(r,s),o}var xh=Symbol.for("@ipld/js-cid/CID");var ks={};J(ks,{identity:()=>Ve});var du=0,Eh="identity",hu=ct;function Sh(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Qe(du,hu(t))}var Ve={code:du,name:Eh,encode:hu,digest:Sh};function he(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function vh(t){return t.buffer instanceof ArrayBuffer}function Fe(t){return vh(t)?t:t.slice()}async function pu(t,e,r,n){let s=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,Fe(e),Fe(r.subarray()));return n?.signal?.throwIfAborted(),o}function lt(t=0){return new Uint8Array(t)}function sn(t=0){return new Uint8Array(t)}function Ks(t,e){e==null&&(e=t.reduce((s,o)=>s+o.length,0));let r=sn(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}function mu(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var gu=Symbol.for("@achingbrain/uint8arraylist");function yu(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let s=r+n.byteLength;if(e<s)return{buf:n,index:e-r};r=s}throw new RangeError("index is out of bounds")}function oo(t){return!!t?.[gu]}var ee=class t{bufs;length;[gu]=!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 r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(oo(n)){r+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(oo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=yu(this.bufs,e);return r.buf[r.index]}set(e,r){let n=yu(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(oo(e))for(let n=0;n<e.length;n++)this.set(r+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,r){let{bufs:n,length:s}=this._subList(e,r);return Ks(n,s)}subarray(e,r){let{bufs:n,length:s}=this._subList(e,r);return n.length===1?n[0]:Ks(n,s)}sublist(e,r){let{bufs:n,length:s}=this._subList(e,r),o=new t;return o.length=s,o.bufs=n,o}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!oo(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(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=sn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let s=lt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,r,n),this.write(s,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let s=lt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,r,n),this.write(s,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let s=lt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,r,n),this.write(s,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=sn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let s=lt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,r,n),this.write(s,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let s=lt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,r,n),this.write(s,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let s=lt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,r,n),this.write(s,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let s=lt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,r,n),this.write(s,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let s=lt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,r,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!mu(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((s,o)=>s+o.byteLength,0)),n.length=r,n}};var qs={};J(qs,{base10:()=>_h});var _h=St({prefix:"9",name:"base10",alphabet:"0123456789"});var zs={};J(zs,{base16:()=>Ah,base16upper:()=>Th});var Ah=ie({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Th=ie({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vs={};J(Vs,{base2:()=>Ih});var Ih=ie({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hs={};J(Hs,{base256emoji:()=>Rh});var bu=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}"),Dh=bu.reduce((t,e,r)=>(t[r]=e,t),[]),Ch=bu.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Lh(t){return t.reduce((e,r)=>(e+=Dh[r],e),"")}function Bh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let s=Ch[n];if(s==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(s)}return new Uint8Array(e)}var Rh=wr({prefix:"\u{1F680}",name:"base256emoji",encode:Lh,decode:Bh});var js={};J(js,{base64:()=>Oh,base64pad:()=>Ph,base64url:()=>$s,base64urlpad:()=>Nh});var Oh=ie({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ph=ie({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$s=ie({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nh=ie({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gs={};J(Gs,{base8:()=>Fh});var Fh=ie({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ws={};J(Ws,{identity:()=>Uh});var Uh=wr({prefix:"\0",name:"identity",encode:t=>tu(t),decode:t=>eu(t)});var Db=new TextEncoder,Cb=new TextDecoder;var Xs={};J(Xs,{sha256:()=>vr,sha512:()=>qh});var Kh=20;function Zs({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:s}){return new Ys(t,e,r,n,s)}var Ys=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,s,o){this.name=e,this.code=r,this.encode=n,this.minDigestLength=s??Kh,this.maxDigestLength=o}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.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?wu(n,this.code,r?.truncate):n.then(s=>wu(s,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function wu(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Qe(e,t)}function Eu(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var vr=Zs({name:"sha2-256",code:18,encode:Eu("SHA-256")}),qh=Zs({name:"sha2-512",code:19,encode:Eu("SHA-512")});var an={...Ws,...Vs,...Gs,...qs,...zs,...Ns,...Fs,...Ps,...js,...Hs},qb={...Xs,...ks};function Te(t=0){return new Uint8Array(t)}function Gt(t=0){return new Uint8Array(t)}function vu(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Su=vu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Qs=vu("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Gt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),zh={utf8:Su,"utf-8":Su,hex:an.base16,latin1:Qs,ascii:Qs,binary:Qs,...an},so=zh;function k(t,e="utf8"){let r=so[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function V(t,e="utf8"){let r=so[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Vh=parseInt("11111",2),Js=parseInt("10000000",2),Hh=parseInt("01111111",2),_u={0:cn,1:cn,2:$h,3:Wh,4:Yh,5:Gh,6:jh,16:cn,22:cn,48:cn};function ft(t,e={offset:0}){let r=t[e.offset]&Vh;if(e.offset++,_u[r]!=null)return _u[r](t,e);throw new Error("No decoder for tag "+r)}function un(t,e){let r=0;if((t[e.offset]&Js)===Js){let n=t[e.offset]&Hh,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=t[e.offset],e.offset++;return r}function cn(t,e){un(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=ft(t,e);if(n===null)break;r.push(n)}return r}function $h(t,e){let r=un(t,e),n=e.offset,s=e.offset+r,o=[];for(let i=n;i<s;i++)i===n&&t[i]===0||o.push(t[i]);return e.offset+=r,Uint8Array.from(o)}function jh(t,e){let r=un(t,e),n=e.offset+r,s=t[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let u=t[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 Gh(t,e){return e.offset++,null}function Wh(t,e){let r=un(t,e),n=t[e.offset];e.offset++;let s=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Yh(t,e){let r=un(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Zh(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new ee;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function ei(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Zh(t.byteLength);return new ee(Uint8Array.from([e.byteLength|Js]),e)}function Le(t){let e=new ee,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new ee(Uint8Array.from([2]),ei(e),e)}function io(t){let e=Uint8Array.from([0]),r=new ee(e,t);return new ee(Uint8Array.from([3]),ei(r),r)}function _t(t,e=48){let r=new ee;for(let n of t)r.append(n);return new ee(Uint8Array.from([e]),ei(r),r)}var Xh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Qh=Uint8Array.from([6,5,43,129,4,0,34]),Jh=Uint8Array.from([6,5,43,129,4,0,35]),ep={ext:!0,kty:"EC",crv:"P-256"},tp={ext:!0,kty:"EC",crv:"P-384"},rp={ext:!0,kty:"EC",crv:"P-521"},ti=32,ri=48,ni=66;function oi(t){let e=ft(t);return Au(e)}function Au(t){let e=t[1][1][0],r=1,n,s;if(e.byteLength===ti*2+1)return n=V(e.subarray(r,r+ti),"base64url"),s=V(e.subarray(r+ti),"base64url"),new _r({...ep,key_ops:["verify"],x:n,y:s});if(e.byteLength===ri*2+1)return n=V(e.subarray(r,r+ri),"base64url"),s=V(e.subarray(r+ri),"base64url"),new _r({...tp,key_ops:["verify"],x:n,y:s});if(e.byteLength===ni*2+1)return n=V(e.subarray(r,r+ni),"base64url"),s=V(e.subarray(r+ni),"base64url"),new _r({...rp,key_ops:["verify"],x:n,y:s});throw new se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Tu(t){return _t([Le(Uint8Array.from([1])),_t([np(t.crv)],160),_t([io(new ee(Uint8Array.from([4]),k(t.x??"","base64url"),k(t.y??"","base64url")))],161)]).subarray()}function np(t){if(t==="P-256")return Xh;if(t==="P-384")return Qh;if(t==="P-521")return Jh;throw new se(`Invalid curve ${t}`)}var _r=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Tu(this.jwk)),this._raw}toMultihash(){return Ve.digest(et(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async verify(e,r,n){return pu(this.jwk,r,e,n)}};function si(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function At(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Ue(t,e,r=""){let n=si(t),s=t?.length,o=e!==void 0;if(!n||o&&s!==e){let i=r&&`"${r}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof t}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return t}function ao(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(At(t.outputLen),At(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Ar(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function co(t,e){Ue(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function ht(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function uo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function He(t,e){return t<<32-e|t>>>e}var Du=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",op=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function lo(t){if(Ue(t),Du)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=op[t[r]];return e}var dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Iu(t){if(t>=dt._0&&t<=dt._9)return t-dt._0;if(t>=dt.A&&t<=dt.F)return t-(dt.A-10);if(t>=dt.a&&t<=dt.f)return t-(dt.a-10)}function ln(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Du)try{return Uint8Array.fromHex(t)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let s=0,o=0;s<r;s++,o+=2){let i=Iu(t.charCodeAt(o)),a=Iu(t.charCodeAt(o+1));if(i===void 0||a===void 0){let c=t[o]+t[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function ii(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];Ue(s),e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let o=t[n];r.set(o,s),s+=o.length}return r}function ai(t,e={}){let r=(s,o)=>t(o).update(s).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=s=>t(s),Object.assign(r,e),Object.freeze(r)}function Cu(t=32){At(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var ci=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Lu(t,e,r){return t&e^~t&r}function Bu(t,e,r){return t&e^t&r^e&r}var fn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,s){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=uo(this.buffer)}update(e){Ar(this),Ue(e);let{view:r,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=uo(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ar(this),co(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;r[i++]=128,ht(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)r[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=uo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},pt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fo=BigInt(4294967295),Ru=BigInt(32);function sp(t,e=!1){return e?{h:Number(t&fo),l:Number(t>>Ru&fo)}:{h:Number(t>>Ru&fo)|0,l:Number(t&fo)|0}}function Ou(t,e=!1){let r=t.length,n=new Uint32Array(r),s=new Uint32Array(r);for(let o=0;o<r;o++){let{h:i,l:a}=sp(t[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var ui=(t,e,r)=>t>>>r,li=(t,e,r)=>t<<32-r|e>>>r,Wt=(t,e,r)=>t>>>r|e<<32-r,Yt=(t,e,r)=>t<<32-r|e>>>r,dn=(t,e,r)=>t<<64-r|e>>>r-32,hn=(t,e,r)=>t>>>r-32|e<<64-r;function tt(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var Pu=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Nu=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Fu=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Uu=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,Mu=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),ku=(t,e,r,n,s,o)=>e+r+n+s+o+(t/2**32|0)|0;var ap=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]),Tt=new Uint32Array(64),fi=class extends fn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,r,n,s,o,i,a,c]}set(e,r,n,s,o,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Tt[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let m=Tt[f-15],d=Tt[f-2],p=He(m,7)^He(m,18)^m>>>3,b=He(d,17)^He(d,19)^d>>>10;Tt[f]=b+Tt[f-7]+p+Tt[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=He(a,6)^He(a,11)^He(a,25),d=l+m+Lu(a,c,u)+ap[f]+Tt[f]|0,b=(He(n,2)^He(n,13)^He(n,22))+Bu(n,s,o)|0;l=u,u=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+b|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,o,i,a,c,u,l)}roundClean(){ht(Tt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ht(this.buffer)}},di=class extends fi{A=pt[0]|0;B=pt[1]|0;C=pt[2]|0;D=pt[3]|0;E=pt[4]|0;F=pt[5]|0;G=pt[6]|0;H=pt[7]|0;constructor(){super(32)}};var Ku=Ou(["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(t=>BigInt(t))),cp=Ku[0],up=Ku[1],It=new Uint32Array(80),Dt=new Uint32Array(80),hi=class extends fn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:p,Hh:b,Hl:h}=this;return[e,r,n,s,o,i,a,c,u,l,f,m,d,p,b,h]}set(e,r,n,s,o,i,a,c,u,l,f,m,d,p,b,h){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=m|0,this.Gh=d|0,this.Gl=p|0,this.Hh=b|0,this.Hl=h|0}process(e,r){for(let v=0;v<16;v++,r+=4)It[v]=e.getUint32(r),Dt[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){let D=It[v-15]|0,I=Dt[v-15]|0,P=Wt(D,I,1)^Wt(D,I,8)^ui(D,I,7),B=Yt(D,I,1)^Yt(D,I,8)^li(D,I,7),T=It[v-2]|0,F=Dt[v-2]|0,Z=Wt(T,F,19)^dn(T,F,61)^ui(T,F,6),U=Yt(T,F,19)^hn(T,F,61)^li(T,F,6),y=Fu(B,U,Dt[v-7],Dt[v-16]),w=Uu(y,P,Z,It[v-7],It[v-16]);It[v]=w|0,Dt[v]=y|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:p,Gh:b,Gl:h,Hh:g,Hl:E}=this;for(let v=0;v<80;v++){let D=Wt(f,m,14)^Wt(f,m,18)^dn(f,m,41),I=Yt(f,m,14)^Yt(f,m,18)^hn(f,m,41),P=f&d^~f&b,B=m&p^~m&h,T=Mu(E,I,B,up[v],Dt[v]),F=ku(T,g,D,P,cp[v],It[v]),Z=T|0,U=Wt(n,s,28)^dn(n,s,34)^dn(n,s,39),y=Yt(n,s,28)^hn(n,s,34)^hn(n,s,39),w=n&o^n&a^o&a,_=s&i^s&c^i&c;g=b|0,E=h|0,b=d|0,h=p|0,d=f|0,p=m|0,{h:f,l:m}=tt(u|0,l|0,F|0,Z|0),u=a|0,l=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let S=Pu(Z,y,_);n=Nu(S,F,U,w),s=S|0}({h:n,l:s}=tt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=tt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=tt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=tt(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:p}=tt(this.Fh|0,this.Fl|0,d|0,p|0),{h:b,l:h}=tt(this.Gh|0,this.Gl|0,b|0,h|0),{h:g,l:E}=tt(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,s,o,i,a,c,u,l,f,m,d,p,b,h,g,E)}roundClean(){ht(It,Dt)}destroy(){this.destroyed=!0,ht(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},pi=class extends hi{Ah=we[0]|0;Al=we[1]|0;Bh=we[2]|0;Bl=we[3]|0;Ch=we[4]|0;Cl=we[5]|0;Dh=we[6]|0;Dl=we[7]|0;Eh=we[8]|0;El=we[9]|0;Fh=we[10]|0;Fl=we[11]|0;Gh=we[12]|0;Gl=we[13]|0;Hh=we[14]|0;Hl=we[15]|0;constructor(){super(64)}};var Tr=ai(()=>new di,ci(1));var ho=ai(()=>new pi,ci(3));var H=(t,e,r)=>Ue(t,e,r),yi=At,Ir=lo,pe=(...t)=>ii(...t),Dr=t=>ln(t),Zt=si,pn=t=>Cu(t),mo=BigInt(0),mi=BigInt(1);function $e(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function yo(t){if(typeof t=="bigint"){if(!po(t))throw new RangeError("positive bigint expected, got "+t)}else yi(t);return t}function je(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function mn(t){let e=yo(t).toString(16);return e.length&1?"0"+e:e}function qu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?mo:BigInt("0x"+t)}function Xt(t){return qu(lo(t))}function rt(t){return qu(lo(yn(Ue(t)).reverse()))}function go(t,e){if(At(e),e===0)throw new RangeError("zero length");t=yo(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return ln(r.padStart(e*2,"0"))}function gi(t,e){return go(t,e).reverse()}function zu(t,e){if(t=H(t),e=H(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function yn(t){return Uint8Array.from(H(t))}function bo(t){if(typeof t!="string")throw new TypeError("ascii string expected, got "+typeof t);return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var po=t=>typeof t=="bigint"&&mo<=t;function lp(t,e,r){return po(t)&&po(e)&&po(r)&&e<=t&&t<r}function Cr(t,e,r,n){if(!lp(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Lr(t){if(t<mo)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>mo;t>>=mi,e+=1);return e}var gn=t=>(mi<<BigInt(t))-mi;function Vu(t,e,r){if(At(t,"hashLen"),At(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),u=n(t),l=0,f=()=>{c.fill(1),u.fill(0),l=0},m=(...h)=>r(u,pe(c,...h)),d=(h=s)=>{u=m(o,h),c=m(),h.length!==0&&(u=m(i,h),c=m())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,g=[];for(;h<e;){c=m();let E=c.slice();g.push(E),h+=c.length}return pe(...g)};return(h,g)=>{f(),d(h);let E;for(;(E=g(p()))===void 0;)d();return f(),E}}function Ge(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let c=t[o];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(r,!0)}var bi=()=>{throw new Error("not implemented")};var xe=BigInt(0),ae=BigInt(1),Qt=BigInt(2),Gu=BigInt(3),Wu=BigInt(4),Yu=BigInt(5),fp=BigInt(7),Zu=BigInt(8),dp=BigInt(9),Xu=BigInt(16);function le(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=xe?r:e+r}function te(t,e,r){if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function Hu(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let r=le(t,e),n=e,s=xe,o=ae,i=ae,a=xe;for(;r!==xe;){let u=n/r,l=n-r*u,f=s-i*u,m=o-a*u;n=r,r=l,s=i,o=a,i=f,a=m}if(n!==ae)throw new Error("invert: does not exist");return le(s,e)}function wi(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Qu(t,e){let r=t,n=(r.ORDER+ae)/Wu,s=r.pow(e,n);return wi(r,s,e),s}function hp(t,e){let r=t,n=(r.ORDER-Yu)/Zu,s=r.mul(e,Qt),o=r.pow(s,n),i=r.mul(e,o),a=r.mul(r.mul(i,Qt),o),c=r.mul(i,r.sub(a,r.ONE));return wi(r,c,e),c}function pp(t){let e=Br(t),r=Ju(t),n=r(e,e.neg(e.ONE)),s=r(e,n),o=r(e,e.neg(n)),i=(t+fp)/Xu;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),m=u.mul(l,s),d=u.mul(l,o),p=u.eql(u.sqr(f),c),b=u.eql(u.sqr(m),c);l=u.cmov(l,f,p),f=u.cmov(d,m,b);let h=u.eql(u.sqr(f),c),g=u.cmov(l,f,h);return wi(u,g,c),g})}function Ju(t){if(t<Gu)throw new Error("sqrt is not defined for small field");let e=t-ae,r=0;for(;e%Qt===xe;)e/=Qt,r++;let n=Qt,s=Br(t);for(;$u(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Qu;let o=s.pow(n,e),i=(e+ae)/Qt;return function(c,u){let l=c;if(l.is0(u))return u;if($u(l,u)!==1)throw new Error("Cannot find square root");let f=r,m=l.mul(l.ONE,o),d=l.pow(u,e),p=l.pow(u,i);for(;!l.eql(d,l.ONE);){if(l.is0(d))return l.ZERO;let b=1,h=l.sqr(d);for(;!l.eql(h,l.ONE);)if(b++,h=l.sqr(h),b===f)throw new Error("Cannot find square root");let g=ae<<BigInt(f-b-1),E=l.pow(m,g);f=b,m=l.sqr(E),d=l.mul(d,m),p=l.mul(p,E)}return p}}function mp(t){return t%Wu===Gu?Qu:t%Zu===Yu?hp:t%Xu===dp?pp(t):Ju(t)}var mt=(t,e)=>(le(t,e)&ae)===ae,yp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xi(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yp.reduce((n,s)=>(n[s]="function",n),e);if(Ge(t,r),je(t.BYTES,"BYTES"),je(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function gp(t,e,r){let n=t;if(r<xe)throw new Error("invalid exponent, negatives unsupported");if(r===xe)return n.ONE;if(r===ae)return e;let s=n.ONE,o=e;for(;r>xe;)r&ae&&(s=n.mul(s,o)),o=n.sqr(o),r>>=ae;return s}function bn(t,e,r=!1){let n=t,s=new Array(e.length).fill(r?n.ZERO:void 0),o=e.reduce((a,c,u)=>n.is0(c)?a:(s[u]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,u)=>n.is0(c)?a:(s[u]=n.mul(a,s[u]),n.mul(a,c)),i),s}function $u(t,e){let r=t,n=(r.ORDER-ae)/Qt,s=r.pow(e,n),o=r.eql(s,r.ONE),i=r.eql(s,r.ZERO),a=r.eql(s,r.neg(r.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function bp(t,e){if(e!==void 0&&yi(e),t<=xe)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=Lr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var ju=new WeakMap,wo=class{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=ae;_lengths;_mod;constructor(e,r={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:s,nByteLength:o}=bp(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return le(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return le(e*e,this.ORDER)}add(e,r){return le(e+r,this.ORDER)}sub(e,r){return le(e-r,this.ORDER)}mul(e,r){return le(e*r,this.ORDER)}pow(e,r){return gp(this,e,r)}div(e,r){return le(e*Hu(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Hu(e,this.ORDER)}sqrt(e){let r=ju.get(this);return r||ju.set(this,r=mp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?gi(e,this.BYTES):go(e,this.BYTES)}fromBytes(e,r=!1){H(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(s);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?rt(e):Xt(e);if(a&&(c=le(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bn(this,e)}cmov(e,r,n){return $e(n,"condition"),n?r:e}};Object.freeze(wo.prototype);function Br(t,e={}){return new wo(t,e)}function el(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=ae)throw new Error("field order must be greater than 1");let e=Lr(t-ae);return Math.ceil(e/8)}function Ei(t){let e=el(t);return e+Math.ceil(e/2)}function Si(t,e,r=!1){H(t);let n=t.length,s=el(e),o=Math.max(Ei(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=r?rt(t):Xt(t),a=le(i,e-ae)+ae;return r?gi(a,s):go(a,s)}var Rr=BigInt(0),Jt=BigInt(1);function wn(t,e){let r=e.negate();return t?r:e}function er(t,e){let r=bn(t.Fp,e.map(n=>n.Z));return e.map((n,s)=>t.fromAffine(n.toAffine(r[s])))}function ol(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function vi(t,e){ol(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,o=gn(t),i=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function tl(t,e,r){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=r,a=Number(t&s),c=t>>i;a>n&&(a-=o,c+=Jt);let u=e*n,l=u+Math.abs(a)-1,f=a===0,m=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:m,isNegF:d,offsetF:u}}var _i=new WeakMap,sl=new WeakMap;function Ai(t){return sl.get(t)||1}function rl(t){if(t!==Rr)throw new Error("invalid wNAF")}var Or=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let s=e;for(;r>Rr;)r&Jt&&(n=n.add(s)),s=s.double(),r>>=Jt;return n}precomputeWindow(e,r){let{windows:n,windowSize:s}=vi(r,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let u=1;u<s;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=vi(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:m,offsetF:d}=tl(n,a,i);n=c,l?o=o.add(wn(m,r[d])):s=s.add(wn(f,r[u]))}return rl(n),{p:s,f:o}}wNAFUnsafe(e,r,n,s=this.ZERO){let o=vi(e,this.bits);for(let i=0;i<o.windows&&n!==Rr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=tl(n,i,o);if(n=a,!u){let f=r[c];s=s.add(l?f.negate():f)}}return rl(n),s}getPrecomputes(e,r,n){let s=_i.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(s=n(s)),_i.set(r,s))),s}cached(e,r,n){let s=Ai(e);return this.wNAF(s,this.getPrecomputes(s,e,n),r)}unsafe(e,r,n,s){let o=Ai(e);return o===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,s)}createCache(e,r){ol(r,this.bits),sl.set(e,r),_i.delete(e)}hasCache(e){return Ai(e)!==1}};function il(t,e,r,n){let s=e,o=t.ZERO,i=t.ZERO;for(;r>Rr||n>Rr;)r&Jt&&(o=o.add(s)),n&Jt&&(i=i.add(s)),s=s.double(),r>>=Jt,n>>=Jt;return{p1:o,p2:i}}function nl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xi(e),e}else return Br(t,{isLE:r})}function xo(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Rr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=nl(e.p,r.Fp,n),o=nl(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Eo(t,e){return function(n){let s=t(n);return{secretKey:s,publicKey:e(s)}}}var Ct=BigInt(0),ge=BigInt(1),Ti=BigInt(2),wp=BigInt(8);function xp(t,e,r,n){let s=t.sqr(r),o=t.sqr(n),i=t.add(t.mul(e.a,s),o),a=t.add(t.ONE,t.mul(e.d,t.mul(s,o)));return t.eql(i,a)}function al(t,e={}){let r=e,n=xo("edwards",t,r,r.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;Ge(r,{},{uvRatio:"function"});let c=Ti<<BigInt(o.BYTES*8)-ge,u=b=>s.create(b),l=r.uvRatio===void 0?(b,h)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,h))}}catch{return{isValid:!1,value:Ct}}}:r.uvRatio;if(!xp(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(b,h,g=!1){let E=g?ge:Ct;return Cr("coordinate "+b,h,E,c),h}function m(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,ge,u(i.Gx*i.Gy));static ZERO=new d(Ct,ge,ge,Ct);static Fp=s;static Fn=o;X;Y;Z;T;constructor(h,g,E,v){this.X=f("x",h),this.Y=f("y",g),this.Z=f("z",E,!0),this.T=f("t",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:g,y:E}=h||{};return f("x",g),f("y",E),new d(g,E,ge,u(g*E))}static fromBytes(h,g=!1){let E=s.BYTES,{a:v,d:D}=i;h=yn(H(h,E,"point")),$e(g,"zip215");let I=yn(h),P=h[E-1];I[E-1]=P&-129;let B=rt(I),T=g?c:s.ORDER;Cr("point.y",B,Ct,T);let F=u(B*B),Z=u(F-ge),U=u(D*F-v),{isValid:y,value:w}=l(Z,U);if(!y)throw new Error("bad point: invalid y coordinate");let _=(w&ge)===ge,S=(P&128)!==0;if(!g&&w===Ct&&S)throw new Error("bad point: x=0 and x_0=1");return S!==_&&(w=u(-w)),d.fromAffine({x:w,y:B})}static fromHex(h,g=!1){return d.fromBytes(Dr(h),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,g=!0){return p.createCache(this,h),g||this.multiply(Ti),this}assertValidity(){let h=this,{a:g,d:E}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:v,Y:D,Z:I,T:P}=h,B=u(v*v),T=u(D*D),F=u(I*I),Z=u(F*F),U=u(B*g),y=u(F*u(U+T)),w=u(Z+u(E*u(B*T)));if(y!==w)throw new Error("bad point: equation left != right (1)");let _=u(v*D),S=u(I*P);if(_!==S)throw new Error("bad point: equation left != right (2)")}equals(h){m(h);let{X:g,Y:E,Z:v}=this,{X:D,Y:I,Z:P}=h,B=u(g*P),T=u(D*v),F=u(E*P),Z=u(I*v);return B===T&&F===Z}is0(){return this.equals(d.ZERO)}negate(){return new d(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:h}=i,{X:g,Y:E,Z:v}=this,D=u(g*g),I=u(E*E),P=u(Ti*u(v*v)),B=u(h*D),T=g+E,F=u(u(T*T)-D-I),Z=B+I,U=Z-P,y=B-I,w=u(F*U),_=u(Z*y),S=u(F*y),x=u(U*Z);return new d(w,_,x,S)}add(h){m(h);let{a:g,d:E}=i,{X:v,Y:D,Z:I,T:P}=this,{X:B,Y:T,Z:F,T:Z}=h,U=u(v*B),y=u(D*T),w=u(P*E*Z),_=u(I*F),S=u((v+D)*(B+T)-U-y),x=_-w,A=_+w,L=u(y-g*U),C=u(S*x),R=u(A*L),N=u(S*L),z=u(x*A);return new d(C,R,z,N)}subtract(h){return m(h),this.add(h.negate())}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=p.cached(this,h,v=>er(d,v));return er(d,[g,E])[0]}multiplyUnsafe(h){if(!o.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Ct?d.ZERO:this.is0()||h===ge?this:p.unsafe(this,h,g=>er(d,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(h){let g=this,E=h,{X:v,Y:D,Z:I}=g,P=g.is0();E==null&&(E=P?wp:s.inv(I));let B=u(v*E),T=u(D*E),F=s.mul(I,E);if(P)return{x:Ct,y:ge};if(F!==ge)throw new Error("invZ was invalid");return{x:B,y:T}}clearCofactor(){return a===ge?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:g}=this.toAffine(),E=s.toBytes(g);return E[E.length-1]|=h&ge?128:0,E}toHex(){return Ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new Or(d,o.BITS);return o.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var So=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){bi()}static fromHex(e){bi()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Ir(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.ep.precompute(e,r),this}};function cl(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=r;Ge(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=t,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(je(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=s.randomBytes===void 0?pn:s.randomBytes,m=s.adjustScalarBytes===void 0?y=>y:s.adjustScalarBytes,d=s.domain===void 0?(y,w,_)=>{if($e(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return y}:s.domain;function p(y){return c.create(rt(y))}function b(y){let w=B.secretKey;H(y,B.secretKey,"secretKey");let _=H(n(y),2*w,"hashedSecretKey"),S=m(_.slice(0,w)),x=_.slice(w,2*w),A=p(S);return{head:S,prefix:x,scalar:A}}function h(y){let{head:w,prefix:_,scalar:S}=b(y),x=i.multiply(S),A=x.toBytes();return{head:w,prefix:_,scalar:S,point:x,pointBytes:A}}function g(y){return h(y).pointBytes}function E(y=Uint8Array.of(),...w){let _=pe(...w);return p(n(d(_,H(y,void 0,"context"),!!o)))}function v(y,w,_={}){y=H(y,void 0,"message"),o&&(y=o(y));let{prefix:S,scalar:x,pointBytes:A}=h(w),L=E(_.context,S,y),C=i.multiply(L).toBytes(),R=E(_.context,C,A,y),N=c.create(L+R*x);if(!c.isValid(N))throw new Error("sign failed: invalid s");let z=pe(C,c.toBytes(N));return H(z,B.signature,"result")}let D={zip215:s.zip215};function I(y,w,_,S=D){let{context:x}=S,A=S.zip215===void 0?!!D.zip215:S.zip215,L=B.signature;y=H(y,L,"signature"),w=H(w,void 0,"message"),_=H(_,B.publicKey,"publicKey"),A!==void 0&&$e(A,"zip215"),o&&(w=o(w));let C=L/2,R=y.subarray(0,C),N=rt(y.subarray(C,L)),z,G,K;try{z=t.fromBytes(_,A),G=t.fromBytes(R,A),K=i.multiplyUnsafe(N)}catch{return!1}if(!A&&z.isSmallOrder())return!1;let de=E(x,R,_,w);return G.add(z.multiplyUnsafe(de)).subtract(K).clearCofactor().is0()}let P=a.BYTES,B={secretKey:P,publicKey:P,signature:2*P,seed:P};function T(y){return y=y===void 0?f(B.seed):y,H(y,B.seed,"seed")}function F(y){return Zt(y)&&y.length===B.secretKey}function Z(y,w){try{return!!t.fromBytes(y,w===void 0?D.zip215:w)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:T,isValidSecretKey:F,isValidPublicKey:Z,toMontgomery(y){let{y:w}=t.fromBytes(y),_=B.publicKey,S=_===32;if(!S&&_!==57)throw new Error("only defined for 25519 and 448");let x=S?a.div(ge+w,ge-w):a.div(w-ge,w+ge);return a.toBytes(x)},toMontgomerySecret(y){let w=B.secretKey;H(y,w);let _=n(y.subarray(0,w));return m(_).subarray(0,w)}};return Object.freeze(B),Object.freeze(U),Object.freeze({keygen:Eo(T,g),getPublicKey:g,sign:v,verify:I,utils:U,Point:t,lengths:B})}function xn(t,e){if(je(t),je(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(t<0||t>2**(8*e)-1)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function Ep(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function Sp(t){if(!Zt(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof t=="string"?bo(t):t;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ii(t,e,r,n){H(t),je(r),e=Sp(e),e.length>255&&(e=n(pe(bo("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=n,i=Math.ceil(r/s);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=pe(e,xn(e.length,1)),c=new Uint8Array(o),u=xn(r,2),l=new Array(i),f=n(pe(c,t,u,xn(0,1),a));l[0]=n(pe(f,xn(1,1),a));for(let d=1;d<i;d++){let p=[Ep(f,l[d-1]),xn(d+1,1),a];l[d]=n(pe(...p))}return pe(...l).slice(0,r)}var ul="HashToScalar-";var vp=BigInt(0),yt=BigInt(1),ll=BigInt(2);var _p=BigInt(5),Ap=BigInt(8),Pr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bi={p:Pr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ap,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tp(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),o=Pr,a=t*t%o*t%o,c=te(a,ll,o)*a%o,u=te(c,yt,o)*t%o,l=te(u,_p,o)*u%o,f=te(l,e,o)*l%o,m=te(f,r,o)*f%o,d=te(m,n,o)*m%o,p=te(d,s,o)*d%o,b=te(p,s,o)*d%o,h=te(b,e,o)*l%o;return{pow_p_5_8:te(h,ll,o)*t%o,b2:a}}function Ip(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Di=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ri(t,e){let r=Pr,n=le(e*e*e,r),s=le(n*n*e,r),o=Tp(t*s).pow_p_5_8,i=le(t*n*o,r),a=le(e*i*i,r),c=i,u=le(i*Di,r),l=a===t,f=a===le(-t,r),m=a===le(-t*Di,r);return l&&(i=c),(f||m)&&(i=u),mt(i,r)&&(i=le(-i,r)),{isValid:l||f,value:i}}var Bt=al(Bi,{uvRatio:Ri}),Lt=Bt.Fp,hl=Bt.Fn;function Dp(t){return cl(Bt,ho,Object.assign({adjustScalarBytes:Ip,zip215:!0},t))}var pl=Dp({});var Ci=Di,Cp=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Lp=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Bp=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Rp=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fl=t=>Ri(yt,t),Op=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Li=t=>Lt.create(rt(t)&Op);function dl(t){let{d:e}=Bi,r=Pr,n=g=>Lt.create(g),s=n(Ci*t*t),o=n((s+yt)*Bp),i=BigInt(-1),a=n((i-e*s)*n(s+e)),{isValid:c,value:u}=Ri(o,a),l=n(u*t);mt(l,r)||(l=n(-l)),c||(u=l),c||(i=s);let f=n(i*(s-yt)*Rp-a),m=u*u,d=n((u+u)*a),p=n(f*Cp),b=n(yt-m),h=n(yt+m);return new Bt(n(d*h),n(b*p),n(p*h),n(d*b))}var Rt=class t extends So{static BASE=new t(Bt.BASE);static ZERO=new t(Bt.ZERO);static Fp=Lt;static Fn=hl;constructor(e){super(e)}static fromAffine(e){return new t(Bt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){Ue(e,32);let{a:r,d:n}=Bi,s=Pr,o=D=>Lt.create(D),i=Li(e);if(!zu(Lt.toBytes(i),e)||mt(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(yt+r*a),u=o(yt-r*a),l=o(c*c),f=o(u*u),m=o(r*n*l-f),{isValid:d,value:p}=fl(o(m*f)),b=o(p*u),h=o(p*b*m),g=o((i+i)*b);mt(g,s)&&(g=o(-g));let E=o(c*h),v=o(g*E);if(!d||mt(v,s)||E===vp)throw new Error("invalid ristretto255 encoding 2");return new t(new Bt(g,E,yt,v))}static fromHex(e){return t.fromBytes(ln(e))}toBytes(){let{X:e,Y:r,Z:n,T:s}=this.ep,o=Pr,i=h=>Lt.create(h),a=i(i(n+r)*i(n-r)),c=i(e*r),u=i(c*c),{value:l}=fl(i(a*u)),f=i(l*a),m=i(l*c),d=i(f*m*s),p;if(mt(s*d,o)){let h=i(r*Ci),g=i(e*Ci);e=h,r=g,p=i(f*Lp)}else p=m;mt(e*d,o)&&(r=i(-r));let b=i((n-r)*p);return mt(b,o)&&(b=i(-b)),Lt.toBytes(b)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:s,Y:o}=e.ep,i=u=>Lt.create(u),a=i(r*o)===i(n*s),c=i(n*o)===i(r*s);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Rt.BASE);Object.freeze(Rt.ZERO);Object.freeze(Rt.prototype);Object.freeze(Rt);var Pp=Object.freeze({Point:Rt,hashToCurve(t,e){let r=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ii(t,r,64,ho);return Pp.deriveToCurve(n)},hashToScalar(t,e={DST:ul}){let r=Ii(t,e.DST,64,ho);return hl.create(rt(r))},deriveToCurve(t){Ue(t,64);let e=Li(t.subarray(0,32)),r=dl(e),n=Li(t.subarray(32,64)),s=dl(n);return new Rt(r.add(s))}});var En=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},vo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qe={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new vo("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 _o=32;var Oi,Np=(async()=>{try{return await qe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Fp(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await qe.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await qe.get().subtle.verify({name:"Ed25519"},n,Fe(e),Fe(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Up(t,e,r){return pl.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function ml(t,e,r){return Oi==null&&(Oi=await Np),Oi?Fp(t,e,r):Up(t,e,r)}function Mp(t){return t?.buffer instanceof ArrayBuffer}function Pi(t){if(Mp(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function tr(t,e){e==null&&(e=t.reduce((s,o)=>s+o.length,0));let r=Gt(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return Pi(r)}function Ao(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var To=class{type="Ed25519";raw;constructor(e){this.raw=Ni(e,_o)}toMultihash(){return Ve.digest(et(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let s=ml(this.raw,r,e);return Ao(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Fi(t){return t=Ni(t,_o),new To(t)}function Ni(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new se(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}function Ot(t=0){return new Uint8Array(t)}var Kp=Math.pow(2,7),qp=Math.pow(2,14),zp=Math.pow(2,21),gl=Math.pow(2,28),bl=Math.pow(2,35),wl=Math.pow(2,42),xl=Math.pow(2,49),Ie=128,Pt=127;function Sn(t){if(t<Kp)return 1;if(t<qp)return 2;if(t<zp)return 3;if(t<gl)return 4;if(t<bl)return 5;if(t<wl)return 6;if(t<xl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function El(t,e,r=0){switch(Sn(t)){case 8:e[r++]=t&255|Ie,t/=128;case 7:e[r++]=t&255|Ie,t/=128;case 6:e[r++]=t&255|Ie,t/=128;case 5:e[r++]=t&255|Ie,t/=128;case 4:e[r++]=t&255|Ie,t>>>=7;case 3:e[r++]=t&255|Ie,t>>>=7;case 2:e[r++]=t&255|Ie,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Sl(t,e){let r=t[e],n=0;if(n+=r&Pt,r<Ie||(r=t[e+1],n+=(r&Pt)<<7,r<Ie)||(r=t[e+2],n+=(r&Pt)<<14,r<Ie)||(r=t[e+3],n+=(r&Pt)<<21,r<Ie)||(r=t[e+4],n+=(r&Pt)*gl,r<Ie)||(r=t[e+5],n+=(r&Pt)*bl,r<Ie)||(r=t[e+6],n+=(r&Pt)*wl,r<Ie)||(r=t[e+7],n+=(r&Pt)*xl,r<Ie))return n;throw new RangeError("Could not decode varint")}var Ui=new Float32Array([-0]),Nt=new Uint8Array(Ui.buffer);function vl(t,e,r){Ui[0]=t,e[r]=Nt[0],e[r+1]=Nt[1],e[r+2]=Nt[2],e[r+3]=Nt[3]}function _l(t,e){return Nt[0]=t[e],Nt[1]=t[e+1],Nt[2]=t[e+2],Nt[3]=t[e+3],Ui[0]}var Mi=new Float64Array([-0]),Se=new Uint8Array(Mi.buffer);function Al(t,e,r){Mi[0]=t,e[r]=Se[0],e[r+1]=Se[1],e[r+2]=Se[2],e[r+3]=Se[3],e[r+4]=Se[4],e[r+5]=Se[5],e[r+6]=Se[6],e[r+7]=Se[7]}function Tl(t,e){return Se[0]=t[e],Se[1]=t[e+1],Se[2]=t[e+2],Se[3]=t[e+3],Se[4]=t[e+4],Se[5]=t[e+5],Se[6]=t[e+6],Se[7]=t[e+7],Mi[0]}var Vp=BigInt(Number.MAX_SAFE_INTEGER),Hp=BigInt(Number.MIN_SAFE_INTEGER),Me=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+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 r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(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,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return rr;if(e<Vp&&e>Hp)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,s=e-(n<<32n);return r&&(n=~n|0n,s=~s|0n,++s>Il&&(s=0n,++n>Il&&(n=0n))),new t(Number(s),Number(n))}static fromNumber(e){if(e===0)return rr;let r=e<0;r&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return r&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new t(n,s)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):rr}},rr=new Me(0,0);rr.toBigInt=function(){return 0n};rr.zzEncode=rr.zzDecode=function(){return this};rr.length=function(){return 1};var Il=4294967296n;function Dl(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Cl(t,e,r){if(r-e<1)return"";let s,o=[],i=0,a;for(;e<r;)a=t[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function ki(t,e,r){let n=r,s,o;for(let i=0;i<t.length;++i)s=t.charCodeAt(i),s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=s&63|128):(s&64512)===55296&&((o=t.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128);return r-n}function We(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Io(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Ki=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,We(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 We(this,4);return Io(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw We(this,4);return Io(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw We(this,4);let e=_l(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw We(this,4);let e=Tl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw We(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Cl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw We(this,e);this.pos+=e}else do if(this.pos>=this.len)throw We(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 Me(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*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;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw We(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw We(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw We(this,8);let e=Io(this.buf,this.pos+=4),r=Io(this.buf,this.pos+=4);return new Me(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Sl(this.buf,this.pos);return this.pos+=Sn(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 vn(t){return new Ki(t instanceof Uint8Array?t:t.subarray())}function Be(t,e,r){let n=vn(t);return e.decode(n,void 0,r)}var $i={};J($i,{base10:()=>Xp});var Ox=new Uint8Array(0);function Bl(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function gt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Rl(t){return new TextEncoder().encode(t)}function Ol(t){return new TextDecoder().decode(t)}function $p(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<t.length;s++){var o=t.charAt(s),i=o.charCodeAt(0);if(r[i]!==255)throw new TypeError(o+" is ambiguous");r[i]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,g=0,E=p.length;g!==E&&p[g]===0;)g++,b++;for(var v=(E-g)*l+1>>>0,D=new Uint8Array(v);g!==E;){for(var I=p[g],P=0,B=v-1;(I!==0||P<h)&&B!==-1;B--,P++)I+=256*D[B]>>>0,D[B]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");h=P,g++}for(var T=v-h;T!==v&&D[T]===0;)T++;for(var F=c.repeat(b);T<v;++T)F+=t.charAt(D[T]);return F}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,g=0;p[b]===c;)h++,b++;for(var E=(p.length-b)*u+1>>>0,v=new Uint8Array(E);p[b];){var D=r[p.charCodeAt(b)];if(D===255)return;for(var I=0,P=E-1;(D!==0||I<g)&&P!==-1;P--,I++)D+=a*v[P]>>>0,v[P]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");g=I,b++}if(p[b]!==" "){for(var B=E-g;B!==E&&v[B]===0;)B++;for(var T=new Uint8Array(h+(E-B)),F=h;B!==E;)T[F++]=v[B++];return T}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var jp=$p,Gp=jp,Nl=Gp;var qi=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},zi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let s=r.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Fl(this,e)}},Vi=class{decoders;constructor(e){this.decoders=e}or(e){return Fl(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 Fl(t,e){return new Vi({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Hi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,s){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=s,this.encoder=new qi(e,r,n),this.decoder=new zi(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Nr({name:t,prefix:e,encode:r,decode:n}){return new Hi(t,e,r,n)}function Ft({name:t,prefix:e,alphabet:r}){let{encode:n,decode:s}=Nl(r,t);return Nr({prefix:e,name:t,encode:n,decode:o=>gt(s(o))})}function Wp(t,e,r,n){let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),i=0,a=0,c=0;for(let u=0;u<s;++u){let l=e[t[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Yp(t,e,r){let n=e[e.length-1]==="=",s=(1<<r)-1,o="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<r-i]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function Zp(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function ce({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let s=Zp(n);return Nr({prefix:e,name:t,encode(o){return Yp(o,n,r)},decode(o){return Wp(o,s,r,t)}})}var Xp=Ft({prefix:"9",name:"base10",alphabet:"0123456789"});var ji={};J(ji,{base16:()=>Qp,base16upper:()=>Jp});var Qp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Gi={};J(Gi,{base2:()=>em});var em=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Wi={};J(Wi,{base256emoji:()=>sm});var Ul=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}"),tm=Ul.reduce((t,e,r)=>(t[r]=e,t),[]),rm=Ul.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function nm(t){return t.reduce((e,r)=>(e+=tm[r],e),"")}function om(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let s=rm[n];if(s==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(s)}return new Uint8Array(e)}var sm=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:nm,decode:om});var Yi={};J(Yi,{base32:()=>Fr,base32hex:()=>um,base32hexpad:()=>fm,base32hexpadupper:()=>dm,base32hexupper:()=>lm,base32pad:()=>am,base32padupper:()=>cm,base32upper:()=>im,base32z:()=>hm});var Fr=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),im=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),am=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),um=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),lm=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),dm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hm=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zi={};J(Zi,{base36:()=>_n,base36upper:()=>pm});var _n=Ft({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pm=Ft({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xi={};J(Xi,{base58btc:()=>nt,base58flickr:()=>mm});var nt=Ft({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mm=Ft({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qi={};J(Qi,{base64:()=>ym,base64pad:()=>gm,base64url:()=>bm,base64urlpad:()=>wm});var ym=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bm=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),wm=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ji={};J(Ji,{base8:()=>xm});var xm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ea={};J(ea,{identity:()=>Em});var Em=Nr({prefix:"\0",name:"identity",encode:t=>Ol(t),decode:t=>Rl(t)});var Yx=new TextEncoder,Zx=new TextDecoder;var ra={};J(ra,{identity:()=>Hm});var _m=Kl,Ml=128,Am=127,Tm=~Am,Im=Math.pow(2,31);function Kl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Im;)e[r++]=t&255|Ml,t/=128;for(;t&Tm;)e[r++]=t&255|Ml,t>>>=7;return e[r]=t|0,Kl.bytes=r-n+1,e}var Dm=ta,Cm=128,kl=127;function ta(t,n){var r=0,n=n||0,s=0,o=n,i,a=t.length;do{if(o>=a)throw ta.bytes=0,new RangeError("Could not decode varint");i=t[o++],r+=s<28?(i&kl)<<s:(i&kl)*Math.pow(2,s),s+=7}while(i>=Cm);return ta.bytes=o-n,r}var Lm=Math.pow(2,7),Bm=Math.pow(2,14),Rm=Math.pow(2,21),Om=Math.pow(2,28),Pm=Math.pow(2,35),Nm=Math.pow(2,42),Fm=Math.pow(2,49),Um=Math.pow(2,56),Mm=Math.pow(2,63),km=function(t){return t<Lm?1:t<Bm?2:t<Rm?3:t<Om?4:t<Pm?5:t<Nm?6:t<Fm?7:t<Um?8:t<Mm?9:10},Km={encode:_m,decode:Dm,encodingLength:km},qm=Km,An=qm;function Tn(t,e=0){return[An.decode(t,e),An.decode.bytes]}function Ur(t,e,r=0){return An.encode(t,e,r),e}function Mr(t){return An.encodingLength(t)}function Kr(t,e){let r=e.byteLength,n=Mr(t),s=n+Mr(r),o=new Uint8Array(s+r);return Ur(t,o,0),Ur(r,o,n),o.set(e,s),new kr(t,r,e,o)}function ql(t){let e=gt(t),[r,n]=Tn(e),[s,o]=Tn(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new kr(r,s,i,e)}function zl(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Bl(t.bytes,r.bytes)}}var kr=class{code;size;digest;bytes;constructor(e,r,n,s){this.code=e,this.size=r,this.digest=n,this.bytes=s}};var Vl=0,zm="identity",Hl=gt;function Vm(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Kr(Vl,Hl(t))}var Hm={code:Vl,name:zm,encode:Hl,digest:Vm};var sa={};J(sa,{sha256:()=>jm,sha512:()=>Gm});var $m=20;function oa({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:s}){return new na(t,e,r,n,s)}var na=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,s,o){this.name=e,this.code=r,this.encode=n,this.minDigestLength=s??$m,this.maxDigestLength=o}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.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?$l(n,this.code,r?.truncate):n.then(s=>$l(s,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function $l(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Kr(e,t)}function Gl(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var jm=oa({name:"sha2-256",code:18,encode:Gl("SHA-256")}),Gm=oa({name:"sha2-512",code:19,encode:Gl("SHA-512")});function Wl(t,e){let{bytes:r,version:n}=t;return n===0?Ym(r,ia(t),e??nt.encoder):Zm(r,ia(t),e??Fr.encoder)}var Yl=new WeakMap;function ia(t){let e=Yl.get(t);if(e==null){let r=new Map;return Yl.set(t,r),r}return e}var Co=class t{code;version;multihash;bytes;"/";constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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:r}=this;if(e!==Dn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Xm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Kr(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&zl(e.multihash,n.multihash)}toString(e){return Wl(this,e)}toJSON(){return{"/":Wl(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:o,bytes:i}=r;return new t(n,s,o,i??Zl(n,s,o.bytes))}else if(r[Qm]===!0){let{version:n,multihash:s,code:o}=r,i=ql(s);return t.create(n,o,i)}else return null}static create(e,r,n){if(typeof r!="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(r!==Dn)throw new Error(`Version 0 CID must use dag-pb (code: ${Dn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let s=Zl(e,r,n.bytes);return new t(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Dn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,s=gt(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=s.subarray(r.multihashSize-r.digestSize),i=new kr(r.multihashCode,r.digestSize,o,s);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,m]=Tn(e.subarray(r));return r+=m,f},s=n(),o=Dn;if(s===18?(s=0,r=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=r,a=n(),c=n(),u=r+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,s]=Wm(e,r),o=t.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ia(o).set(n,e),o}};function Wm(t,e){switch(t[0]){case"Q":{let r=e??nt;return[nt.prefix,r.decode(`${nt.prefix}${t}`)]}case nt.prefix:{let r=e??nt;return[nt.prefix,r.decode(t)]}case Fr.prefix:{let r=e??Fr;return[Fr.prefix,r.decode(t)]}case _n.prefix:{let r=e??_n;return[_n.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Ym(t,e,r){let{prefix:n}=r;if(n!==nt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return s}function Zm(t,e,r){let{prefix:n}=r,s=e.get(n);if(s==null){let o=r.encode(t);return e.set(n,o),o}else return s}var Dn=112,Xm=18;function Zl(t,e,r){let n=Mr(t),s=n+Mr(e),o=new Uint8Array(s+r.byteLength);return Ur(t,o,0),Ur(e,o,n),o.set(r,s),o}var Qm=Symbol.for("@ipld/js-cid/CID");var aa={...ea,...Gi,...Ji,...$i,...ji,...Yi,...Zi,...Xi,...Qi,...Wi},bE={...sa,...ra};function Ql(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Xl=Ql("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ca=Ql("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Ot(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Jm={utf8:Xl,"utf-8":Xl,hex:aa.base16,latin1:ca,ascii:ca,binary:ca,...aa},Jl=Jm;function ef(t,e="utf8"){let r=Jl[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function ua(t){let e=t??8192,r=e>>>1,n,s=e;return function(i){if(i<1||i>r)return Ot(i);s+i>e&&(n=Ot(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var nr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function la(){}var da=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},e0=ua();function t0(t){return globalThis.Buffer!=null?Ot(t):e0(t)}var Ln=class{len;head;tail;states;constructor(){this.len=0,this.head=new nr(la,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new nr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ha((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(Lo,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Me.fromBigInt(e);return this._push(Lo,r.length(),r)}uint64Number(e){return this._push(El,Sn(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 r=Me.fromBigInt(e).zzEncode();return this._push(Lo,r.length(),r)}sint64Number(e){let r=Me.fromNumber(e).zzEncode();return this._push(Lo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fa,1,e?1:0)}fixed32(e){return this._push(Cn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Me.fromBigInt(e);return this._push(Cn,4,r.lo)._push(Cn,4,r.hi)}fixed64Number(e){let r=Me.fromNumber(e);return this._push(Cn,4,r.lo)._push(Cn,4,r.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(vl,4,e)}double(e){return this._push(Al,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(fa,1,0):this.uint32(r)._push(n0,r,e)}string(e){let r=Dl(e);return r!==0?this.uint32(r)._push(ki,r,e):this._push(fa,1,0)}fork(){return this.states=new da(this),this.head=this.tail=new nr(la,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 nr(la,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=t0(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function fa(t,e,r){e[r]=t&255}function r0(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var ha=class extends nr{next;constructor(e,r){super(r0,e,r),this.next=void 0}};function Lo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function Cn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function n0(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Ln.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(o0,e,t),this},Ln.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(s0,e,t),this});function o0(t,e,r){e.set(t,r)}function s0(t,e,r){t.length<40?ki(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(ef(t),r)}function pa(){return new Ln}function Re(t,e){let r=pa();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Oe(t,e,r){let n=vn(t);yield*e.stream(n,void 0,"$",r)}var Bo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ro(t,e,r,n,s){return{name:t,type:e,encode:r,decode:n,stream:s}}function or(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return Ro("enum",Bo.VARINT,r,n,s)}function Pe(t,e,r){return Ro("message",Bo.LENGTH_DELIMITED,t,e,r)}var sr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ne||(ne={}));var ma;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ma||(ma={}));(function(t){t.codec=()=>or(ma)})(ne||(ne={}));var ot;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(ot||(ot={}));var ya;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(ya||(ya={}));var Rn={};J(Rn,{MAX_RSA_KEY_SIZE:()=>ga,generateRSAKeyPair:()=>sf,jwkToJWKKeyPair:()=>af,jwkToPkcs1:()=>u0,jwkToPkix:()=>Ea,jwkToRSAPrivateKey:()=>Aa,pkcs1MessageToJwk:()=>wa,pkcs1MessageToRSAPrivateKey:()=>Sa,pkcs1ToJwk:()=>c0,pkcs1ToRSAPrivateKey:()=>of,pkixMessageToJwk:()=>xa,pkixMessageToRSAPublicKey:()=>_a,pkixToJwk:()=>l0,pkixToRSAPublicKey:()=>va});var qr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Rn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return fe.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){return nf(this.jwk,r,e,n)}},Bn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=Rn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,r){return rf(this.jwk,e,r)}};var ga=8192,ba=18,i0=1062,a0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function c0(t){let e=ft(t);return wa(e)}function wa(t){return{n:V(t[1],"base64url"),e:V(t[2],"base64url"),d:V(t[3],"base64url"),p:V(t[4],"base64url"),q:V(t[5],"base64url"),dp:V(t[6],"base64url"),dq:V(t[7],"base64url"),qi:V(t[8],"base64url"),kty:"RSA"}}function u0(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new se("JWK was missing components");return _t([Le(Uint8Array.from([0])),Le(k(t.n,"base64url")),Le(k(t.e,"base64url")),Le(k(t.d,"base64url")),Le(k(t.p,"base64url")),Le(k(t.q,"base64url")),Le(k(t.dp,"base64url")),Le(k(t.dq,"base64url")),Le(k(t.qi,"base64url"))]).subarray()}function l0(t){let e=ft(t,{offset:0});return xa(e)}function xa(t){let e=ft(t[1],{offset:0});return{kty:"RSA",n:V(e[0],"base64url"),e:V(e[1],"base64url")}}function Ea(t){if(t.n==null||t.e==null)throw new se("JWK was missing components");return _t([a0,io(_t([Le(k(t.n,"base64url")),Le(k(t.e,"base64url"))]))]).subarray()}function of(t){let e=ft(t);return Sa(e)}function Sa(t){let e=wa(t);return Aa(e)}function va(t,e){if(t.byteLength>=i0)throw new yr("Key size is too large");let r=ft(t,{offset:0});return _a(r,t,e)}function _a(t,e,r){let n=xa(t);if(r==null){let s=Tr(ot.encode({Type:ne.RSA,Data:e}));r=Qe(ba,s)}return new qr(n,r)}function Aa(t){if(uf(t)>ga)throw new se("Key size is too large");let e=af(t),r=Tr(ot.encode({Type:ne.RSA,Data:Ea(e.publicKey)})),n=Qe(ba,r);return new Bn(e.privateKey,new qr(e.publicKey,n))}async function sf(t){if(t>ga)throw new se("Key size is too large");let e=await cf(t),r=Tr(ot.encode({Type:ne.RSA,Data:Ea(e.publicKey)})),n=Qe(ba,r);return new Bn(e.privateKey,new qr(e.publicKey,n))}function af(t){if(t==null)throw new se("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function cf(t,e){let r=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await f0(r,e);return{privateKey:n[0],publicKey:n[1]}}async function rf(t,e,r){let n=await qe.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let s=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Fe(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function nf(t,e,r,n){let s=await qe.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,Fe(e),Fe(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),o}async function f0(t,e){if(t.privateKey==null||t.publicKey==null)throw new se("Private and public key are required");let r=await Promise.all([qe.get().subtle.exportKey("jwk",t.privateKey),qe.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function uf(t){if(t.kty!=="RSA")throw new se("invalid key type");if(t.n==null)throw new se("invalid key modulus");return k(t.n,"base64url").length*8}var Oo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(ao(e),Ue(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),ht(s)}update(e){return Ar(this),this.iHash.update(e),this}digestInto(e){Ar(this),co(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),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:r,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},lf=(()=>{let t=((e,r,n)=>new Oo(e,r).update(n).digest());return t.create=(e,r)=>new Oo(e,r),t})();var ff=(t,e)=>(t+(t>=0?e:-e)/df)/e;function d0(t,e,r){Cr("scalar",t,st,r);let[[n,s],[o,i]]=e,a=ff(i*t,r),c=ff(-s*t,r),u=t-a*n-c*o,l=-a*s-c*i,f=u<st,m=l<st;f&&(u=-u),m&&(l=-l);let d=gn(Math.ceil(Lr(r)/2))+Ut;if(u<st||u>=d||l<st||l>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:l}}function Ia(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ta(t,e){Ge(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return $e(r.lowS,"lowS"),$e(r.prehash,"prehash"),r.format!==void 0&&Ia(r.format),r}var Da=class extends Error{constructor(e=""){super(e)}},Ye={Err:Da,_tlv:{encode:(t,e)=>{let{Err:r}=Ye;if(je(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,s=mn(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?mn(s.length/2|128):"";return mn(t)+o+s+e},decode(t,e){let{Err:r}=Ye;e=H(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Ye;if(yo(t),t<st)throw new e("integer: negative integers are not allowed");let r=mn(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ye;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xt(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ye,s=H(t,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ye,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),o=n+s;return e.encode(48,o)}};Object.freeze(Ye._tlv);Object.freeze(Ye._int);Object.freeze(Ye);var st=BigInt(0),Ut=BigInt(1),df=BigInt(2),Po=BigInt(3),h0=BigInt(4);function hf(t,e={}){let r=xo("weierstrass",t,e),n=r.Fp,s=r.Fn,o=r.CURVE,{h:i,n:a}=o;Ge(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=mf(n,s);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(U,y,w){if(u&&y.is0())return Uint8Array.of(0);let{x:_,y:S}=y.toAffine(),x=n.toBytes(_);if($e(w,"isCompressed"),w){f();let A=!n.isOdd(S);return pe(pf(A),x)}else return pe(Uint8Array.of(4),x,n.toBytes(S))}function d(U){H(U,void 0,"Point");let{publicKey:y,publicKeyUncompressed:w}=l,_=U.length,S=U[0],x=U.subarray(1);if(u&&_===1&&S===0)return{x:n.ZERO,y:n.ZERO};if(_===y&&(S===2||S===3)){let A=n.fromBytes(x);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let L=h(A),C;try{C=n.sqrt(L)}catch(z){let G=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();let R=n.isOdd(C);return(S&1)===1!==R&&(C=n.neg(C)),{x:A,y:C}}else if(_===w&&S===4){let A=n.BYTES,L=n.fromBytes(x.subarray(0,A)),C=n.fromBytes(x.subarray(A,A*2));if(!g(L,C))throw new Error("bad point: is not on curve");return{x:L,y:C}}else throw new Error(`bad point: got length ${_}, expected compressed=${y} or uncompressed=${w}`)}let p=e.toBytes===void 0?m:e.toBytes,b=e.fromBytes===void 0?d:e.fromBytes;function h(U){let y=n.sqr(U),w=n.mul(y,U);return n.add(n.add(w,n.mul(U,o.a)),o.b)}function g(U,y){let w=n.sqr(y),_=h(U);return n.eql(w,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(o.a,Po),h0),v=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(E,v)))throw new Error("bad curve params: a or b");function D(U,y,w=!1){if(!n.isValid(y)||w&&n.is0(y))throw new Error(`bad point coordinate ${U}`);return y}function I(U){if(!(U instanceof T))throw new Error("Weierstrass Point expected")}function P(U){if(!c||!c.basises)throw new Error("no endo");return d0(U,c.basises,s.ORDER)}function B(U,y,w,_,S){return w=new T(n.mul(w.X,U),w.Y,w.Z),y=wn(_,y),w=wn(S,w),y.add(w)}class T{static BASE=new T(o.Gx,o.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(y,w,_){this.X=D("x",y),this.Y=D("y",w,!0),this.Z=D("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){let{x:w,y:_}=y||{};if(!y||!n.isValid(w)||!n.isValid(_))throw new Error("invalid affine point");if(y instanceof T)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(_)?T.ZERO:new T(w,_,n.ONE)}static fromBytes(y){let w=T.fromAffine(b(H(y,void 0,"point")));return w.assertValidity(),w}static fromHex(y){return T.fromBytes(Dr(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,w=!0){return Z.createCache(this,y),w||this.multiply(Po),this}assertValidity(){let y=this;if(y.is0()){if(e.allowInfinityPoint&&n.is0(y.X)&&n.eql(y.Y,n.ONE)&&n.is0(y.Z))return;throw new Error("bad point: ZERO")}let{x:w,y:_}=y.toAffine();if(!n.isValid(w)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!g(w,_))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(y)}equals(y){I(y);let{X:w,Y:_,Z:S}=this,{X:x,Y:A,Z:L}=y,C=n.eql(n.mul(w,L),n.mul(x,S)),R=n.eql(n.mul(_,L),n.mul(A,S));return C&&R}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:y,b:w}=o,_=n.mul(w,Po),{X:S,Y:x,Z:A}=this,L=n.ZERO,C=n.ZERO,R=n.ZERO,N=n.mul(S,S),z=n.mul(x,x),G=n.mul(A,A),K=n.mul(S,x);return K=n.add(K,K),R=n.mul(S,A),R=n.add(R,R),L=n.mul(y,R),C=n.mul(_,G),C=n.add(L,C),L=n.sub(z,C),C=n.add(z,C),C=n.mul(L,C),L=n.mul(K,L),R=n.mul(_,R),G=n.mul(y,G),K=n.sub(N,G),K=n.mul(y,K),K=n.add(K,R),R=n.add(N,N),N=n.add(R,N),N=n.add(N,G),N=n.mul(N,K),C=n.add(C,N),G=n.mul(x,A),G=n.add(G,G),N=n.mul(G,K),L=n.sub(L,N),R=n.mul(G,z),R=n.add(R,R),R=n.add(R,R),new T(L,C,R)}add(y){I(y);let{X:w,Y:_,Z:S}=this,{X:x,Y:A,Z:L}=y,C=n.ZERO,R=n.ZERO,N=n.ZERO,z=o.a,G=n.mul(o.b,Po),K=n.mul(w,x),de=n.mul(_,A),me=n.mul(S,L),ye=n.add(w,_),ue=n.add(x,A);ye=n.mul(ye,ue),ue=n.add(K,de),ye=n.sub(ye,ue),ue=n.add(w,S);let De=n.add(x,L);return ue=n.mul(ue,De),De=n.add(K,me),ue=n.sub(ue,De),De=n.add(_,S),C=n.add(A,L),De=n.mul(De,C),C=n.add(de,me),De=n.sub(De,C),N=n.mul(z,ue),C=n.mul(G,me),N=n.add(C,N),C=n.sub(de,N),N=n.add(de,N),R=n.mul(C,N),de=n.add(K,K),de=n.add(de,K),me=n.mul(z,me),ue=n.mul(G,ue),de=n.add(de,me),me=n.sub(K,me),me=n.mul(z,me),ue=n.add(ue,me),K=n.mul(de,ue),R=n.add(R,K),K=n.mul(De,ue),C=n.mul(ye,C),C=n.sub(C,K),K=n.mul(ye,de),N=n.mul(De,N),N=n.add(N,K),new T(C,R,N)}subtract(y){return I(y),this.add(y.negate())}is0(){return this.equals(T.ZERO)}multiply(y){let{endo:w}=e;if(!s.isValidNot0(y))throw new RangeError("invalid scalar: out of range");let _,S,x=A=>Z.cached(this,A,L=>er(T,L));if(w){let{k1neg:A,k1:L,k2neg:C,k2:R}=P(y),{p:N,f:z}=x(L),{p:G,f:K}=x(R);S=z.add(K),_=B(w.beta,N,G,A,C)}else{let{p:A,f:L}=x(y);_=A,S=L}return er(T,[_,S])[0]}multiplyUnsafe(y){let{endo:w}=e,_=this,S=y;if(!s.isValid(S))throw new RangeError("invalid scalar: out of range");if(S===st||_.is0())return T.ZERO;if(S===Ut)return _;if(Z.hasCache(this))return this.multiply(S);if(w){let{k1neg:x,k1:A,k2neg:L,k2:C}=P(S),{p1:R,p2:N}=il(T,_,A,C);return B(w.beta,R,N,x,L)}else return Z.unsafe(_,S)}toAffine(y){let w=this,_=y,{X:S,Y:x,Z:A}=w;if(n.eql(A,n.ONE))return{x:S,y:x};let L=w.is0();_==null&&(_=L?n.ONE:n.inv(A));let C=n.mul(S,_),R=n.mul(x,_),N=n.mul(A,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(N,n.ONE))throw new Error("invZ was invalid");return{x:C,y:R}}isTorsionFree(){let{isTorsionFree:y}=e;return i===Ut?!0:y?y(T,this):Z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:y}=e;return i===Ut?this:y?y(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ut?this.is0():this.clearCofactor().is0()}toBytes(y=!0){return $e(y,"isCompressed"),this.assertValidity(),p(T,this,y)}toHex(y=!0){return Ir(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let F=s.BITS,Z=new Or(T,e.endo?Math.ceil(F/2):F);return F>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function pf(t){return Uint8Array.of(t?2:3)}function mf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function p0(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?pn:e.randomBytes,s=Object.assign(mf(t.Fp,r),{seed:Math.max(Ei(r.ORDER),16)});function o(d){try{let p=r.fromBytes(d);return r.isValidNot0(p)}catch{return!1}}function i(d,p){let{publicKey:b,publicKeyUncompressed:h}=s;try{let g=d.length;return p===!0&&g!==b||p===!1&&g!==h?!1:!!t.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(s.seed):d,Si(H(d,s.seed,"seed"),r.ORDER)}function c(d,p=!0){return t.BASE.multiply(r.fromBytes(d)).toBytes(p)}function u(d){let{secretKey:p,publicKey:b,publicKeyUncompressed:h}=s,g=r._lengths;if(!Zt(d))return;let E=H(d,void 0,"key").length,v=E===b||E===h,D=E===p||!!g?.includes(E);if(!(v&&D))return v}function l(d,p,b=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(d);return t.fromBytes(p).multiply(h).toBytes(b)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=Eo(a,c);return Object.freeze(f),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:m,Point:t,utils:f,lengths:s})}function yf(t,e,r={}){let n=e;ao(n),Ge(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let s=r.randomBytes===void 0?pn:r.randomBytes,o=r.hmac===void 0?(S,x)=>lf(n,S,x):r.hmac,{Fp:i,Fn:a}=t,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:p}=p0(t,r),b={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=c*df+Ut<i.ORDER;function g(S){let x=c>>Ut;return S>x}function E(S,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return x}function v(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(S,x){Ia(x);let A=p.signature,L=x==="compact"?A:x==="recovered"?A+1:void 0;return H(S,L)}class I{r;s;recovery;constructor(x,A,L){if(this.r=E("r",x),this.s=E("s",A),L!=null){if(v(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,A=b.format){D(x,A);let L;if(A==="der"){let{r:z,s:G}=Ye.toSig(H(x));return new I(z,G)}A==="recovered"&&(L=x[0],A="compact",x=x.subarray(1));let C=p.signature/2,R=x.subarray(0,C),N=x.subarray(C,C*2);return new I(a.fromBytes(R),a.fromBytes(N),L)}static fromHex(x,A){return this.fromBytes(Dr(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new I(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:L}=this,C=this.assertRecovery(),R=C===2||C===3?A+c:A;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let N=i.toBytes(R),z=t.fromBytes(pe(pf((C&1)===0),N)),G=a.inv(R),K=B(H(x,void 0,"msgHash")),de=a.create(-K*G),me=a.create(L*G),ye=t.BASE.multiplyUnsafe(de).add(z.multiplyUnsafe(me));if(ye.is0())throw new Error("invalid recovery: point at infinify");return ye.assertValidity(),ye}hasHighS(){return g(this.s)}toBytes(x=b.format){if(Ia(x),x==="der")return Dr(Ye.hexFromSig(this));let{r:A,s:L}=this,C=a.toBytes(A),R=a.toBytes(L);return x==="recovered"?(v(),pe(Uint8Array.of(this.assertRecovery()),C,R)):pe(C,R)}toHex(x){return Ir(this.toBytes(x))}}Object.freeze(I.prototype),Object.freeze(I);let P=r.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let A=Xt(x),L=x.length*8-u;return L>0?A>>BigInt(L):A}:r.bits2int,B=r.bits2int_modN===void 0?function(x){return a.create(P(x))}:r.bits2int_modN,T=gn(u);function F(S){return Cr("num < 2^"+u,S,st,T),a.toBytes(S)}function Z(S,x){return H(S,void 0,"message"),x?H(n(S),void 0,"prehashed message"):S}function U(S,x,A){let{lowS:L,prehash:C,extraEntropy:R}=Ta(A,b);S=Z(S,C);let N=B(S),z=a.fromBytes(x);if(!a.isValidNot0(z))throw new Error("invalid private key");let G=[F(z),F(N)];if(R!=null&&R!==!1){let ye=R===!0?s(p.secretKey):R;G.push(H(ye,void 0,"extraEntropy"))}let K=pe(...G),de=N;function me(ye){let ue=P(ye);if(!a.isValidNot0(ue))return;let De=a.inv(ue),mr=t.BASE.multiply(ue).toAffine(),Jr=a.create(mr.x);if(Jr===st)return;let Wn=a.create(De*a.create(de+Jr*z));if(Wn===st)return;let Vc=(mr.x===Jr?0:2)|Number(mr.y&Ut),Hc=Wn;return L&&g(Wn)&&(Hc=a.neg(Wn),Vc^=1),new I(Jr,Hc,h?void 0:Vc)}return{seed:K,k2sig:me}}function y(S,x,A={}){let{seed:L,k2sig:C}=U(S,x,A);return Vu(n.outputLen,a.BYTES,o)(L,C).toBytes(A.format)}function w(S,x,A,L={}){let{lowS:C,prehash:R,format:N}=Ta(L,b);if(A=H(A,void 0,"publicKey"),x=Z(x,R),!Zt(S)){let z=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}D(S,N);try{let z=I.fromBytes(S,N),G=t.fromBytes(A);if(C&&z.hasHighS())return!1;let{r:K,s:de}=z,me=B(x),ye=a.inv(de),ue=a.create(me*ye),De=a.create(K*ye),mr=t.BASE.multiplyUnsafe(ue).add(G.multiplyUnsafe(De));return mr.is0()?!1:a.create(mr.x)===K}catch{return!1}}function _(S,x,A={}){let{prehash:L}=Ta(A,b);return x=Z(x,L),I.fromBytes(S,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:p,Point:t,sign:y,verify:w,recoverPublicKey:_,Signature:I,hash:n})}var La={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},m0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gf=BigInt(2);function y0(t){let e=La.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=te(l,r,e)*l%e,m=te(f,r,e)*l%e,d=te(m,gf,e)*u%e,p=te(d,s,e)*d%e,b=te(p,o,e)*p%e,h=te(b,a,e)*b%e,g=te(h,c,e)*h%e,E=te(g,a,e)*b%e,v=te(E,r,e)*l%e,D=te(v,i,e)*p%e,I=te(D,n,e)*u%e,P=te(I,gf,e);if(!Ca.eql(Ca.sqr(P),t))throw new Error("Cannot find square root");return P}var Ca=Br(La.p,{sqrt:y0}),g0=hf(La,{Fp:Ca,endo:m0}),zr=yf(g0,Tr);function bf(t,e,r,n){let s=vr.digest(r instanceof Uint8Array?r:r.subarray());if(Ao(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),zr.verify(e,o,t,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new En(String(o))});try{return n?.signal?.throwIfAborted(),zr.verify(e,s.digest,t,{prehash:!1,format:"der"})}catch(o){throw new En(String(o))}}var No=class{type="secp256k1";raw;_key;constructor(e){this._key=xf(e),this.raw=wf(this._key)}toMultihash(){return Ve.digest(et(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){return bf(this._key,r,e,n)}};function Ba(t){return new No(t)}function wf(t){return zr.Point.fromBytes(t).toBytes()}function xf(t){try{return zr.Point.fromBytes(t),t}catch(e){throw new yr(String(e))}}function Ef(t,e){let{Type:r,Data:n}=ot.decode(t),s=n??new Uint8Array;switch(r){case ne.RSA:return va(s,e);case ne.Ed25519:return Fi(s);case ne.secp256k1:return Ba(s);case ne.ECDSA:return oi(s);default:throw new gr}}function Sf(t){let{Type:e,Data:r}=ot.decode(t.digest),n=r??new Uint8Array;switch(e){case ne.Ed25519:return Fi(n);case ne.secp256k1:return Ba(n);case ne.ECDSA:return oi(n);default:throw new gr}}function et(t){return ot.encode({Type:ne[t.type],Data:t.raw})}var vf=Symbol.for("nodejs.util.inspect.custom"),b0=114,On=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()})`}[Cs]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return fe.createV1(b0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return he(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return he(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[vf](){return`PeerId(${this.toString()})`}},Fo=class extends On{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Uo=class extends On{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Mo=class extends On{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},w0=2336,Pn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ve.digest(k(this.url))}[vf](){return`PeerId(${this.url})`}[Cs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return fe.createV1(w0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};var x0=114,_f=2336;function Ra(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Je(re.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return E0(fe.parse(t));if(e==null)throw new se('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Je(e.decode(t))}return Vr(r)}function Vr(t){if(v0(t))return new Fo({multihash:t});if(S0(t))try{let e=Sf(t);if(e.type==="Ed25519")return new Uo({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Mo({multihash:t,publicKey:e})}catch{let r=V(t.digest);return new Pn(new URL(r))}throw new Xn("Supplied PeerID Multihash is invalid")}function E0(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==x0&&t.code!==_f)throw new Zn("Supplied PeerID CID is invalid");if(t.code===_f){let e=V(t.multihash.digest);return new Pn(new URL(e))}return Vr(t.multihash)}function S0(t){return t.code===Ve.code}function v0(t){return t.code===vr.code}function Af(t=0){return new Uint8Array(t)}var _0=Math.pow(2,7),A0=Math.pow(2,14),T0=Math.pow(2,21),I0=Math.pow(2,28),D0=Math.pow(2,35),C0=Math.pow(2,42),L0=Math.pow(2,49),Ne=128;function Oa(t){if(t<_0)return 1;if(t<A0)return 2;if(t<T0)return 3;if(t<I0)return 4;if(t<D0)return 5;if(t<C0)return 6;if(t<L0)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function B0(t,e,r=0){switch(Oa(t)){case 8:e[r++]=t&255|Ne,t/=128;case 7:e[r++]=t&255|Ne,t/=128;case 6:e[r++]=t&255|Ne,t/=128;case 5:e[r++]=t&255|Ne,t/=128;case 4:e[r++]=t&255|Ne,t>>>=7;case 3:e[r++]=t&255|Ne,t>>>=7;case 2:e[r++]=t&255|Ne,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function R0(t,e,r=0){switch(Oa(t)){case 8:e.set(r++,t&255|Ne),t/=128;case 7:e.set(r++,t&255|Ne),t/=128;case 6:e.set(r++,t&255|Ne),t/=128;case 5:e.set(r++,t&255|Ne),t/=128;case 4:e.set(r++,t&255|Ne),t>>>=7;case 3:e.set(r++,t&255|Ne),t>>>=7;case 2:e.set(r++,t&255|Ne),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function ko(t,e,r=0){return e==null&&(e=Af(Oa(t))),e instanceof Uint8Array?B0(t,e,r):R0(t,e,r)}var Nn;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:Te(0),payloadType:Te(0),payload:Te(0),signature:Te(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(Nn||(Nn={}));var Ko=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Fn=class t{static createFromProtobuf=e=>{let r=Nn.decode(e),n=Ef(r.publicKey);return new t({publicKey:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(e,r,n)=>{if(r==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=Tf(s,o,i),c=await r.sign(a.subarray(),n);return new t({publicKey:r.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,r,n)=>{let s=t.createFromProtobuf(e);if(!await s.validate(r,n))throw new Ko("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:r,payloadType:n,payload:s,signature:o}=e;this.publicKey=r,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Nn.encode({publicKey:et(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:he(this.marshal(),e.marshal())}async validate(e,r){let n=Tf(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,r)}},Tf=(t,e,r)=>{let n=k(t),s=ko(n.byteLength),o=ko(e.length),i=ko(r.length);return new ee(s,n,o,e,i,r)};var P0=Math.pow(2,7),N0=Math.pow(2,14),F0=Math.pow(2,21),Pa=Math.pow(2,28),Na=Math.pow(2,35),Fa=Math.pow(2,42),Ua=Math.pow(2,49),oe=128,ve=127;function Hr(t){if(t<P0)return 1;if(t<N0)return 2;if(t<F0)return 3;if(t<Pa)return 4;if(t<Na)return 5;if(t<Fa)return 6;if(t<Ua)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ma(t,e,r=0){switch(Hr(t)){case 8:e[r++]=t&255|oe,t/=128;case 7:e[r++]=t&255|oe,t/=128;case 6:e[r++]=t&255|oe,t/=128;case 5:e[r++]=t&255|oe,t/=128;case 4:e[r++]=t&255|oe,t>>>=7;case 3:e[r++]=t&255|oe,t>>>=7;case 2:e[r++]=t&255|oe,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function U0(t,e){let r=t[e],n=0;if(n+=r&ve,r<oe||(r=t[e+1],n+=(r&ve)<<7,r<oe)||(r=t[e+2],n+=(r&ve)<<14,r<oe)||(r=t[e+3],n+=(r&ve)<<21,r<oe)||(r=t[e+4],n+=(r&ve)*Pa,r<oe)||(r=t[e+5],n+=(r&ve)*Na,r<oe)||(r=t[e+6],n+=(r&ve)*Fa,r<oe)||(r=t[e+7],n+=(r&ve)*Ua,r<oe))return n;throw new RangeError("Could not decode varint")}function M0(t,e){let r=t.get(e),n=0;if(n+=r&ve,r<oe||(r=t.get(e+1),n+=(r&ve)<<7,r<oe)||(r=t.get(e+2),n+=(r&ve)<<14,r<oe)||(r=t.get(e+3),n+=(r&ve)<<21,r<oe)||(r=t.get(e+4),n+=(r&ve)*Pa,r<oe)||(r=t.get(e+5),n+=(r&ve)*Na,r<oe)||(r=t.get(e+6),n+=(r&ve)*Fa,r<oe)||(r=t.get(e+7),n+=(r&ve)*Ua,r<oe))return n;throw new RangeError("Could not decode varint")}function ka(t,e=0){return t instanceof Uint8Array?U0(t,e):M0(t,e)}var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},bt=class extends Error{static name="ValidationError";name="ValidationError"},qo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},zo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Vo=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(o*=e,o+=l,o>u||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let s=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[s]=i[0],r[s+1]=i[1],r[s+2]=i[2],r[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];r[s]=o>>8,r[s+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,s]=e(r);if(n===16)return r;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var K0=45,q0=15,Ho=new Vo;function If(t){if(!(t.length>q0))return Ho.new(t).parseWith(()=>Ho.readIPv4Addr())}function Df(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>K0))return Ho.new(t).parseWith(()=>Ho.readIPv6Addr())}function $o(t){return!!If(t)}function Cf(t){return!!Df(t)}function qa(t){return e=>V(e,t)}function za(t){return e=>k(e,t)}function $r(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function ir(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Lf(t){let e=t.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 r=k(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ir(n);return tr([r,s],r.length+s.length)}function Bf(t){let e=t.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 r=vt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ir(n);return tr([r,s],r.length+s.length)}function Va(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=V(e,"base32"),s=$r(r);return`${n}:${s}`}var Ha=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let s=parseInt(r,10);if(isNaN(s)||s<0||s>255)throw new Ee("Invalid byte value in IP address");e[n]=s}),e},Rf=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let o=$o(r[n]),i;o&&(i=Ha(r[n]),r[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,V(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let s=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let o=parseInt(r[n],16);if(isNaN(o)||o<0||o>65535)throw new Ee("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},Of=function(t){if(t.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},Pf=function(t){if(t.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let s=t[n],o=t[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}};function Nf(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}}var Ka=Object.values(an).map(t=>t.decoder),z0=(function(){let t=Ka[0].or(Ka[1]);return Ka.slice(2).forEach(e=>t=t.or(e)),t})();function Ff(t){return z0.decode(t)}function Uf(t){return e=>t.encoder.encode(e)}function V0(t){if(parseInt(t).toString()!==t)throw new bt("Value must be an integer")}function H0(t){if(t<0)throw new bt("Value must be a positive integer, or zero")}function $0(t){return e=>{if(e>t)throw new bt(`Value must be smaller than or equal to ${t}`)}}function j0(...t){return e=>{for(let r of t)r(e)}}var Un=j0(V0,H0,$0(65535));var be=-1,$a=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new zo(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},xt=new $a,iy=[{code:4,name:"ip4",size:32,valueToBytes:Ha,bytesToValue:Of,validate:t=>{if(!$o(t))throw new bt(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ir,bytesToValue:$r,validate:Un},{code:273,name:"udp",size:16,valueToBytes:ir,bytesToValue:$r,validate:Un},{code:33,name:"dccp",size:16,valueToBytes:ir,bytesToValue:$r,validate:Un},{code:41,name:"ip6",size:128,valueToBytes:Rf,bytesToValue:Pf,stringToValue:Nf,validate:t=>{if(!Cf(t))throw new bt(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:be},{code:43,name:"ipcidr",size:8,bytesToValue:qa("base10"),valueToBytes:za("base10")},{code:53,name:"dns",size:be},{code:54,name:"dns4",size:be},{code:55,name:"dns6",size:be},{code:56,name:"dnsaddr",size:be},{code:132,name:"sctp",size:16,valueToBytes:ir,bytesToValue:$r,validate:Un},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:be,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:be,bytesToValue:qa("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?za("base58btc")(t):fe.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Va,valueToBytes:Lf},{code:445,name:"onion3",size:296,bytesToValue:Va,valueToBytes:Bf},{code:446,name:"garlic64",size:be},{code:447,name:"garlic32",size:be},{code:448,name:"tls"},{code:449,name:"sni",size:be},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:be,bytesToValue:Uf($s),valueToBytes:Ff},{code:480,name:"http"},{code:481,name:"http-path",size:be,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:be}];iy.forEach(t=>{xt.addProtocol(t)});function Mf(t){let e=[],r=0;for(;r<t.length;){let n=ka(t,r),s=xt.getProtocol(n),o=Hr(n),i=ay(s,t,r+o),a=0;i>0&&s.size===be&&(a=Hr(i));let c=o+a+i,u={code:n,name:s.name,bytes:Fe(t.subarray(r,r+c))};if(i>0){let l=r+o+a,f=t.subarray(l,l+i);u.value=s.bytesToValue?.(f)??V(f)}e.push(u),r+=c}return e}function kf(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let s=xt.getProtocol(n.code),o=Hr(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??k(n.value),a=i.byteLength,s.size===be&&(c=Hr(a)));let u=new Uint8Array(o+c+a),l=0;Ma(n.code,u,l),l+=o,i!=null&&(s.size===be&&(Ma(a,u,l),l+=c),u.set(i,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return tr(r,e)}function Kf(t){if(t.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],r="protocol",n="",s="";for(let o=1;o<t.length;o++){let i=t.charAt(o);i!=="/"&&(r==="protocol"?s+=t.charAt(o):n+=t.charAt(o));let a=o===t.length-1;if(i==="/"||a){let c=xt.getProtocol(s);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",r="protocol";continue}else if(a)throw new Ee(`Component ${s} was missing value`);r="value"}else if(r==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${s} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",s="",r="protocol"}}}if(s!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function qf(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=xt.getProtocol(e.code);if(r==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function ay(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:ka(e,r)}var cy=Symbol.for("nodejs.util.inspect.custom"),cc=Symbol.for("@multiformats/multiaddr");function uy(t){if(t==null&&(t="/"),zf(t))return t.getComponents();if(t instanceof Uint8Array)return Mf(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Kf(t);if(Array.isArray(t))return t;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Zo=class t{[cc]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=uy(e),r.validate!==!1&&ly(this)}get bytes(){return this.#r==null&&(this.#r=kf(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=qf(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),s=n.lastIndexOf(r);if(s<0)throw new qo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,s),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return he(this.bytes,e.bytes)}[cy](){return`Multiaddr(${this.toString()})`}};function ly(t){t.getComponents().forEach(e=>{let r=xt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function zf(t){return!!t?.[cc]}function ke(t){return new Zo(t)}var uc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Vf={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Hf=new globalThis.TextEncoder;function fy(t,e){let r=uc[e],n=Vf[e];for(let s=0;s<t.length;s++)n^=BigInt(t[s]),n=BigInt.asUintN(e,n*r);return n}function dy(t,e,r){if(r.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=uc[e],s=Vf[e],o=t;for(;o.length>0;){let i=Hf.encodeInto(o,r);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(r[a]),s=BigInt.asUintN(e,s*n)}return s}function lc(t,{size:e=32,utf8Buffer:r}={}){if(!uc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof t=="string"){if(r)return dy(t,e,r);t=Hf.encode(t)}return fy(t,e)}var Mn={hash:t=>Number(lc(t,{size:32})),hashV:(t,e)=>hy(Mn.hash(t,e))};function hy(t){let e=t.toString(16);return e.length%2===1&&(e=`0${e}`),k(e,"base16")}var fc=64,Ze=class{fp;h;seed;constructor(e,r,n,s=2){if(s>fc)throw new TypeError("Invalid Fingerprint Size");let o=r.hashV(e,n),i=Te(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?he(this.fp,e.fp):!1}};function ur(t,e){return Math.floor(Math.random()*(e-t))+t}var lr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ze))throw new TypeError("Invalid Fingerprint");return this.contents.some(r=>e.equals(r))}add(e){if(!(e instanceof Ze))throw new TypeError("Invalid Fingerprint");for(let r=0;r<this.contents.length;r++)if(this.contents[r]==null)return this.contents[r]=e,!0;return!0}swap(e){if(!(e instanceof Ze))throw new TypeError("Invalid Fingerprint");let r=ur(0,this.contents.length-1),n=this.contents[r];return this.contents[r]=e,n}remove(e){if(!(e instanceof Ze))throw new TypeError("Invalid Fingerprint");let r=this.contents.findIndex(n=>e.equals(n));return r>-1?(this.contents[r]=null,!0):!1}};var py=500,kn=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??Mn,this.seed=e.seed??ur(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=k(e));let r=new Ze(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^r.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new lr(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new lr(this.bucketSize)),this.buckets[n].add(r)||this.buckets[s].add(r))return this.count++,!0;let o=[n,s],i=o[ur(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize));for(let a=0;a<py;a++){let c=this.buckets[i].swap(r);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=k(e));let r=new Ze(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(r)??!1;if(s)return s;let o=(n^r.hash())%this.filterSize;return this.buckets[o]?.has(r)??!1}remove(e){typeof e=="string"&&(e=k(e));let r=new Ze(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(r)??!1;if(s)return this.count--,s;let o=(n^r.hash())%this.filterSize,i=this.buckets[o]?.remove(r)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},my={1:.5,2:.84,4:.95,8:.98};function yy(t=.001){return t>.002?2:t>1e-5?4:8}function $f(t,e=.001){let r=yy(e),n=my[r],s=Math.round(t/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*r)),fc);return{filterSize:s,bucketSize:r,fingerprintSize:o}}var Xo=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??Mn,this.seed=e.seed??ur(0,Math.pow(2,10)),this.filterSeries=[new kn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=k(e)),this.has(e))return!0;let r=this.filterSeries.find(n=>n.reliable);if(r==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);r=new kn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(r)}return r.add(e)}has(e){typeof e=="string"&&(e=k(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=k(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,r)=>e+r.count,0)}};function Yr(t,e=.001,r){return new Xo({...$f(t,e),...r??{}})}var X=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),O=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),jf=t=>({match:e=>t.match(e)===!1?e:!1}),q=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),_e=(...t)=>({match:e=>{let r;for(let n of t){let s=n.match(e);s!==!1&&(r==null||s.length<r.length)&&(r=s)}return r??!1}}),$=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function Q(...t){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of t){let a=i.match(o);if(a===!1)return!1;o=a}return o}function r(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:t,matches:r,exactMatch:n}}var gy=O(421),Tv=Q(gy),Jo=O(54),es=O(55),ts=O(56),hc=O(53),Iv=Q(Jo,q(O(421))),Dv=Q(es,q(O(421))),Cv=Q(ts,q(O(421))),Lv=Q(_e(hc,ts,Jo,es),q(O(421))),Gf=$(O(4),q(O(43))),Wf=$(q(O(42)),O(41),q(O(43))),pc=_e(Gf,Wf),Zr=_e(pc,hc,Jo,es,ts),Bv=Q(_e(pc,$(_e(hc,ts,Jo,es),q(O(421))))),Rv=Q(Gf),Ov=Q(Wf),Pv=Q(pc),mc=$(Zr,O(6)),Kn=$(Zr,O(273)),Nv=Q($(mc,q(O(421)))),Fv=Q(Kn),yc=$(Kn,X(460),q(O(421))),rs=$(Kn,X(461),q(O(421))),by=_e(yc,rs),Uv=Q(yc),Mv=Q(rs),dc=_e(Zr,mc,Kn,yc,rs),Yf=_e($(dc,X(477),q(O(421)))),kv=Q(Yf),Zf=_e($(dc,X(478),q(O(421))),$(dc,X(448),q(O(449)),X(477),q(O(421)))),Kv=Q(Zf),Xf=$(Kn,X(280),q(O(466)),q(O(466)),q(O(421))),qv=Q(Xf),Qf=$(rs,X(465),q(O(466)),q(O(466)),q(O(421))),zv=Q(Qf),Qo=_e(Yf,Zf,$(mc,q(O(421))),$(by,q(O(421))),$(Zr,q(O(421))),Xf,Qf,O(421)),Jf=Q(Qo),wy=$(q(Qo),X(290),jf(X(281)),q(O(421))),fr=Q(wy),xy=_e($(Qo,X(290),X(281),q(O(421))),$(Qo,X(281),q(O(421))),$(X(281),q(O(421)))),Vv=Q(xy),Ey=$(Zr,_e($(O(6,"80")),$(O(6),X(480)),X(480)),q(O(481)),q(O(421))),Hv=Q(Ey),Sy=$(Zr,_e($(O(6,"443")),$(O(6,"443"),X(480)),$(O(6),X(443)),$(O(6),X(448),X(480)),$(X(448),X(480)),X(448),X(443)),q(O(481)),q(O(421))),$v=Q(Sy),vy=_e($(O(777),q(O(421)))),jv=Q(vy),_y=_e($(O(400),q(O(421)))),Gv=Q(_y);function Xe(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var ns=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}},Xr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ns(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 r=this.head;this.head=r.next=new ns(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var gc=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Mt(t={}){return Ay(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Ay(t,e){e=e??{};let r=e.onEnd,n=new Xr,s,o,i,a=Xe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{o=E=>{o=null,n.push(E);try{h(t(n))}catch(v){g(v)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Xe()})}},u=h=>o!=null?o(h):(n.push(h),s),l=h=>(n=new Xr,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},m=h=>i?s:(i=!0,h!=null?l(h):u({done:!0})),d=()=>(n=new Xr,m(),{done:!0}),p=h=>(m(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:m,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,v;g!=null&&(E=new Promise((D,I)=>{v=()=>{I(new gc)},g.addEventListener("abort",v)}));try{await Promise.race([a.promise,E])}finally{v!=null&&g!=null&&g?.removeEventListener("abort",v)}}},r==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return b.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(h){return b.end(h),r!=null&&(r(h),r=void 0),s},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},s}var bc=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},ed=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function wc(t,e){let{milliseconds:r,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,m)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){m(ed(i));return}if(i&&(c=()=>{m(ed(i))},i.addEventListener("abort",c,{once:!0})),t.then(f,m),r===Number.POSITIVE_INFINITY)return;let d=new bc;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){m(p)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?f():s instanceof Error?m(s):(d.message=s??`Promise timed out after ${r} milliseconds`,m(d))},r)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}var Ty=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Iy(t,e,r){let n,s=new Promise((o,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=Ty(t),f=async(...d)=>{let p=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(p))return}catch(b){n(),i(b);return}c.push(p),r.count===c.length&&(n(),o(c))},m=(...d)=>{n(),i(r.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)l(d,f);for(let d of r.rejectionEvents)a.includes(d)||l(d,m)};for(let d of a)u(d,f);for(let d of r.rejectionEvents)a.includes(d)||u(d,m);r.signal&&r.signal.addEventListener("abort",()=>{m(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(c)});if(s.cancel=n,typeof r.timeout=="number"){let o=wc(s,{milliseconds:r.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function it(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Iy(t,e,r),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function xc(t,e){let r,n=function(){let s=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var os=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},dr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var ss=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Dy(t){return t.reason}async function kt(t,e,r){if(e==null)return t;let n=r?.translateError??Dy;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([t,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var is=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Xe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new at)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Cy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var as=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,r){this.id=Cy(),this.status="queued",this.fn=e,this.options=r,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((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new at),this.cleanup())}async join(e){let r=new is(e);return this.recipients.push(r),e?.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await kt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:r=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(r)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var cs=class extends Ce{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=xc(this.emitEmpty.bind(this),1),this.emitIdle=xc(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 r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,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,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new os;let n=new as(e,r);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(r).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new at)}),this.clear()}async onEmpty(e){this.size!==0&&await it(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await it(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await it(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 r=Mt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},s=c=>{c.detail!=null&&r.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new at("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ly=Math.pow(2,20)*4,us=class extends Ce{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Ly,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ee,this.writeBuffer=new ee,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=s=>{this.onDrainPromise?.reject(s.error??new ss)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),kt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Mt(),r=o=>{e.push(o.data)};this.addEventListener("message",r);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Et(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new to(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Et("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Et("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Et(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Et(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Yn;this.dispatchEvent(new ro(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new br))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new ee(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new eo(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new en(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new en(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ls=class extends us{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await it(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await it(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function fs(t){let e=new globalThis.AbortController;function r(){let o=t.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let s=e.signal;return s.clear=n,s}function td(t=0){return new Uint8Array(t)}var By=Math.pow(2,7),Ry=Math.pow(2,14),Oy=Math.pow(2,21),Ec=Math.pow(2,28),Sc=Math.pow(2,35),vc=Math.pow(2,42),_c=Math.pow(2,49),W=128,Ae=127;function qn(t){if(t<By)return 1;if(t<Ry)return 2;if(t<Oy)return 3;if(t<Ec)return 4;if(t<Sc)return 5;if(t<vc)return 6;if(t<_c)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Py(t,e,r=0){switch(qn(t)){case 8:e[r++]=t&255|W,t/=128;case 7:e[r++]=t&255|W,t/=128;case 6:e[r++]=t&255|W,t/=128;case 5:e[r++]=t&255|W,t/=128;case 4:e[r++]=t&255|W,t>>>=7;case 3:e[r++]=t&255|W,t>>>=7;case 2:e[r++]=t&255|W,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ny(t,e,r=0){switch(qn(t)){case 8:e.set(r++,t&255|W),t/=128;case 7:e.set(r++,t&255|W),t/=128;case 6:e.set(r++,t&255|W),t/=128;case 5:e.set(r++,t&255|W),t/=128;case 4:e.set(r++,t&255|W),t>>>=7;case 3:e.set(r++,t&255|W),t>>>=7;case 2:e.set(r++,t&255|W),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Fy(t,e){let r=t[e],n=0;if(n+=r&Ae,r<W||(r=t[e+1],n+=(r&Ae)<<7,r<W)||(r=t[e+2],n+=(r&Ae)<<14,r<W)||(r=t[e+3],n+=(r&Ae)<<21,r<W)||(r=t[e+4],n+=(r&Ae)*Ec,r<W)||(r=t[e+5],n+=(r&Ae)*Sc,r<W)||(r=t[e+6],n+=(r&Ae)*vc,r<W)||(r=t[e+7],n+=(r&Ae)*_c,r<W))return n;throw new RangeError("Could not decode varint")}function Uy(t,e){let r=t.get(e),n=0;if(n+=r&Ae,r<W||(r=t.get(e+1),n+=(r&Ae)<<7,r<W)||(r=t.get(e+2),n+=(r&Ae)<<14,r<W)||(r=t.get(e+3),n+=(r&Ae)<<21,r<W)||(r=t.get(e+4),n+=(r&Ae)*Ec,r<W)||(r=t.get(e+5),n+=(r&Ae)*Sc,r<W)||(r=t.get(e+6),n+=(r&Ae)*vc,r<W)||(r=t.get(e+7),n+=(r&Ae)*_c,r<W))return n;throw new RangeError("Could not decode varint")}function rd(t,e,r=0){return e==null&&(e=td(qn(t))),e instanceof Uint8Array?Py(t,e,r):Ny(t,e,r)}function nd(t,e=0){return t instanceof Uint8Array?Fy(t,e):Uy(t,e)}var Ac=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Xe(),this.haveNext=Xe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Xe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Xe(),await kt(this.readNext.promise,r?.signal,r)}};function od(){return new Ac}function ky(t){return t[Symbol.asyncIterator]!=null}async function Ky(t,e,r){try{await Promise.all(t.map(async n=>{for await(let s of n)await e.push(s,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*qy(t){let e=new AbortController,r=od();Ky(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*zy(t){for(let e of t)yield*e}function Vy(...t){let e=[];for(let r of t)ky(r)||e.push(r);return e.length===t.length?zy(e):qy(t)}var sd=Vy;function id(t,...e){if(t==null)throw new Error("Empty pipeline");if(Tc(t)){let n=t;t=()=>n.source}else if(cd(t)||ad(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Tc(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Tc(r[n])&&(r[n]=$y(r[n]));return Hy(...r)}var Hy=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},ad=t=>t?.[Symbol.asyncIterator]!=null,cd=t=>t?.[Symbol.iterator]!=null,Tc=t=>t==null?!1:t.sink!=null&&t.source!=null,$y=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Mt({objectMode:!0});r.then(()=>{n.end()},i=>{n.end(i)});let s,o=t.source;if(ad(o))s=async function*(){yield*o,n.end()};else if(cd(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sd(n,s())}return t.source};var jy=4194304,ds=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Dc=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Cc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Lc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Gy(t){return typeof t?.closeRead=="function"}function Wy(t){return typeof t?.close=="function"}function Ic(t){return Gy(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:Wy(t)?t.status!=="open":!1}function Yy(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Zy(t,e){let r=e?.maxBufferSize??jy,n=new ee,s,o=!1;if(!Yy(t))throw new se("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}s?.resolve()};t.addEventListener("message",i);let a=l=>{l.error!=null?s?.reject(l.error):s?.resolve()};t.addEventListener("close",a);let c=()=>{s?.resolve()};t.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(o===!0)throw new ds("Stream was unwrapped");if(Ic(t)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new dr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await kt(s.promise,l?.signal),Ic(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}s=Promise.withResolvers()}let m=l?.bytes??n.byteLength;if(n.byteLength<m){if(Ic(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,m),new dr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return u.read(l)}let d=n.sublist(0,m);return n.consume(m),d},async write(l,f){if(o===!0)throw new ds("Stream was unwrapped");t.send(l)||await it(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return u}function Xy(t,e={}){let r=Zy(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=qn(e.maxDataLength));let n=e?.lengthDecoder??nd,s=e?.lengthEncoder??rd;return{async read(i){let a=-1,c=new ee;for(;;){let l=await r.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 Dc("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Lc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Cc(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new dr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new dr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new ee(s(i.byteLength),i),a)},async writeV(i,a){let c=new ee(...i.flatMap(u=>[s(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function Kt(t,e){let r=Xy(t,e),n={read:async(s,o)=>{let i=await r.read(o);return s.decode(i)},write:async(s,o,i)=>{await r.write(o.encode(s),i)},writeV:async(s,o,i)=>{await r.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}function Qy(t){return t?.addEventListener!=null}function Jy(t){let e=Mt(),r,n=i=>{e.push(i.data)},s=()=>{e.end(),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&r?.reject(i.error),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",s)};return t.addEventListener("message",n),t.addEventListener("close",o,{once:!0}),t.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){r=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),r.promise]);if(t.writeStatus==="closing"||t.writeStatus==="closed"||(l!=null&&(t.send(l)||await Promise.race([it(t,"drain",{rejectionEvents:["close"]})])),u===!0))break}await t.close()}}}function ud(...t){let e=t.map(r=>Qy(r)?Jy(r):r);return id(...e)}var Qr=class extends cs{has(e){return this.find(e)!=null}find(e){return this.queue.find(r=>e.equals(r.options.peerId))}};var Bc=1e3,ld=60*Bc,fd=15,dd=120*ld,hd=1,hs=5e3,pd=100,Rc="circuit-relay-source",zn=`${$c}-circuit-relay`,md=2*ld,yd=BigInt(1<<17),ze="/libp2p/circuit/relay/0.2.0/hop",hr="/libp2p/circuit/relay/0.2.0/stop",gd=30*Bc,e_=30*Bc,Vn=300,bd=4096,wd=.001;var Y;(function(t){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(r||(r={})),(function(a){a.codec=()=>or(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Pe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),qt.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),Hn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),zt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),M.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.peer=qt.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.reservation=Hn.codec().decode(a,a.uint32(),{limits:u.limits?.reservation});break}case 4:{l.limit=zt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 5:{l.status=M.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*qt.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*Hn.codec().stream(a,a.uint32(),`${u}.reservation`,{limits:l.limits?.reservation});break}case 4:{yield*zt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 5:{yield{field:`${u}.status`,value:M.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Re(a,t.codec())}t.encode=s;function o(a,c){return Be(a,t.codec(),c)}t.decode=o;function i(a,c){return Oe(a,t.codec(),c)}t.stream=i})(Y||(Y={}));var Ke;(function(t){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(r||(r={})),(function(a){a.codec=()=>or(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Pe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),qt.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),zt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),M.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.peer=qt.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.limit=zt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 4:{l.status=M.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*qt.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*zt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 4:{yield{field:`${u}.status`,value:M.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Re(a,t.codec())}t.encode=s;function o(a,c){return Be(a,t.codec(),c)}t.decode=o;function i(a,c){return Oe(a,t.codec(),c)}t.stream=i})(Ke||(Ke={}));var qt;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:Te(0),addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new sr('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new sr('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(qt||(qt={}));var Hn;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),$n.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new sr('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=$n.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new sr('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}case 3:{yield*$n.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(Hn||(Hn={}));var zt;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(zt||(zt={}));var M;(function(t){t.UNUSED="UNUSED",t.OK="OK",t.RESERVATION_REFUSED="RESERVATION_REFUSED",t.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",t.PERMISSION_DENIED="PERMISSION_DENIED",t.CONNECTION_FAILED="CONNECTION_FAILED",t.NO_RESERVATION="NO_RESERVATION",t.MALFORMED_MESSAGE="MALFORMED_MESSAGE",t.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(M||(M={}));var Oc;(function(t){t[t.UNUSED=0]="UNUSED",t[t.OK=100]="OK",t[t.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",t[t.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",t[t.PERMISSION_DENIED=202]="PERMISSION_DENIED",t[t.CONNECTION_FAILED=203]="CONNECTION_FAILED",t[t.NO_RESERVATION=204]="NO_RESERVATION",t[t.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",t[t.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Oc||(Oc={}));(function(t){t.codec=()=>or(Oc)})(M||(M={}));var pr;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:Te(0),peer:Te(0),expiration:0n},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})(pr||(pr={}));var $n;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),pr.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:Te(0),payloadType:Te(0),signature:Te(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=pr.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*pr.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Re(o,t.codec())}t.encode=r;function n(o,i){return Be(o,t.codec(),i)}t.decode=n;function s(o,i){return Oe(o,t.codec(),i)}t.stream=s})($n||($n={}));var ps=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},ms=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},jn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},ys=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},gs=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function xd(t,e,r){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&t.abort(new ps(`data limit of ${n} bytes exceeded`))};t.addEventListener("message",s)}function Ed(t,e,r,n,s){function o(l){t.abort(l),e.abort(l)}let i=[r,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=fs(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;r.aborted?l=r.reason:l=new ms(`duration limit of ${n.limit?.duration} ms exceeded`),o(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(xd(e,c,s),xd(t,c,s)),ud(t,e,t).catch(l=>{o(l)}).finally(()=>{a.clear()})}function Pc(t){let e=t*BigInt(1e3),r=new Date().getTime();return Number(e-BigInt(r))}var Gn=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let r=this;Object.defineProperty(e,"bytes",{get(){return r.bytes}})}if(this.expires!=null){let r=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((r.expires??0)-Date.now())/1e3)}})}return e}},bs=Q($(Jf.matchers[0],X(290))),ws=Q(X(290));function xs(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return r}var Vt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return xs(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((r,n)=>{e(r.value,r.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),{key:e,value:r})}keys(){return xs(this.map.values(),e=>e.key)}values(){return xs(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Es=class{filter;constructor(e,r){this.filter=Yr(e,r)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Nc(t,e=.001){return new Es(t,e)}var Fc=class extends Vt{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Uc(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Fc({name:e,metrics:r}):n=new Vt,n}var Mc=class extends Error{type;code;constructor(e,r,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=r??"ABORT_ERR"}};function Sd(t,e){let r=new Mc(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(r)},o=AbortSignal.timeout(t);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??t),o.addEventListener("abort",()=>{n.abort(r)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var Ss=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=r.maxReservations??fd,this.applyDefaultLimit=r.applyDefaultLimit!==!1,this.reservationTtl=r.reservationTtl??dd,this.defaultDurationLimit=r.defaultDurationLimit??md,this.defaultDataLimit=r.defaultDataLimit??yd,this.reservations=Uc({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,r,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:M.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:r,expiry:o,limit:i,signal:Sd(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:M.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var vs=class t{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:r,expiration:n}){this.relay=e,this.peer=r,this.expiration=n}marshal(){return pr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof t)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var eg={maxOutboundStopStreams:Vn},_s=class extends Ce{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=r?.hopTimeout??gd,this.maxInboundHopStreams=r.maxInboundHopStreams,this.maxOutboundHopStreams=r.maxOutboundHopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??eg.maxOutboundStopStreams,this.reservationStore=new Ss(e,r.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(ze,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(ze),this.started=!1}async onHop(e,r){this.log("received circuit v2 hop protocol stream from %p",r.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=Kt(e);try{let i=await o.pb(Y).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:r,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Y).write({type:Y.Type.STATUS,status:M.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:r,connection:n},s){switch(this.log("received hop message"),r.type){case Y.Type.RESERVE:await this.handleReserve({stream:e,request:r,connection:n},s);break;case Y.Type.CONNECT:await this.handleConnect({stream:e,request:r,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",r.type,n.remotePeer),await e.pb(Y).write({type:Y.Type.STATUS,status:M.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:r},n){let s=e.pb(Y);if(this.log("hop reserve request from %p",r.remotePeer),fr.exactMatch(r.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",r.remotePeer),await s.write({type:Y.Type.STATUS,status:M.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(r.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",r.remotePeer),await s.write({type:Y.Type.STATUS,status:M.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(r.remotePeer,r.remoteAddr);try{if(o.status!==M.OK){await s.write({type:Y.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(r.remotePeer,{tags:{[Rc]:{value:1,ttl:i}}},n)}await s.write({type:Y.Type.STATUS,status:M.OK,reservation:await this.makeReservation(r.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(r.remotePeer)?.limit},n),this.log("sent confirmation response to %s",r.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",r.remotePeer,i),this.reservationStore.removeReservation(r.remotePeer);try{await this.components.peerStore.merge(r.remotePeer,{tags:{[Rc]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",r.remotePeer,a)}}}async makeReservation(e,r){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await Fn.seal(new vs({peer:e,relay:this.components.peerId,expiration:r}),this.components.privateKey);return{addrs:n,expire:r,voucher:{publicKey:et(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:r},signature:s.signature}}}async handleConnect({stream:e,request:r,connection:n},s){let o=e.pb(Y);if(fr.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Y.Type.STATUS,status:M.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(r.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");r.peer.addrs.forEach(ke),i=Vr(Je(r.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:Y.Type.STATUS,status:M.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,M.NO_RESERVATION),await o.write({type:Y.Type.STATUS,status:M.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Y.Type.STATUS,status:M.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Y.Type.STATUS,status:M.NO_RESERVATION},s);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:Ke.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await o.write({type:Y.Type.STATUS,status:M.CONNECTION_FAILED},s);return}await o.write({type:Y.Type.STATUS,status:M.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Ed(e.unwrap(),l,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:r},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(hr,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Kt(s),i=o.pb(Ke);await i.write(r,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===M.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Ht=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var As=class extends Ce{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(ze,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ze)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=vd(n),i=vd(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let r=this.queue=new Qr({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),r.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}r.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await r.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,r.size,r.running),r.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await r.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(r=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,r)})}async maybeDialPeer(e){if(this.queue==null)return;let r=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(r)){this.log.trace("random peer %p was already in queue",r);return}if(this.components.connectionManager.getConnections(r)?.length>0){this.log.trace("random peer %p was already connected",r);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",r);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:r}){let n=fs([AbortSignal.timeout(5e3),r]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function vd(t){let e=t.metadata.get("last-dial-success");return e==null?0:new Date(V(e)).getTime()}var Kc=class extends Ce{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=r.listenTimeout??hs,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(r=>{this.addressManager.removeObservedAddr(r)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:r}=e.detail;r.type!=="configured"&&r.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(ws.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(bs.exactMatch(e)){this.log("listen on specific relay server %a",e);let r=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:r});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new $t(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(r=>ke(r).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(r=>{this.addressManager.confirmObservedAddr(r,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function _d(t){return new Kc(t)}var Ad="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Td=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Ad[r[t]&63];return e};var tg=60*1e3*10,rg=60*1e3*5,ng=30*1e3,Ts=class extends Ce{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,r){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Vt,this.pendingReservations=[],this.maxReservationQueueLength=r?.maxReservationQueueLength??pd,this.reservationCompletionTimeout=r?.reservationCompletionTimeout??hs,this.started=!1,this.relayFilter=Yr(100),this.reserveQueue=new Qr({concurrency:r?.reservationConcurrency??hd,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(zn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async r=>{await this.peerStore.merge(r.id,{tags:{[zn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async r=>this.addRelay(r.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Td();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,r){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new $t("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new gs("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new $t("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let p=this.connectionManager.getConnections(e),b=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(h=>h.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),b=!0),b&&Pc(o.reservation.expire)>tg)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(r==="discovered"&&this.pendingReservations.length===0)throw new jn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(fr.matches(a.remoteAddr))throw new ys("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),u=Pc(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+u).toString());let l=Math.min(Math.max(u-rg,ng),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,r).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},l),m;if(r==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new jn("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:r,connection:a.id,id:p}}else m={timeout:f,reservation:c,type:r,connection:a.id};this.reservations.set(e,m),await this.peerStore.merge(e,{tags:{[zn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(o){throw r==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((r,n)=>(n.type===e&&r++,r),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,r){r.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ze,r),o=Kt(n).pb(Y);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Y.Type.RESERVE},r);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(r)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(r)}if(this.log.trace("read response %s",i.status),i.status===M.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=ke(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=ke(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>ke(u).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let r=this.reservations.get(e);r!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(r.timeout),this.reservations.delete(e),r.type==="discovered"&&this.pendingReservations.push(r.id),await this.peerStore.merge(e,{tags:{[zn]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:r}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Yr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var qc=class extends ls{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",r=>{this.onTransportClosed(r.error)}),this.stream.addEventListener("remoteCloseWrite",r=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",r=>{e.onDataRead?.(r.data),this.onData(r.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function zc(t){return new qc(t)}var og=t=>{if(t.peer==null)return!1;try{t.peer.addrs.forEach(ke)}catch{return!1}return!0},Id={maxInboundStopStreams:Vn,maxOutboundStopStreams:Vn,stopTimeout:3e4},Is=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,r={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=r.maxInboundStopStreams??Id.maxInboundStopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??Id.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new As(e,{filter:r.discoveryFilter??Nc(bd,wd)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new Ts(e,r),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Xc]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Qc](){return this.discovery!=null?["@libp2p/identify"]:[]}[Zc]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(hr,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Gc(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Wc(this.discovery,this.reservationStore),await this.components.registrar.unhandle(hr),this.started=!1}async dial(e,r){let n=e.toString().split("/p2p-circuit"),s=ke(n[0]),o=ke(n[n.length-1]),i=s.getComponents().find(d=>d.code===421)?.value,a=o.getComponents().find(d=>d.code===421)?.value;if(i==null||a==null){let d=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new Jn(`C${d}`)}let c=Ra(i),u=Ra(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),r.onProgress?.(new Ht("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,r)):r.onProgress?.(new Ht("circuit-relay:reuse-connection"));let m;try{r.onProgress?.(new Ht("circuit-relay:open-hop-stream")),m=await f.newStream(ze,r);let d=Kt(m).pb(Y);r.onProgress?.(new Ht("circuit-relay:write-connect-message")),await d.write({type:Y.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[ke(o).bytes]}},r),r.onProgress?.(new Ht("circuit-relay:read-connect-response"));let p=await d.read(r);if(p.status!==M.OK)throw new Qn(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let b=new Gn(p.limit),h=zc({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:b.onData,onDataWrite:b.onData,log:m.log.newScope("circuit-relay:connection")}),g=await this.components.upgrader.upgradeOutbound(h,{...r,limits:b.getLimits()});return g.log("outbound relayed connection established to %p with limits %o, over connection %s",g.remotePeer,p.limit??"none",f.id),g}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,c,d),m?.abort(d),d}}createListener(e){return _d({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>bs.exactMatch(r)||ws.exactMatch(r))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>fr.exactMatch(r))}async onStop(e,r){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(r.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([r.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",f)}let s=Kt(e).pb(Ke),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",r.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",r.remotePeer),await s.write({type:Ke.Type.STATUS,status:M.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==Ke.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await s.write({type:Ke.Type.STATUS,status:M.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!og(o)){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await s.write({type:Ke.Type.STATUS,status:M.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Vr(Je(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(r.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",r.remotePeer),await s.write({type:Ke.Type.STATUS,status:M.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",r.remotePeer),await s.write({type:Ke.Type.STATUS,status:M.OK},{signal:n});let a=new Gn(o.limit),c=r.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=zc({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",r.id)}finally{n?.clear()}}};function sg(t={}){return e=>new _s(e,t)}function ig(t={}){return e=>new Is(e,t)}return Rd(ag);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: